<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'name', 'code', 'location_type', 'address', 'city', 'country',
        'latitude', 'longitude', 'contact_name', 'contact_phone', 'status',
        'notes', 'created_by', 'updated_by',
    ];

    public const TYPES = ['depot', 'stop', 'hub', 'warehouse', 'customer', 'other'];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $type = null): self
    {
        if ($search) {
            $this->groupStart()
                ->like('number', $search)
                ->orLike('name', $search)
                ->orLike('code', $search)
                ->orLike('address', $search)
                ->orLike('city', $search)
                ->groupEnd();
        }

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

        if ($type) {
            $this->where('location_type', $type);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        return $this->nextSeqNumber('LOC');
    }

    public function getActive(?string $search = null, int $limit = 200): array
    {
        $builder = $this->where('status', 'active');

        if ($search) {
            $builder->groupStart()
                ->like('name', $search)
                ->orLike('number', $search)
                ->orLike('code', $search)
                ->orLike('city', $search)
                ->groupEnd();
        }

        return $builder->orderBy('name', 'ASC')->limit($limit)->findAll();
    }

    /**
     * @return list<array>
     */
    public function getWithCoordinates(?string $search = null, int $limit = 150): array
    {
        $builder = $this->where('status', 'active')
            ->where('latitude IS NOT NULL')
            ->where('longitude IS NOT NULL');

        if ($search) {
            $builder->groupStart()
                ->like('name', $search)
                ->orLike('number', $search)
                ->orLike('code', $search)
                ->orLike('city', $search)
                ->groupEnd();
        }

        return $builder->orderBy('name', 'ASC')->limit($limit)->findAll();
    }

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

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