<?php

namespace App\Models;

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

class RelationProductAttribute extends Model
{
    use HasFactory;

    protected $table = "tbl_relation_product_attribute";
    protected $primaryKey = "id";

    protected $fillable = [
        'parent_attribute_id',
        'child_attribute_id',
        'idcompany',
        'status'
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    # Relación Muchos a Muchos
    public function parentAttributes(): BelongsToMany
    {
        return $this->belongsToMany(
            ProductAttribute::class,         
            'tbl_relation_product_attribute',   
            'parent_attribute_id',           
            'child_attribute_id'
        );
    }

    public function childAttributes(): BelongsToMany
    {
        return $this->belongsToMany(
            ProductAttribute::class,         
            'tbl_relation_product_attribute',
            'child_attribute_id',
            'parent_attribute_id'
        );
    }

    public function childAttribute()
    {
        return $this->belongsTo(ProductAttribute::class, 'child_attribute_id', 'id');
    }

    public function parentAttribute()
    {
        return $this->belongsTo(ProductAttribute::class, 'parent_attribute_id', 'id');
    }


    public function products()
    {
        return $this->belongsToMany(Product::class, 'tbl_product_details', 'relation_product_attribute_id', 'product_id')
                    ->withTimestamps();
    }

    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1)->company();
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    # Filtro de idcompany
    public function scopeCompany($query)
    {
        return $query->when(
            request('idcompany'),
            fn($query) => $query->where('idcompany', request('idcompany'))
        );
    }

    # Filtro por parent_attribute_id o child_attribute_id
    public function scopeByParentOrChildType($query, $typeId)
    {
        return $query->where('parent_attribute_id', $typeId)->orWhere('child_attribute_id', $typeId);
    }

    # Filtros adicionales
    public function scopeAttributeRelationFilters($query)
    {
        #Filtro de estado
        $query->when(
            request('status') !== null,
            fn ($query) => $query->where('status', request('status'))
        )->when(
            request('status') === null,
            fn ($query) => $query->where('status', 1)
        );

        #Filtro de idcompany
        $query->company();
    }
}
