<?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;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;

class Vale extends Model
{
    use HasFactory;

    protected $table = 'vales';

    protected $fillable = [
        'total',
        'precio_unitario',
        'imagen_qr',
        'iva',
        'ieps',
        'token',
        'vigencia',
        'estatus',
        'cancelado',
        'fecha_registro',
    ];

    public function valesSesiones(): HasMany
    {
        return $this->hasMany(ValeSesion::class, 'vale_id');
    }

    public function ventaDetalle(): HasMany
    {
        return $this->hasMany(VentaDetalle::class, 'vale_id');
    }

    public function venta(): HasOneThrough
    {
        return $this->hasOneThrough(
            Venta::class,
            VentaDetalle::class,
            'vale_id', // Foreign key on venta_detalles table
            'id', // Foreign key on ventas table
            'id', // Local key on vales table
            'venta_id' // Local key on venta_detalles table
        );
    }

    public function cliente(): HasOneThrough
    {
        return $this->hasOneThrough(
            Cliente::class,
            VentaDetalle::class,
            'vale_id', // Foreign key on venta_detalles table
            'id', // Foreign key on clientes table
            'id', // Local key on vales table
            'venta_id' // Local key on venta_detalles table
        )->join('ventas', 'ventas.id', '=', 'ventas_detalles.venta_id')
         ->where('ventas_detalles.vale_id', '!=', null);
    }
}
