<?php

namespace App\Models;

use CodeIgniter\Model;

class EmployeeDocumentModel extends Model
{
    protected $table         = 'employee_documents';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'employee_id', 'document_type_id', 'document_number', 'issue_date',
        'expiry_date', 'notes', 'status', 'version_count',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'employee_id'      => 'required|integer',
        'document_type_id' => 'required|integer',
        'status'           => 'permit_empty|in_list[active,archived]',
    ];

    public function scopeForList(
        ?int $employeeId = null,
        ?int $documentTypeId = null,
        ?string $status = null,
        ?string $search = null,
        ?string $expiryFilter = null,
        ?string $today = null
    ): self {
        if ($employeeId) {
            $this->where('employee_documents.employee_id', $employeeId);
        }

        if ($documentTypeId) {
            $this->where('employee_documents.document_type_id', $documentTypeId);
        }

        if ($status) {
            $this->where('employee_documents.status', $status);
        }

        if ($search) {
            $this->groupStart()
                ->like('e.full_name', $search)
                ->orLike('e.employee_number', $search)
                ->orLike('employee_documents.document_number', $search)
                ->orLike('t.name', $search)
                ->groupEnd();
        }

        if ($expiryFilter && $today) {
            $this->where('employee_documents.expiry_date IS NOT NULL', null, false);

            match ($expiryFilter) {
                'expired' => $this->where('employee_documents.expiry_date <', $today),
                '7'       => $this->where('employee_documents.expiry_date >=', $today)
                    ->where('employee_documents.expiry_date <=', date('Y-m-d', strtotime($today . ' +7 days'))),
                '30'      => $this->where('employee_documents.expiry_date >=', $today)
                    ->where('employee_documents.expiry_date <=', date('Y-m-d', strtotime($today . ' +30 days'))),
                '90'      => $this->where('employee_documents.expiry_date >=', $today)
                    ->where('employee_documents.expiry_date <=', date('Y-m-d', strtotime($today . ' +90 days'))),
                default   => null,
            };
        }

        return $this;
    }

    public function getForEmployee(int $employeeId): array
    {
        return $this
            ->select('employee_documents.*, t.name as type_name, t.code as type_code, t.requires_expiry')
            ->join('document_types t', 't.id = employee_documents.document_type_id')
            ->where('employee_documents.employee_id', $employeeId)
            ->where('employee_documents.status', 'active')
            ->orderBy('t.name', 'ASC')
            ->findAll();
    }

    public function getWithDetails(int $id): ?array
    {
        return $this
            ->select('employee_documents.*, e.full_name, e.employee_number, t.name as type_name, t.code as type_code, t.requires_expiry, t.requires_number')
            ->join('employees e', 'e.id = employee_documents.employee_id')
            ->join('document_types t', 't.id = employee_documents.document_type_id')
            ->where('employee_documents.id', $id)
            ->where('e.deleted_at', null)
            ->first();
    }

    public function countExpired(string $today): int
    {
        return $this
            ->join('employees e', 'e.id = employee_documents.employee_id')
            ->where('e.deleted_at', null)
            ->where('employee_documents.status', 'active')
            ->where('employee_documents.expiry_date IS NOT NULL', null, false)
            ->where('employee_documents.expiry_date <', $today)
            ->countAllResults();
    }

    public function countExpiringWithin(string $today, int $days): int
    {
        $end = date('Y-m-d', strtotime($today . " +{$days} days"));

        return $this
            ->join('employees e', 'e.id = employee_documents.employee_id')
            ->where('e.deleted_at', null)
            ->where('employee_documents.status', 'active')
            ->where('employee_documents.expiry_date >=', $today)
            ->where('employee_documents.expiry_date <=', $end)
            ->countAllResults();
    }

    public function getExpiryList(string $today, ?int $days = null, int $limit = 10): array
    {
        $builder = $this
            ->select('employee_documents.*, e.full_name, e.employee_number, t.name as type_name, t.code as type_code')
            ->join('employees e', 'e.id = employee_documents.employee_id')
            ->join('document_types t', 't.id = employee_documents.document_type_id')
            ->where('e.deleted_at', null)
            ->where('employee_documents.status', 'active')
            ->where('employee_documents.expiry_date IS NOT NULL', null, false);

        if ($days === null) {
            $builder->where('employee_documents.expiry_date <', $today);
            $builder->orderBy('employee_documents.expiry_date', 'DESC');
        } else {
            $end = date('Y-m-d', strtotime($today . " +{$days} days"));
            $builder->where('employee_documents.expiry_date >=', $today);
            $builder->where('employee_documents.expiry_date <=', $end);
            $builder->orderBy('employee_documents.expiry_date', 'ASC');
        }

        return $builder->limit($limit)->findAll();
    }
}
