<?php

namespace App\Models;

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

class FstrDetail extends Model
{
    use HasFactory;

    protected $table = 'm_fstr_details';

    protected $fillable = [
        'fstr_id',
        'raw_material_id',
        'quantity',
        'uom',
        'unit_cost',
        'total_cost',
        'notes',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'quantity' => 'decimal:2',
        'unit_cost' => 'decimal:2',
        'total_cost' => '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');
    }

    // Relationship with FSTR
    public function fstr()
    {
        return $this->belongsTo(Fstr::class, 'fstr_id');
    }

    // Relationship with raw material
    public function rawMaterial()
    {
        return $this->belongsTo(RawMaterial::class, 'raw_material_id');
    }

    // Calculate total cost automatically
    public function calculateTotalCost()
    {
        return $this->quantity * $this->unit_cost;
    }

    // Auto-calculate total cost before saving
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            $model->total_cost = $model->calculateTotalCost();
        });
    }
}