<?php
namespace App\Modules\HR\Reports\Exports;

use App\Modules\HR\Reports\Exports\Concerns\ProfessionalExcelStyles;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class EmployeeServicesExport implements FromCollection, WithHeadings, WithColumnWidths, WithStyles, WithTitle
{
    use ProfessionalExcelStyles;

    protected $data;

    public function __construct($data) { $this->data = $data['employees']; }

    public function title(): string { return 'Employee Services'; }

    public function headings(): array
    {
        return ['#', 'Emp Code', 'EPF No', 'Name', 'Department', 'Designation', 'Joining Date', 'Service As Of', 'Duration'];
    }

    public function collection()
    {
        return $this->data->values()->map(function ($emp, $i) {
            return [
                $i + 1,
                $emp->employee_code,
                $emp->epf_no,
                trim($emp->first_name . ' ' . ($emp->middle_name ?? '') . ' ' . $emp->last_name),
                optional($emp->department)->name,
                optional($emp->designation)->name,
                \Carbon\Carbon::parse($emp->date_of_joining)->format('Y-m-d'),
                $emp->service_to_date,
                $emp->service_duration,
            ];
        });
    }

    public function columnWidths(): array
    {
        return ['A'=>5,'B'=>14,'C'=>12,'D'=>32,'E'=>22,'F'=>22,'G'=>14,'H'=>14,'I'=>28];
    }

    public function styles(Worksheet $sheet)
    {
        $last = $this->data->count() + 1;
        $this->applyStyles($sheet, $last, 'I', ['A','G','H'], []);
        return [];
    }
}
