<?php

namespace App\Exports;

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

class PayrollExport 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', 'Employee', 'Payroll Month', 'Payroll Year', 'Basic Salary', 'Allowances', 'Deductions', 'Overtime Amount', 'Bonus', 'Tax', 'Gross Salary', 'Net Salary', 'Payment Status', 'Payment Date', 'Payslip', 'Status'];
    }

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

        // Add serial numbers
        $sr = 1;
        return $data->map(function ($row) use (&$sr) {
            return [
                $sr++,
                strip_tags($row->client ? $row->client->name : ''), strip_tags($row->employee ? $row->employee->first_name : ''), strip_tags($row->payroll_month), strip_tags($row->payroll_year), strip_tags($row->basic_salary), strip_tags($row->allowances), strip_tags($row->deductions), strip_tags($row->overtime_amount), strip_tags($row->bonus), strip_tags($row->tax), strip_tags($row->gross_salary), strip_tags($row->net_salary), strip_tags($row->payment_status), strip_tags($row->payment_date), $this->exportMediaUrl($row->payslip), strip_tags($row->status)
            ];
        });
    }
}
