<?php

namespace App\Exports;

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

class AttendanceExport 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.', 'Employee', 'Attendance Date', 'Check In', 'Check Out', 'Working Hours', 'Overtime Hours', 'Late Minutes', 'Status', 'Remarks'];
    }

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

        // Add serial numbers
        $sr = 1;
        return $data->map(function ($row) use (&$sr) {
            return [
                $sr++,
                strip_tags($row->employee ? $row->employee->first_name : ''), strip_tags($row->attendance_date), strip_tags($row->check_in), strip_tags($row->check_out), strip_tags($row->working_hours), strip_tags($row->overtime_hours), strip_tags($row->late_minutes), strip_tags($row->status), strip_tags($row->remarks)
            ];
        });
    }
}
