<?php

declare(strict_types=1);

namespace App\Exports;

use App\Models\Vacation;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class VacationsExport implements FromQuery, WithHeadings, WithMapping
{
    /**
     * @param  array<int, int>|null  $ids
     */
    public function __construct(
        private readonly ?array $ids = null,
    ) {}

    public function query(): Builder
    {
        $query = Vacation::query()->with(['employee', 'approver']);

        if ($this->ids !== null) {
            $query->whereIn('id', $this->ids);
        }

        return $query->orderByDesc('start_date');
    }

    /**
     * @return array<int, string>
     */
    public function headings(): array
    {
        return [
            'Employee Number',
            'Employee Name',
            'Type',
            'Start Date',
            'End Date',
            'Return Date',
            'Days',
            'Status',
            'Reason',
            'Approved By',
            'Approved At',
        ];
    }

    /**
     * @param  Vacation  $vacation
     * @return array<int, mixed>
     */
    public function map($vacation): array
    {
        return [
            $vacation->employee?->employee_number,
            $vacation->employee?->full_name,
            $vacation->type?->value,
            $vacation->start_date?->toDateString(),
            $vacation->end_date?->toDateString(),
            $vacation->return_date?->toDateString(),
            $vacation->days,
            $vacation->status?->value,
            $vacation->reason,
            $vacation->approver?->name,
            $vacation->approved_at?->toDateTimeString(),
        ];
    }
}
