<?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 Ticket extends Model
{
    use HasFactory;

    protected $table = "tbl_ticket";

    protected $fillable = [
        'date',
        'nro_ticket',
        'type',
        'idshopping_cart',
        'iduser_created',
        'idcustomer',
        'idclient_address',
        'seller_rut',
        'net_total',
        'mnt_excent',
        'IVA',
        'gross_total',
        'discounttype',
        'total_discount',
        'sub_total',
        'total',
        'idcompany',
        'idtype_document',
        'idsale_channel',
        // 'payment_condition',
        'idway_to_pay',
        'bussines_area',
        'idsalesman',
        'observation',
        'status_ticket',
        'status_invoice',
        'issued_proof_payment',
        'proof_payment_amount',
        'url_invoice',
        'folio',
        'payment_status',
        'status'
    ];

    protected $hidden = [
        'updated_at'
    ];

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

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

    public function clientAddress(): HasOne
    {
        return $this->hasOne(ClientAddress::class, 'id', 'idclient_address');
    }

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

    public function detail(): HasMany
    {
        return $this->hasMany(DetailTicket::class, 'idticket', 'id')->where('status', 1);
    }

    public function pay(): HasOne
    {
        return $this->hasOne(Pay::class, 'idregister', 'id')->where('pay_type', 1)->where('transaction_status', 1)->where('status', 1);
    }

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

    public function typeSale(): HasOne
    {
        return $this->hasOne(TypeSale::class, 'id', 'idtype_sale');
    }

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

    public function saleChannel(): HasOne
    {
        return $this->hasOne(SaleChannel::class, 'id', 'idsale_channel');
    }

    public function shoppingCart(): HasOne
    {
        return $this->hasOne(ShoppingCart::class, ' id', 'idshopping_cart');
    }

    public function salesman(): HasOne
    {
        return $this->hasOne(Salesman::class, ' id', 'idsalesman');
    }

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

    # 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->where('idcompany', request('idcompany'))
        );
    }

    # Filtros
    public function scopeTicketFilters($query)
    {
        #Filtro de id
        $query->when(
            request('id'),
            fn($query) => $query->where('id', request('id'))
        );

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

        #Filtro de usuario creado
        $query->when(
            request('iduser_created'),
            fn($query) => $query->where('iduser_created', request('iduser_created'))
        );

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

        #Filtro de tipo de documento
        $query->when(
            request('type_document'),
            fn($query) => $query->where('idtype_document', request('type_document'))
        );

        $query->when(
            request('types_document'),
            fn($query) => $query->wherein('idtype_document', request('types_document'))
        );


        #Filtro de tipo de venta
        $query->when(
            request('type_sale'),
            fn($query) => $query->where('type_sale', request('type_sale'))
        );

        #Filtro de condicion de pago
        $query->when(
            request('payment_condition'),
            fn($query) => $query->where('payment_condition', request('payment_condition'))
        );

        #Filtro de condicion de pago
        $query->when(
            request('payment_term'),
            function ($query) {
                $paymentTerm = request('payment_term');
                if ($paymentTerm == 1) {
                    # Contado
                    $paymentTermArray = [1, 2, 3, 4, 5, 6];
                } elseif ($paymentTerm == 2) {
                    # Crédito
                    $paymentTermArray = [1, 2, 6];
                }
                return $query->whereIn('idtype_document', $paymentTermArray);
            }
        );

        #Filtro de forma de pago
        $query->when(
            request('way_to_pay'),
            fn($query) => $query->where('way_to_pay', request('way_to_pay'))
        );

        #Filtro de estado de ticket
        $query->when(
            request('status_ticket'),
            fn($query) => $query->where('status_ticket', request('status_ticket'))
        );

        #Filtro de estado de pago del ticket
        $query->when(
            request('payment_status'),
            fn($query) => $query->where('payment_status', request('payment_status'))
        );

        #Filtro de estado de documento de venta
        $query->when(
            request('status_invoice') !== null,
            fn($query) => $query->where('status_invoice', request('status_invoice'))
        )->when(
            request('status_invoice') === null,
            fn($query) => $query->where('status_invoice', 0)
        );

        #Filtro de estado de comprobantes emitidos
        $query->when(
            request('issued_proof_payment') !== null,
            fn($query) => $query->where('issued_proof_payment', request('issued_proof_payment'))
        )->when(
            request('issued_proof_payment') === null,
            fn($query) => $query->where('issued_proof_payment', 0)
        );

        #Filtro de fechas
        $query->when(
            request('start_date') && request('end_date'),
            function ($query) {
                $start_date = request('start_date');
                $end_date = request('end_date');

                $query->whereBetween('date', [$start_date, $end_date]);
            }
        );

        # Filtro de fecha exacta
        $query->when(
            request('date'),
            fn($query) => $query->where('date', request('date'))
        );

        # Filtro de fecha limite
        $query->when(
            request('date_until'),
            fn($query) => $query->where('date', '<=', request('date_until'))
        );
        

        #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)
        );
        // $query->when(
        //     request('status') !== null,
        //     fn($query) => $query->where('status', request('status'))
        // );

        # Filtro por IDs de distritos seleccionados (comunas)
        $query->when(
            request('district_ids'),
            function ($query, $districtIds) {
                $query->whereHas('clientAddress', function ($subQuery) use ($districtIds) {
                    $subQuery->whereIn('iddistrict', $districtIds);
                });
            }
        );

    }
}
