<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'supplier_id', 'status',
        'start_date', 'end_date', 'value', 'notes',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'title'       => 'required|min_length[2]|max_length[200]',
        'supplier_id' => 'required|is_natural_no_zero',
        'status'      => 'permit_empty|in_list[draft,active,expired,terminated,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $supplierId = null): self
    {
        $this->select('supplier_contracts.*, suppliers.name as supplier_name')
            ->join('suppliers', 'suppliers.id = supplier_contracts.supplier_id', 'left');

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

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

        if ($supplierId) {
            $this->where('supplier_contracts.supplier_id', $supplierId);
        }

        return $this;
    }

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