<?php

namespace App\Models;

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

class AccountReceivable extends Model
{
    use HasFactory;

    protected $table = "tbl_account_receivable";

    protected $fillable = [
        'idticket',
        'deadline',
        'amount_paid',
        'debt',
        'total',
        'paid',
        'url_document',
        'status'
    ];

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

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

    public function accountReceivableDets(): HasMany
    {
        return $this->hasMany(AccountReceivableDet::class, 'idaccount_receivable', 'id')->active();
    }

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

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

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

    # Filtros
    public function scopeFilters($query)
    {
        $query->when(
            request('search'),
            fn($query) => $query->whereHas(
                'ticket',
                fn($q) => $q->where('folio', 'like', '%' . request('search') . '%')
            )
        );

        $query->when(
            request('idsupplier'),
            fn($query) => $query->whereHas(
                'ticket',
                fn($q) => $q->where('idcustomer', request('idsupplier'))
            )
        );

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

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

        $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'))
        )->when(
            !request('orderBy') && !request('order'),
            fn($query) => $query->orderBy('id', 'desc')
        );
    }
}
