<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'plan_start_date', 'plan_end_date', 'status',
        'total_routes', 'total_employees', 'total_distance_km', 'total_duration_minutes',
        'total_fuel_litres', 'total_cost', 'conflicts_json', 'fleet_summary_json',
        'optimization_summary', 'rejection_reason', 'generated_by',
        'approved_by', 'approved_at', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['draft', 'pending_approval', 'approved', 'rejected'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select(
            'transport_ai_plans.*,
             creator.username AS generated_by_username,
             approver.username AS approved_by_username'
        )
            ->join('users AS creator', 'creator.id = transport_ai_plans.generated_by', 'left')
            ->join('users AS approver', 'approver.id = transport_ai_plans.approved_by', 'left');

        if ($search) {
            $this->groupStart()
                ->like('transport_ai_plans.number', $search)
                ->orLike('transport_ai_plans.title', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'AIP-' . 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);
    }

    /**
     * @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;
    }
}
