<?php

namespace App\Exports;

use App\Models\PayrollItem;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class PayrollItemExport implements FromCollection, WithHeadings
{
    /**
     * Full download URL for picture / file / attachment / video paths (stored under public/images/).
     */
    protected function exportMediaUrl($path): string
    {
        if ($path === null || trim((string) $path) === '') {
            return '';
        }
        $path = strip_tags((string) $path);
        if (preg_match('#^https?://#i', $path)) {
            return $path;
        }
        return rtrim(config('app.url'), '/') . '/images/' . ltrim($path, '/');
    }

    /**
     * Headings for the export.
     */
    public function headings(): array
    {
        return ['Sr.', 'Client', 'Payroll', 'Item Type', 'Title', 'Amount', 'Status'];
    }

    /**
     * Collection of rows for Excel export.
     */
    public function collection()
    {
        $data = PayrollItem::with(['payroll'])
->latest('client_id')
->whereNull('deleted_at')
->get();

        // Add serial numbers
        $sr = 1;
        return $data->map(function ($row) use (&$sr) {
            return [
                $sr++,
                strip_tags($row->client_id), strip_tags($row->payroll ? $row->payroll->id : ''), strip_tags($row->item_type), strip_tags($row->title), strip_tags($row->amount), strip_tags($row->status)
            ];
        });
    }
}
