<?php

namespace App\Models;

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

class Product extends Model
{
    protected $fillable = [
        'product_category_id', 'name', 'slug', 'description',
        'price', 'image', 'gallery', 'is_active', 'stock', 'order', 'weight_kg',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'is_active' => 'boolean',
        'gallery' => 'array',
    ];

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

    public function inStock(): bool
    {
        return $this->stock === null || $this->stock > 0;
    }

    /** Image principale ou première photo de la galerie (aperçus liste). */
    public function primaryImagePath(): ?string
    {
        if (! empty($this->image)) {
            return $this->image;
        }
        $g = $this->gallery;
        if (! is_array($g)) {
            return null;
        }
        foreach ($g as $path) {
            if (is_string($path) && $path !== '') {
                return $path;
            }
        }

        return null;
    }

    /** Chemins galerie normalisés (sans la principale si elle est déjà dans image). */
    public function galleryPaths(): array
    {
        $g = $this->gallery;
        if (! is_array($g)) {
            return [];
        }

        return array_values(array_filter($g, fn ($p) => is_string($p) && $p !== ''));
    }
}
