<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\Ingredient;
use App\Models\Product;

class InnerOptionItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'inner_option_set_id',
        'name',
        'price',
        'is_active',
        'sort_order',
        'ingredient_id',
        'source_product_id',
        'deduction_grams',
    ];

    protected $casts = [
        'price'            => 'decimal:2',
        'is_active'        => 'boolean',
        'sort_order'       => 'integer',
        'deduction_grams'  => 'decimal:2',
    ];

    protected $appends = ['price_modifier', 'is_default'];

    // Map price to price_modifier for frontend consistency
    public function getPriceModifierAttribute(): string
    {
        return $this->price ?? '0.00';
    }

    public function setPriceModifierAttribute($value): void
    {
        $this->attributes['price'] = $value;
    }

    // Default to false since column doesn't exist
    public function getIsDefaultAttribute(): bool
    {
        return false;
    }

    public function innerOptionSet(): BelongsTo
    {
        return $this->belongsTo(InnerOptionSet::class);
    }

    /** Raw-stock topping (sprinkles, nuts, cherry…) */
    public function ingredient(): BelongsTo
    {
        return $this->belongsTo(Ingredient::class);
    }

    /** Daily-production topping (Lotus syrup, Nutella, brownie…) */
    public function sourceProduct(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'source_product_id');
    }

    /** Whether this topping has any inventory deduction configured */
    public function hasInventoryLink(): bool
    {
        return ($this->ingredient_id || $this->source_product_id) && $this->deduction_grams > 0;
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }
}
