<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'service_visit_id', 'employee_id', 'title', 'role',
        'status', 'priority', 'due_date', 'assigned_at', 'started_at',
        'completed_at', 'notes', 'assigned_by', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['assigned', 'accepted', 'in_progress', 'done', 'cancelled'];

    public const OPEN_STATUSES = ['assigned', 'accepted', 'in_progress'];

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

    public function scopeForList(?string $search = null, ?string $status = null, ?string $priority = null): self
    {
        $this->select(
            'fs_technician_jobs.*,
             employees.full_name AS employee_name,
             employees.employee_number AS employee_number,
             fs_service_visits.number AS visit_number'
        )
            ->join('employees', 'employees.id = fs_technician_jobs.employee_id', 'left')
            ->join('fs_service_visits', 'fs_service_visits.id = fs_technician_jobs.service_visit_id', 'left');

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

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

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

        return $this;
    }

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