<?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 EmployeeTerminationExport implements FromCollection, WithHeadings, WithColumnWidths, WithStyles, WithTitle
{
    use ProfessionalExcelStyles;

    protected $data;

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

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

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

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

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

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