<?php

namespace App\Models;

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

class DetailAttribute extends Model
{
    use HasFactory;
    protected $table = "tbl_detail_attributes";
    protected $primaryKey = "id";

    protected $fillable = [
        'code',
        'idproduct_attribute',
        'idspecific_attributes',
        'createdby',
        'idcompany',
        'status'
    ];

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

    public function productAttribute(): HasOne
    {
        return $this->hasOne(ProductAttribute::class, 'id', 'idproduct_attribute');
    }

    public function specificAttributes(): HasOne
    {
        return $this->hasOne(SpecificAttributes::class, 'id', 'idspecific_attributes');
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'createdby');
    }

    public function company(): HasOne
    {
        return $this->hasOne(Company::class, 'id', 'idcompany');
    }

    # 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);
    }

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

    public function scopeCode($query, $code, $id = null)
    {
        return $query->when($id, fn ($query) => $query->where('id', '<>', $id))->where('code', $code);
    }


    # Filtros
    public function scopeAttributeFilters($query)
    {
        #Filtro de Buscador
        // $query->when(
        //     request('search'),
        //     fn ($query) => $query->where('code', 'LIKE', '%' . request('search') . '%')
        //         ->orWhere('name', 'LIKE', '%' . request('search') . '%')
        // );

        #Filtro de codigo
        $query->when(
            request('code'),
            fn ($query) => $query->where('code', 'LIKE', '%' . request('code') . '%')
        );

        #Filtro de id de usuario creador
        $query->when(
            request('createdby'),
            fn ($query) => $query->where('createdby', request('createdby'))
        );

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

        #Filtro de estados
        $query->when(
            request('status') !== null,
            fn ($query) => $query->where('status', request('status'))
        )->when(
            request('status') === null,
            fn ($query) => $query->where('status', 1)
        );
    }
}
