<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class Product extends Model
{
    use HasFactory;

    protected $guarded = [];

    /**
     * Sitemap cache auto refresh (Product change হলে)
     */
    protected static function booted()
    {
        static::saved(function () {
            cache()->forget('sef_sitemap_xml_v1');
        });

        static::deleted(function () {
            cache()->forget('sef_sitemap_xml_v1');
        });
    }

    // Relationship with Main Category (Menu as category)
    public function category()
    {
        return $this->belongsTo(Menu::class, 'category_id');
    }

    // Relationship with Subcategory (Submenu)
    public function subcategory()
    {
        return $this->belongsTo(Menu::class, 'subcategory_id');
    }

    public function variants()
    {
        return $this->hasMany(Variant::class);
    }

    public function galleries()
    {
        return $this->hasMany(Gallary::class);
    }

    public function tags()
    {
        return $this->hasMany(Tag::class);
    }

    public function orderDetails()
    {
        return $this->hasMany(OrderDetails::class);
    }

    /**
     * 🔁 NEW: Ei product je je HomeSection-e use hocche
     */
    public function homeSections()
    {
        return $this->belongsToMany(HomeSection::class, 'home_section_product')
            ->withPivot('position')
            ->withTimestamps();
    }

    /**
     * 🔁 NEW: Multi Main Category / Menu mapping
     * Ekta product onek gula main category-te thakte parbe.
     */
    public function menus()
    {
        return $this->belongsToMany(Menu::class, 'menu_product')
            ->withTimestamps();
    }

    // ============ SEO helper ==============
    public function getMetaTitle()
    {
        return $this->name . ' | Best Deals & Prices';
    }

    public function getMetaDescription()
    {
        return Str::limit(strip_tags($this->description), 160);
    }

    // ============ THUMBNAIL URL accessor ============
    public function getThumbnailUrlAttribute(): string
    {
        // thumbnail na thakle fallback
        if (empty($this->thumbnail)) {
            return asset('assets/img/no-image.png');
        }

        $thumb = ltrim($this->thumbnail, '/');

        // 1) Full URL hole
        if (Str::startsWith($thumb, ['http://', 'https://'])) {
            return $thumb;
        }

        // 2) storage/app/public er vitore
        if (Storage::disk('public')->exists($thumb)) {
            return asset('storage/' . $thumb);
        }

        // 3) jodi 'storage/...' diye start hoy
        if (Str::startsWith($thumb, 'storage/')) {
            return asset($thumb);
        }

        // 4) public/assets/img/products/
        if (file_exists(public_path('assets/img/products/' . $thumb))) {
            return asset('assets/img/products/' . $thumb);
        }

        // 5) public/assets/img/
        if (file_exists(public_path('assets/img/' . $thumb))) {
            return asset('assets/img/' . $thumb);
        }

        // last fallback
        return asset('assets/img/no-image.png');
    }
}
