<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'checklist_id', 'title', 'is_required', 'sort_order',
    ];

    /**
     * @return list<array>
     */
    public function getForChecklist(int $checklistId): array
    {
        return $this->where('checklist_id', $checklistId)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('id', 'ASC')
            ->findAll();
    }

    public function nextSortOrder(int $checklistId): int
    {
        $row = $this->selectMax('sort_order')
            ->where('checklist_id', $checklistId)
            ->first();

        return (int) ($row['sort_order'] ?? 0) + 1;
    }
}
