<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'sales_order_id', 'company_id', 'delivery_date', 'status',
        'carrier', 'tracking_number', 'shipping_address',
        'dispatched_at', 'delivered_at', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'        => 'required|max_length[40]',
        'company_id'    => 'required|is_natural_no_zero',
        'delivery_date' => 'required|valid_date',
        'status'        => 'permit_empty|in_list[draft,ready,dispatched,in_transit,delivered,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $companyId = null): self
    {
        $this->select('deliveries.*, companies.name as company_name, sales_orders.number as order_number')
            ->join('companies', 'companies.id = deliveries.company_id', 'left')
            ->join('sales_orders', 'sales_orders.id = deliveries.sales_order_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('deliveries.number', $search)
                ->orLike('companies.name', $search)
                ->orLike('deliveries.tracking_number', $search)
                ->orLike('deliveries.carrier', $search)
                ->orLike('sales_orders.number', $search)
                ->groupEnd();
        }

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

        if ($companyId) {
            $this->where('deliveries.company_id', $companyId);
        }

        return $this;
    }

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