<?php

namespace App\Models;

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

class RawMaterial extends Model
{
    use HasFactory;

    protected $table = 'm_raw_materials';

    protected $fillable = [
        'code',
        'name',
        'uom',
        'description',
        'konversi_satuan_utuh',
        'konversi_satuan_pakai',
        'konversi_satuan_kirim',
        'tipe_barang',
        'minimal_order',
        'multiple_order',
        'suggest_ratio',
        'latest_ratio',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'minimal_order' => 'decimal:2',
        'multiple_order' => 'decimal:2',
        'suggest_ratio' => 'decimal:2',
        'latest_ratio' => 'decimal:2',
        'delete_flag' => 'boolean',
    ];

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

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

    public function targetSisaMalam()
    {
        return $this->hasMany(TargetSisaMalam::class, 'raw_material_id');
    }

    public function stockOpnameDetails()
    {
        return $this->hasMany(StockOpnameDetail::class, 'raw_material_id');
    }

    public function itemRequestDetails()
    {
        return $this->hasMany(ItemRequestDetail::class, 'raw_material_id');
    }

    public function forecasts()
    {
        return $this->hasMany(Forecast::class, 'raw_material_id');
    }

    // Relationship with item conversions
    public function itemConversions()
    {
        return $this->hasMany(ItemConversion::class, 'raw_material_id');
    }

    // Get active conversion for this raw material
    public function activeConversion()
    {
        return $this->hasOne(ItemConversion::class, 'raw_material_id')->where('is_active', true)->where('delete_flag', false);
    }

    // FSTR details relationship
    public function fstrDetails()
    {
        return $this->hasMany(FstrDetail::class, 'raw_material_id');
    }
    public function stores()
    {
        return $this->belongsToMany(Store::class, 'm_store_raw_materials', 'raw_material_id', 'store_id')
            ->withPivot(['is_active', 'min_stock', 'max_stock', 'reorder_point', 'notes', 'delete_flag'])
            ->withTimestamps()
            ->wherePivot('delete_flag', 0);
    }

    // Get active stores for this raw material
    public function activeStores()
    {
        return $this->stores()->wherePivot('is_active', true);
    }

    // Direct relationship to store raw materials mapping
    public function storeRawMaterials()
    {
        return $this->hasMany(StoreRawMaterial::class, 'raw_material_id');
    }

    // Check if this material is wet type (Basah)
    public function isWetType()
    {
        return $this->tipe_barang === 'Basah';
    }

    // Check if this material is dry type (Kering)
    public function isDryType()
    {
        return $this->tipe_barang === 'Kering';
    }

    // Get material type display with badge color
    public function getMaterialTypeBadgeAttribute()
    {
        return $this->tipe_barang === 'Basah' ? 'badge-info' : 'badge-secondary';
    }

    // Calculate suggested order quantity based on ratio and current stock
    public function calculateSuggestedOrder($currentStock, $forecastQty)
    {
        if ($this->suggest_ratio <= 0) {
            return 0;
        }

        $suggestedQty = $forecastQty * $this->suggest_ratio;
        
        // Apply minimal order constraint
        if ($suggestedQty < $this->minimal_order) {
            $suggestedQty = $this->minimal_order;
        }

        // Apply multiple order constraint
        if ($this->multiple_order > 0) {
            $suggestedQty = ceil($suggestedQty / $this->multiple_order) * $this->multiple_order;
        }

        return $suggestedQty;
    }

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

        static::creating(function ($model) {
            $lastCode = static::selectRaw("code")
                ->where('delete_flag', '0')
                ->where('code', 'like', 'RM%')
                ->orderByRaw("CAST(SUBSTRING(code FROM 3) AS INTEGER) DESC")
                ->value('code');

            $lastNumber = $lastCode ? intval(substr($lastCode, 2)) : 0;
            $newNumber = $lastNumber + 1;

            $model->code = 'RM' . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
        });
    }
}