<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'service_visit_id', 'work_order_id', 'inspector_employee_id',
        'title', 'findings', 'result', 'status', 'inspected_at', 'notes',
        'created_by', 'updated_by',
    ];

    public const STATUSES = ['draft', 'submitted', 'approved', 'rejected'];

    public const OPEN_STATUSES = ['draft', 'rejected'];

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

    public function scopeForList(?string $search = null, ?string $status = null, ?string $result = null): self
    {
        $this->select(
            'fs_inspection_reports.*,
             inspector.full_name AS inspector_name,
             inspector.employee_number AS inspector_number,
             fs_service_visits.number AS visit_number,
             work_orders.number AS work_order_number'
        )
            ->join('employees AS inspector', 'inspector.id = fs_inspection_reports.inspector_employee_id', 'left')
            ->join('fs_service_visits', 'fs_service_visits.id = fs_inspection_reports.service_visit_id', 'left')
            ->join('work_orders', 'work_orders.id = fs_inspection_reports.work_order_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('fs_inspection_reports.number', $search)
                ->orLike('fs_inspection_reports.title', $search)
                ->orLike('inspector.full_name', $search)
                ->orLike('fs_service_visits.number', $search)
                ->groupEnd();
        }

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

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

        return $this;
    }

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