<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'category_id',
        'name',
        'slug',
        'description',
        'base_price',
        'scoop_price',
        'image',
        'max_scoops',
        'is_active',
        'requires_production',
    ];

    protected $casts = [
        'base_price' => 'decimal:2',
        'scoop_price' => 'decimal:2',
        'max_scoops' => 'integer',
        'is_active' => 'boolean',
        'requires_production' => 'boolean',
    ];

    protected $appends = ['image_url'];

    public function getImageUrlAttribute(): ?string
    {
        if (empty($this->image) || trim($this->image) === '') {
            return null;
        }

        // If it's already a full URL, return as is
        if (str_starts_with($this->image, 'http')) {
            return $this->image;
        }

        // Return the storage URL
        return asset('storage/' . $this->image);
    }

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

    public function optionSets(): BelongsToMany
    {
        return $this->belongsToMany(OptionSet::class, 'product_option_sets')
            ->withTimestamps();
    }

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

    public function branches(): BelongsToMany
    {
        return $this->belongsToMany(Branch::class, 'branch_products')
            ->withPivot(['is_available', 'custom_price'])
            ->withTimestamps();
    }

    public function branchProducts(): HasMany
    {
        return $this->hasMany(BranchProduct::class);
    }

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

    public function scopeByCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }
}
