<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'registration_number', 'make', 'model', 'year', 'vehicle_type',
        'fuel_type', 'capacity', 'odometer_km', 'last_service_date',
        'current_driver_id', 'current_location_id', 'latitude', 'longitude',
        'status', 'notes', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['active', 'maintenance', 'retired'];
    public const TYPES    = ['car', 'van', 'truck', 'bus', 'motorcycle', 'other'];
    public const FUELS    = ['petrol', 'diesel', 'electric', 'hybrid', 'other'];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $type = null): self
    {
        $this->select(
            'transport_vehicles.*,
             drivers.number AS driver_number,
             employees.full_name AS driver_name,
             locations.name AS location_name'
        )
            ->join('transport_drivers AS drivers', 'drivers.id = transport_vehicles.current_driver_id', 'left')
            ->join('employees', 'employees.id = drivers.employee_id', 'left')
            ->join('transport_locations AS locations', 'locations.id = transport_vehicles.current_location_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('transport_vehicles.number', $search)
                ->orLike('transport_vehicles.registration_number', $search)
                ->orLike('transport_vehicles.make', $search)
                ->orLike('transport_vehicles.model', $search)
                ->groupEnd();
        }

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

        if ($type) {
            $this->where('transport_vehicles.vehicle_type', $type);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'VEH-' . 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->where('status', 'active')->orderBy('registration_number', 'ASC')->findAll();
    }

    public function isRegistrationTaken(string $registration, ?int $excludeId = null): bool
    {
        $builder = $this->where('registration_number', strtoupper(trim($registration)));
        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;
    }
}
