<?php

namespace App\Models;

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

class Fstr extends Model
{
    use HasFactory;

    protected $table = 'm_fstrs';

    protected $fillable = [
        'code',
        'name',
        'description',
        'recipe_data',
        'total_cost',
        'is_active',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'recipe_data' => 'json',
        'total_cost' => 'decimal:2',
        'is_active' => 'boolean',
        '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 details (raw materials used)
    public function fstrDetails()
    {
        return $this->hasMany(FstrDetail::class, 'fstr_id');
    }

    // Scope for active FSTRs
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('delete_flag', false);
    }

    // Get formatted total cost
    public function getFormattedTotalCostAttribute()
    {
        return 'Rp ' . number_format($this->total_cost, 0, ',', '.');
    }

    // Calculate total cost from details
    public function calculateTotalCost()
    {
        return $this->fstrDetails()->sum('total_cost');
    }

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

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

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

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