<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ProductionMaterial extends Model
{
    use HasFactory;

    protected $fillable = [
        'production_id',
        'material_id',
        'quantity',
        'unit',
        'unit_cost',
        'total_cost',
        'created_by',
        'is_admin_suggested',
        'sent_to_teknisi_at',
        'revised_by_teknisi_at',
        'revised_by',
        // Field baru untuk checklist & status
        'is_received',
        'received_at',
        'stock_status', // available, insufficient, pending_purchase
        'is_additional', // item tambahan saat produksi
        'request_reason',
    ];

    protected $casts = [
        'quantity' => 'integer',
        'unit_cost' => 'decimal:2',
        'total_cost' => 'decimal:2',
        'is_admin_suggested' => 'boolean',
        'sent_to_teknisi_at' => 'datetime',
        'revised_by_teknisi_at' => 'datetime',
        'is_received' => 'boolean',
        'received_at' => 'datetime',
        'is_additional' => 'boolean',
    ];

    protected static function booted()
    {
        static::creating(function ($item) {
            // Validasi: total_cost HARUS di-set oleh controller dengan perhitungan yang benar
            // total_cost = quantity × unit_cost × orderQty (untuk semua unit produk)
            // Tidak ada fallback auto-calculation untuk mencegah kesalahan perhitungan
            if ($item->total_cost === null) {
                // Jika total_cost null saat create, berarti controller lupa set
                throw new \InvalidArgumentException(
                    'ProductionMaterial: total_cost must be set by controller. ' .
                    'Calculation: total_cost = quantity × unit_cost × orderQty. ' .
                    'This ensures accurate cost calculation for all product units.'
                );
            }
        });

        static::saved(function ($item) {
            if ($item->production) {
                $item->production->calculateCosts();
            }
        });
    }

    public function production()
    {
        return $this->belongsTo(Production::class);
    }

    public function material()
    {
        return $this->belongsTo(Material::class);
    }

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

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

    /*
    |--------------------------------------------------------------------------
    | ACCESSORS
    |--------------------------------------------------------------------------
    */
    
    /**
     * Get stock status label
     */
    public function getStockStatusLabelAttribute()
    {
        return match ($this->stock_status) {
            'available' => 'Tersedia',
            'insufficient' => 'Stok Kurang',
            'pending_purchase' => 'Menunggu Pembelian',
            default => ucfirst($this->stock_status ?? 'available'),
        };
    }

    /**
     * Get stock status badge class
     */
    public function getStockStatusBadgeClassAttribute()
    {
        return match ($this->stock_status) {
            'available' => 'bg-green-100 text-green-800',
            'insufficient' => 'bg-red-100 text-red-800',
            'pending_purchase' => 'bg-yellow-100 text-yellow-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }

    /**
     * Get received status label
     */
    public function getReceivedStatusLabelAttribute()
    {
        return $this->is_received ? 'Diterima' : 'Belum Diterima';
    }

    /**
     * Check if stock is sufficient for the required quantity
     */
    public function checkStockAvailability($orderQty = 1)
    {
        if (!$this->material) {
            return false;
        }
        
        $totalNeeded = $this->quantity * $orderQty;
        return $this->material->stock >= $totalNeeded;
    }

    /**
     * Get shortage amount
     */
    public function getShortageAmount($orderQty = 1)
    {
        if (!$this->material) {
            return $this->quantity * $orderQty;
        }
        
        $totalNeeded = $this->quantity * $orderQty;
        return max(0, $totalNeeded - $this->material->stock);
    }

    public function resolveRouteBinding($value, $field = null)
    {
        // Jika ada production di route, scope ke production tersebut
        if (request()->route('production')) {
            return $this->where('id', $value)
                ->where('production_id', request()->route('production')->id)
                ->firstOrFail();
        }
        
        return parent::resolveRouteBinding($value, $field);
    }
}
