<?php

namespace App\Models;

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

class Product extends Model
{
    protected $fillable = [
        'name', 'slug', 'description', 'price', 'sale_price', 'stock',
        'category_id', 'brand_id', 'image_url',
        'is_active', 'is_on_sale', 'is_product_of_month',
    ];

    protected $casts = [
        'price'               => 'decimal:2',
        'sale_price'          => 'decimal:2',
        'is_active'           => 'boolean',
        'is_on_sale'          => 'boolean',
        'is_product_of_month' => 'boolean',
    ];

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

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

    // ---- Marketing relacional ----
    public function relations(): HasMany
    {
        return $this->hasMany(ProductRelation::class);
    }

    /** Productos relacionados por tipo: 'cross' | 'up' | 'down'. */
    public function relatedByType(string $type)
    {
        return $this->belongsToMany(
            Product::class,
            'product_relations',
            'product_id',
            'related_product_id'
        )->wherePivot('type', $type);
    }

    /**
     * ACCESOR: precio vigente. Si está en oferta y tiene sale_price,
     * devuelve el precio de oferta; de lo contrario el precio normal.
     * Uso: $product->active_price
     */
    public function getActivePriceAttribute(): float
    {
        return (float) ($this->is_on_sale && $this->sale_price
            ? $this->sale_price
            : $this->price);
    }

    /** ACCESOR: porcentaje de descuento (0 si no aplica). */
    public function getDiscountPercentAttribute(): int
    {
        if (! $this->is_on_sale || ! $this->sale_price || $this->price <= 0) {
            return 0;
        }
        return (int) round(100 - ($this->sale_price / $this->price * 100));
    }

    // ---- Scopes de conveniencia para el Page Builder ----
    public function scopeActive($q)        { return $q->where('is_active', true); }
    public function scopeOnSale($q)         { return $q->where('is_on_sale', true); }
    public function scopeProductOfMonth($q) { return $q->where('is_product_of_month', true); }
}
