<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ShopProduct extends Model
{
    protected $fillable = [
        'category_id',
        'department_id',    // ✅ ADD THIS
        'branch_id',        // ✅ ADD THIS
        'name',
        'slug',
        'sku',
        'category_label',
        'brand',
        'product_type',
        'short_description',
        'description',
        'price',
        'compare_at_price',
        'cost_price',
        'image',
        'stock_quantity',
        'track_inventory',
        'is_featured',
        'is_active',
        'rating',
        'review_count',
        'base_features',
        'specifications',
        'upgrade_options',
        'metadata',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'compare_at_price' => 'decimal:2',
            'cost_price' => 'decimal:2',
            'rating' => 'decimal:2',
            'stock_quantity' => 'integer',
            'review_count' => 'integer',
            'track_inventory' => 'boolean',
            'is_featured' => 'boolean',
            'is_active' => 'boolean',
            'base_features' => 'array',
            'specifications' => 'array',
            'upgrade_options' => 'array',
            'metadata' => 'array',
            'sort_order' => 'integer',
        ];
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(ShopCategory::class, 'category_id');
    }

    // ✅ ADD THIS - Department Relationship
    public function department(): BelongsTo
    {
        return $this->belongsTo(ShopDepartment::class, 'department_id');
    }

    // ✅ ADD THIS - Branch Relationship
    public function branch(): BelongsTo
    {
        return $this->belongsTo(ShopBranch::class, 'branch_id');
    }

    public function images(): HasMany
    {
        return $this->hasMany(ShopProductImage::class, 'product_id')->orderBy('sort_order');
    }

    public function variants(): HasMany
    {
        return $this->hasMany(ShopProductVariant::class, 'product_id')->orderBy('sort_order');
    }

    public function orderItems(): HasMany
    {
        return $this->hasMany(ShopOrderItem::class, 'product_id');
    }

    public function catalogItems(): BelongsToMany
    {
        return $this->belongsToMany(
            ShopCatalogItem::class,
            'shop_catalog_item_product',
            'product_id',
            'catalog_item_id'
        )->withPivot('sort_order');
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(ShopReview::class, 'product_id');
    }
}
