<?php

namespace App\Models;

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

class Cartola extends Model
{
    use HasFactory;
    protected $table = "tbl_cartola";

    protected $fillable = [
        'idsupplier',
        'idticket',
        'idpayment_voucher',
        'type',
        'charge',
        'payment',
        'balance',
        'idway_to_pay',
        'gloss',
        'idcompany',
        'iduser',
        'status'
    ];

    protected $hidden = [
        'updated_at'
    ];

    # Relaciones
    public function supplier(): HasOne
    {
        return $this->hasOne(Supplier::class, 'id', 'idsupplier');
    }

    public function paymentVoucher(): HasOne
    {
        return $this->hasOne(PaymentVoucher::class, 'id', 'idpayment_voucher');
    }

    public function ticket(): HasOne
    {
        return $this->hasOne(Ticket::class, 'id', 'idticket');
    }

    public function wayToPay(): HasOne
    {
        return $this->hasOne(WayToPay::class, 'id', 'idway_to_pay');
    }

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

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

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

    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 scopeFilters($query)
    {
        $query->when(
            request('id'),
            fn($query) => $query->where('id', request('id'))
        );

        $query->when(
            request('idsupplier'),
            fn($query) => $query->where('idsupplier', request('idsupplier'))
        );

        $query->company();

        $query->when(
            request('status'),
            fn($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn($query) => $query->where('status', 1)
        );

        $query->when(
            request('orderBy') && request('order'),
            fn($query) => $query->orderBy(request('orderBy'), request('order') ?? 'asc')
        )->when(
            !request('orderBy') && !request('order'),
            fn($query) => $query->orderBy('idticket', 'desc')
                ->orderBy('created_at', 'asc')

        );
    }
}
