<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class InnerOptionSet extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'type',
        'is_active',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    protected $appends = ['min_select', 'max_select', 'is_required', 'max_selections'];

    // Default accessors for fields that don't exist in DB but frontend expects
    public function getMinSelectAttribute(): int
    {
        return 0;
    }

    public function getMaxSelectAttribute(): int
    {
        return 10; // Default max selections for inner options (toppings)
    }

    public function getIsRequiredAttribute(): bool
    {
        return false;
    }

    public function getMaxSelectionsAttribute(): int
    {
        return 10; // Same as max_select default
    }

    public function items(): HasMany
    {
        return $this->hasMany(InnerOptionItem::class)->orderBy('sort_order');
    }

    public function activeItems(): HasMany
    {
        return $this->hasMany(InnerOptionItem::class)
            ->where('is_active', true)
            ->orderBy('sort_order');
    }

    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class, 'product_inner_options')
            ->withTimestamps();
    }

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

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }
}
