<?php

namespace App\Models;

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

class ProductionItemRequest extends Model
{
    use HasFactory;

    protected $fillable = [
        'production_id',
        'item_type', // material atau sparepart
        'material_id',
        'sparepart_id',
        'item_name', // untuk item baru yang belum ada di sistem
        'item_description',
        'quantity',
        'unit',
        'estimated_price',
        'reason',
        'status', // pending, approved, rejected, purchased, sent, received
        'requested_by',
        'requested_at',
        'processed_by',
        'processed_at',
        'admin_notes',
        'purchase_id',
        'proposal_number', // usulan ke-1, 2, 3
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'estimated_price' => 'decimal:2',
        'requested_at' => 'datetime',
        'processed_at' => 'datetime',
        'proposal_number' => 'integer',
    ];

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

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

    public function sparepart()
    {
        return $this->belongsTo(Sparepart::class);
    }

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

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

    public function purchase()
    {
        return $this->belongsTo(Purchase::class);
    }

    /*
    |--------------------------------------------------------------------------
    | ACCESSORS
    |--------------------------------------------------------------------------
    */
    
    /**
     * Get item name (dari relasi atau item_name untuk item baru)
     */
    public function getItemNameDisplayAttribute()
    {
        if ($this->item_type === 'material' && $this->material) {
            return $this->material->name;
        }
        
        if ($this->item_type === 'sparepart' && $this->sparepart) {
            return $this->sparepart->name;
        }
        
        return $this->item_name ?? 'Item Baru';
    }

    /**
     * Check if this is a new item (not in system)
     */
    public function getIsNewItemAttribute()
    {
        return is_null($this->material_id) && is_null($this->sparepart_id);
    }

    /**
     * Get status label
     */
    public function getStatusLabelAttribute()
    {
        return match ($this->status) {
            'pending' => 'Menunggu Persetujuan',
            'approved' => 'Disetujui',
            'rejected' => 'Ditolak',
            'purchased' => 'Sudah Dibeli',
            'sent' => 'Dikirim ke Teknisi',
            'received' => 'Sudah Diterima',
            default => ucfirst($this->status),
        };
    }

    /**
     * Get status badge class
     */
    public function getStatusBadgeClassAttribute()
    {
        return match ($this->status) {
            'pending' => 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-800 dark:text-yellow-300',
            'approved' => 'bg-blue-100 dark:bg-blue-900/40 text-blue-800 dark:text-blue-300',
            'rejected' => 'bg-red-100 dark:bg-red-900/40 text-red-800 dark:text-red-300',
            'purchased' => 'bg-purple-100 dark:bg-purple-900/40 text-purple-800 dark:text-purple-300',
            'sent' => 'bg-indigo-100 dark:bg-indigo-900/40 text-indigo-800 dark:text-indigo-300',
            'received' => 'bg-green-100 dark:bg-green-900/40 text-green-800 dark:text-green-300',
            default => 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300',
        };
    }

    /**
     * Get item type label
     */
    public function getItemTypeLabelAttribute()
    {
        return match ($this->item_type) {
            'material' => 'Bahan',
            'sparepart' => 'Sparepart',
            default => ucfirst($this->item_type),
        };
    }

    /**
     * Get current stock (for existing items)
     */
    public function getCurrentStockAttribute()
    {
        if ($this->item_type === 'material' && $this->material) {
            return $this->material->stock;
        }
        
        if ($this->item_type === 'sparepart' && $this->sparepart) {
            return $this->sparepart->stock;
        }
        
        return 0;
    }

    /**
     * Get stock shortage (how much more is needed)
     */
    public function getStockShortageAttribute()
    {
        $currentStock = $this->current_stock;
        $needed = $this->quantity;
        
        return max(0, $needed - $currentStock);
    }

    /*
    |--------------------------------------------------------------------------
    | SCOPES
    |--------------------------------------------------------------------------
    */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeByProposal($query, $number)
    {
        return $query->where('proposal_number', $number);
    }

    public function scopeMaterials($query)
    {
        return $query->where('item_type', 'material');
    }

    public function scopeSpareparts($query)
    {
        return $query->where('item_type', 'sparepart');
    }

    public function scopeNewItems($query)
    {
        return $query->whereNull('material_id')->whereNull('sparepart_id');
    }
}

