<?php

namespace App\Models\Warehouse\IndirectGoods;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Warehouse\Project;
use App\Models\User;

class IndirectGoodsConsumption extends Model
{
    use HasFactory;

    protected $table = 'indirect_goods_consumption';

    protected $fillable = [
        'consumption_number',
        'consumption_date',
        'project_id',
        'indirect_good_id',
        'invoice_number',
        'quantity_consumed',
        'consumption_type',
        'reason',
        'recorded_by',
        'approved_by',
    ];

    protected $casts = [
        'consumption_date' => 'date',
        'quantity_consumed' => 'decimal:2',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($consumption) {
            if (empty($consumption->consumption_number)) {
                $consumption->consumption_number = static::generateNumber();
            }
        });
    }

    public static function generateNumber(): string
    {
        $prefix = 'IGC-' . date('Ymd') . '-';
        $last = static::where('consumption_number', 'LIKE', $prefix . '%')
            ->orderBy('consumption_number', 'desc')
            ->first();

        $seq = $last ? ((int) substr($last->consumption_number, -4) + 1) : 1;

        return $prefix . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }

    /**
     * Process the consumption - deduct from project inventory and create stock movement.
     */
    public function processConsumption(): bool
    {
        $projectInv = IndirectGoodsProjectInventory::where('project_id', $this->project_id)
            ->where('indirect_good_id', $this->indirect_good_id)
            ->where('invoice_number', $this->invoice_number)
            ->where('quantity_available', '>', 0)
            ->first();

        if (!$projectInv || $projectInv->quantity_available < $this->quantity_consumed) {
            return false;
        }

        $quantityBefore = $projectInv->quantity_available;
        $projectInv->recordConsumption($this->quantity_consumed);

        // Create stock movement
        IndirectGoodsStockMovement::create([
            'indirect_good_id' => $this->indirect_good_id,
            'movement_type' => 'consumption',
            'reference_type' => 'consumption',
            'reference_id' => $this->id,
            'quantity_before' => $quantityBefore,
            'quantity_moved' => $this->quantity_consumed,
            'quantity_after' => $projectInv->quantity_available,
            'invoice_number' => $this->invoice_number,
            'user_id' => $this->recorded_by,
            'notes' => 'Consumption: ' . $this->consumption_number . ' (' . $this->consumption_type . ')',
        ]);

        return true;
    }

    // Relationships

    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id');
    }

    public function indirectGood()
    {
        return $this->belongsTo(IndirectGood::class, 'indirect_good_id');
    }

    public function recorder()
    {
        return $this->belongsTo(User::class, 'recorded_by');
    }

    public function approver()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }
}
