<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'name', 'code', 'origin_location_id', 'destination_location_id',
        'distance_km', 'estimated_duration_minutes', 'route_geometry', 'status',
        'notes', 'created_by', 'updated_by',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select(
            'transport_routes.*,
             origin.name AS origin_name,
             destination.name AS destination_name'
        )
            ->join('transport_locations AS origin', 'origin.id = transport_routes.origin_location_id', 'left')
            ->join('transport_locations AS destination', 'destination.id = transport_routes.destination_location_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('transport_routes.number', $search)
                ->orLike('transport_routes.name', $search)
                ->orLike('transport_routes.code', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'RTE-' . 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('name', 'ASC')->findAll();
    }
}
