<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'employee_id', 'work_order_id', 'service_visit_id',
        'role', 'status', 'from_date', 'to_date', 'notes',
        'assigned_at', 'assigned_by', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['planned', 'active', 'released'];

    public const EDITABLE_STATUSES = ['planned'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $select = 'ops_staff_allocations.*, employees.full_name AS employee_name, employees.employee_number,'
            . ' work_orders.number AS work_order_number, work_orders.title AS work_order_title';

        $this->join('employees', 'employees.id = ops_staff_allocations.employee_id', 'left')
            ->join('work_orders', 'work_orders.id = ops_staff_allocations.work_order_id', 'left');

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

        $this->select($select);

        if ($search) {
            $this->groupStart()
                ->like('ops_staff_allocations.number', $search)
                ->orLike('ops_staff_allocations.role', $search)
                ->orLike('ops_staff_allocations.notes', $search)
                ->orLike('employees.full_name', $search)
                ->orLike('employees.employee_number', $search)
                ->orLike('work_orders.number', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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