<?php

namespace Modules\HR\DTO;

class AttendanceFilter
{
    public function __construct(
        public readonly ?string $search = null,
        public readonly ?int $employee_id = null,
        public readonly ?int $department_id = null,
        public readonly ?int $designation_id = null,
        public readonly ?int $shift_id = null,
        public readonly ?array $status = null,
        public readonly ?bool $is_locked = null,
        public readonly ?bool $has_overtime = null,
        public readonly ?int $min_late_minutes = null,
        public readonly ?string $from_date = null,
        public readonly ?string $to_date = null,
        public readonly ?int $fiscal_year_id = null,
        public readonly ?int $accounting_period_id = null,
        public readonly ?int $perPage = 15,
    ) {}

    public static function fromRequest($request): self
    {
        return new self(
            search: $request->filled('search') ? trim($request->search) : null,
            employee_id: $request->filled('employee_id') ? (int) $request->employee_id : null,
            department_id: $request->filled('department_id') ? (int) $request->department_id : null,
            designation_id: $request->filled('designation_id') ? (int) $request->designation_id : null,
            shift_id: $request->filled('shift_id') ? (int) $request->shift_id : null,
            status: $request->filled('status') ? self::toArray($request->input('status')) : null,
            is_locked: $request->filled('is_locked') ? filter_var($request->input('is_locked'), FILTER_VALIDATE_BOOLEAN) : null,
            has_overtime: $request->filled('has_overtime') ? filter_var($request->input('has_overtime'), FILTER_VALIDATE_BOOLEAN) : null,
            min_late_minutes: $request->filled('min_late_minutes') ? (int) $request->min_late_minutes : null,
            from_date: $request->input('from_date'),
            to_date: $request->input('to_date'),
            fiscal_year_id: $request->filled('fiscal_year_id') ? (int) $request->fiscal_year_id : null,
            accounting_period_id: $request->filled('accounting_period_id') ? (int) $request->accounting_period_id : null,
            perPage: $request->input('per_page', 15),
        );
    }

    /**
     * status=present,late,absent  ->  ['present','late','absent']
     * status[]=present&status[]=late  ->  ['present','late']  (already array)
     */
    private static function toArray($value): array
    {
        if (is_array($value)) {
            return $value;
        }

        return array_filter(array_map('trim', explode(',', $value)));
    }
}
