<?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\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'vendor_id', 'category_id',
        'name_en', 'name_ur', 'description_en', 'description_ur',
        'slug', 'sku', 'price', 'discount_price', 'stock_quantity',
        'track_stock', 'unit', 'weight', 'is_active', 'is_featured',
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'discount_price' => 'decimal:2',
            'weight' => 'decimal:3',
            'is_active' => 'boolean',
            'is_featured' => 'boolean',
            'track_stock' => 'boolean',
        ];
    }

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

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

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

    public function primaryImage(): HasMany
    {
        return $this->hasMany(ProductImage::class)->where('is_primary', true)->limit(1);
    }

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

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

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

    /**
     * Attribute values grouped for display: one row per attribute, with
     * multiselect values collapsed into a comma-separated string.
     * Returns: [['name' => 'Color', 'slug' => 'color', 'unit' => null, 'values' => ['Red','Blue']], ...]
     */
    public function specifications(): array
    {
        return $this->attributeValues
            ->loadMissing('attribute')
            ->filter(fn($v) => $v->attribute !== null)
            ->groupBy('attribute_id')
            ->map(function ($rows) {
                $attr = $rows->first()->attribute;
                return [
                    'name'   => $attr->name,
                    'slug'   => $attr->slug,
                    'unit'   => $attr->unit,
                    'values' => $rows->pluck('value')->filter()->values()->all(),
                ];
            })
            ->sortBy(fn($s, $attrId) => $this->attributeValues->firstWhere('attribute_id', $attrId)?->attribute?->sort_order ?? 999)
            ->values()
            ->all();
    }

    public function getEffectivePrice(): float
    {
        return (float) ($this->discount_price ?? $this->price);
    }

    public function isInStock(): bool
    {
        return ! $this->track_stock || $this->stock_quantity > 0;
    }
}
