<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'inventory_asset_id', 'work_order_id', 'service_visit_id',
        'status', 'notes', 'assigned_at', 'returned_at',
        'assigned_by', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['assigned', 'returned', 'lost'];

    public const EDITABLE_STATUSES = ['assigned'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $select = 'ops_equipment_allocations.*, inventory_assets.asset_tag, inventory_assets.name AS asset_name,'
            . ' work_orders.number AS work_order_number, work_orders.title AS work_order_title';

        $this->join('inventory_assets', 'inventory_assets.id = ops_equipment_allocations.inventory_asset_id', 'left')
            ->join('work_orders', 'work_orders.id = ops_equipment_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_equipment_allocations.service_visit_id', 'left');
        }

        $this->select($select);

        if ($search) {
            $this->groupStart()
                ->like('ops_equipment_allocations.number', $search)
                ->orLike('ops_equipment_allocations.notes', $search)
                ->orLike('inventory_assets.asset_tag', $search)
                ->orLike('inventory_assets.name', $search)
                ->orLike('work_orders.number', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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