<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'title', 'description', 'company_id', 'work_order_id',
        'service_visit_id', 'inspector_employee_id', 'priority', 'status',
        'overall_result', 'location', 'scheduled_date', 'completed_at',
        'score', 'notes', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['planned', 'in_progress', 'completed', 'cancelled'];

    public const OPEN_STATUSES = ['planned', 'in_progress'];

    public const RESULTS = ['pass', 'fail', 'na', 'pending'];

    public const PRIORITIES = ['low', 'normal', 'high', 'urgent'];

    public function scopeForList(
        ?string $search = null,
        ?string $status = null,
        ?string $priority = null,
        ?string $result = null
    ): self {
        $select = 'qc_inspections.*, companies.name AS company_name,'
            . ' employees.full_name AS inspector_name, employees.employee_number AS inspector_number,'
            . ' work_orders.number AS work_order_number, work_orders.title AS work_order_title';

        $this->join('companies', 'companies.id = qc_inspections.company_id', 'left')
            ->join('employees', 'employees.id = qc_inspections.inspector_employee_id', 'left')
            ->join('work_orders', 'work_orders.id = qc_inspections.work_order_id', 'left');

        if ($this->db->tableExists('fs_service_visits')) {
            $select .= ', fs_service_visits.number AS service_visit_number, fs_service_visits.title AS service_visit_title';
            $this->join('fs_service_visits', 'fs_service_visits.id = qc_inspections.service_visit_id', 'left');
        }

        $this->select($select);

        if ($search) {
            $this->groupStart()
                ->like('qc_inspections.number', $search)
                ->orLike('qc_inspections.title', $search)
                ->orLike('qc_inspections.description', $search)
                ->orLike('qc_inspections.location', $search)
                ->orLike('companies.name', $search)
                ->groupEnd();
        }

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

        if ($priority) {
            $this->where('qc_inspections.priority', $priority);
        }

        if ($result) {
            $this->where('qc_inspections.overall_result', $result);
        }

        return $this;
    }

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