<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'name', 'code', 'description', 'status',
        'created_by', 'updated_by',
    ];

    public const STATUSES = ['active', 'inactive'];

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

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

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

        return $this;
    }

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