<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'request_date', 'needed_by', 'department', 'status',
        'subtotal', 'tax_amount', 'total', 'notes', 'rejection_reason',
        'approved_by', 'approved_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'       => 'required|max_length[40]',
        'request_date' => 'required|valid_date',
        'status'       => 'permit_empty|in_list[draft,pending_approval,approved,rejected,converted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('purchase_requests.*');

        if ($search) {
            $this->groupStart()
                ->like('purchase_requests.number', $search)
                ->orLike('purchase_requests.department', $search)
                ->orLike('purchase_requests.notes', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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