<?php

declare(strict_types=1);

namespace App\Exports;

use App\Models\Employee;
use App\Support\Countries;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

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

    public function query(): Builder
    {
        $query = Employee::query()
            ->with(['department', 'position', 'shift']);

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

        return $query->orderBy('employee_number');
    }

    /**
     * @return array<int, string>
     */
    public function headings(): array
    {
        return [
            'Employee Number',
            'Full Name',
            'Nationality',
            'Gender',
            'Birth Date',
            'Phone',
            'Address',
            'Department',
            'Position',
            'Shift',
            'Employment Status',
            'Hire Date',
            'Termination Date',
            'Notes',
        ];
    }

    /**
     * @param  Employee  $employee
     * @return array<int, mixed>
     */
    public function map($employee): array
    {
        return [
            $employee->employee_number,
            $employee->full_name,
            Countries::name($employee->national_id) ?? $employee->national_id,
            $employee->gender?->value,
            $employee->birth_date?->toDateString(),
            $employee->phone,
            $employee->address,
            $employee->department?->name,
            $employee->position?->name,
            $employee->shift?->name,
            $employee->employment_status?->value,
            $employee->hire_date?->toDateString(),
            $employee->termination_date?->toDateString(),
            $employee->notes,
        ];
    }
}
