<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'product_id', 'work_order_id', 'service_visit_id',
        'quantity', 'unit_label', 'used_at', 'used_by_employee_id',
        'notes', 'status', 'recorded_by', 'created_by', 'updated_by',
    ];

    public const STATUSES = ['recorded', 'voided'];

    public const EDITABLE_STATUSES = ['recorded'];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $select = 'ops_material_usage.*, products.name AS product_name, products.sku,'
            . ' employees.full_name AS used_by_name, employees.employee_number AS used_by_number,'
            . ' work_orders.number AS work_order_number, work_orders.title AS work_order_title';

        $this->join('products', 'products.id = ops_material_usage.product_id', 'left')
            ->join('employees', 'employees.id = ops_material_usage.used_by_employee_id', 'left')
            ->join('work_orders', 'work_orders.id = ops_material_usage.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_material_usage.service_visit_id', 'left');
        }

        $this->select($select);

        if ($search) {
            $this->groupStart()
                ->like('ops_material_usage.number', $search)
                ->orLike('ops_material_usage.notes', $search)
                ->orLike('ops_material_usage.unit_label', $search)
                ->orLike('products.name', $search)
                ->orLike('products.sku', $search)
                ->orLike('work_orders.number', $search)
                ->groupEnd();
        }

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

        return $this;
    }

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