<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Opcion extends Model
{
    use HasFactory;

    protected $fillable = [
        'nombre',
        'tipo'
    ];

    public function productos()
    {
        return $this->belongsToMany(Producto::class)
            ->using(OpcionProducto::class)
            ->withPivot('caracteristicas')
            ->withTimestamps();
    }

    public function caracteristicas()
    {
        return $this->hasMany(Caracteristica::class);
    }

    public function scopeVerificarFamilia($query, $familia_id){
        $query->when($familia_id,function($query,$familia_id){
            $query->whereHas('productos.subcategoria.categoria', function ($query) use($familia_id){
                $query->where('familia_id', $familia_id);
            })->with([
                'caracteristicas' => function($query)use($familia_id) {
                    $query->whereHas('variantes.producto.subcategoria.categoria', function ($query) use($familia_id){
                        $query->where('familia_id', $familia_id);
                    });
                }
            ]);
        });
    }

    public function scopeVerificarCategoria($query, $categoria_id){
        $query->when($categoria_id,function($query,$categoria_id){
            $query->whereHas('productos.subcategoria.categoria', function ($query) use($categoria_id){
                $query->where('familia_id', $categoria_id);
            })->with([
                'caracteristicas' => function($query)use($categoria_id) {
                    $query->whereHas('variantes.producto.subcategoria.categoria', function ($query) use($categoria_id){
                        $query->where('familia_id', $categoria_id);
                    });
                }
            ]);
        });
    }

    public function scopeVerificarSubcategoria($query, $subcategoria_id){
        $query->when($subcategoria_id,function($query,$subcategoria_id){
            $query->whereHas('productos.subcategoria.categoria', function ($query) use($subcategoria_id){
                $query->where('familia_id', $subcategoria_id);
            })->with([
                'caracteristicas' => function($query)use($subcategoria_id) {
                    $query->whereHas('variantes.producto.subcategoria.categoria', function ($query) use($subcategoria_id){
                        $query->where('familia_id', $subcategoria_id);
                    });
                }
            ]);
        });
    }
}
