<?php

namespace App\Models;

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

class CustomerReferenceDocument extends Model
{
    use HasFactory;
    protected $table = 'tbl_customer_reference_documents';

    protected $fillable = [
        'folio',
        'description',
        'iddocument_of_sale',
        'idcustomer',
        'idcompany',
        'status',
    ];

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

    public function documentofsale(): HasOne
    {
        return $this->hasOne(DocumentOfSale::class, 'id', 'iddocument_of_sale');
    }

    public function customer(): HasOne
    {
        return $this->hasOne(Supplier::class, 'id', 'idcustomer');
    }

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

    # Filtros
    public function scopeReferenceDocumentsFilters($query)
    {

        #Filtro de cliente
        $query->when(
            request('idcustomer'),
            fn ($query) => $query->where('idcustomer', request('idcustomer'))
        );

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