<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'employee_id', 'license_number', 'license_class', 'license_expiry',
        'phone', 'status', 'notes', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['active', 'inactive', 'suspended'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('transport_drivers.*, employees.full_name AS employee_name, employees.employee_number')
            ->join('employees', 'employees.id = transport_drivers.employee_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('transport_drivers.number', $search)
                ->orLike('transport_drivers.license_number', $search)
                ->orLike('employees.full_name', $search)
                ->orLike('employees.employee_number', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'DRV-' . date('ymd') . '-';
        $row    = $this->like('number', $prefix, 'after')->orderBy('id', 'DESC')->first();
        $seq    = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }

    public function getActive(): array
    {
        return $this->scopeForList(null, 'active')
            ->orderBy('employees.full_name', 'ASC')
            ->findAll();
    }

    public function isEmployeeTaken(int $employeeId, ?int $excludeId = null): bool
    {
        $builder = $this->where('employee_id', $employeeId);
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }

    /**
     * @return array<string, int>
     */
    public function countByStatus(): array
    {
        $counts = array_fill_keys(self::STATUSES, 0);
        $rows   = $this->select('status, COUNT(*) AS cnt')->groupBy('status')->findAll();
        foreach ($rows as $row) {
            $counts[$row['status']] = (int) $row['cnt'];
        }

        return $counts;
    }
}
