<?php

namespace App\Models;

use DragonCode\Contracts\Http\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Cliente extends Model
{
    use HasFactory;

    protected $table = 'clientes';

    protected $fillable = [
        'rfc',
        'razonSocial',
        'celular',
        'email',
        'tipo',
        'observacion',
        'estatus',
    ];

    public function expedientes(): HasMany
    {
        return $this->hasMany(Expediente::class, 'cliente_id')
        ->leftjoin('sucursales', 'expedientes.sucursal_id', '=', 'sucursales.id')
        ->selectRaw('
            expedientes.*,
            sucursales.nombre sucursal
        ')
        ->orderByDesc('expedientes.fecha_registro');
    }

    public function sesiones(): HasMany
    {
        return $this->hasMany(Sesion::class, 'cliente_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'id','cliente_id');
    }

    public function ventas(): HasMany
    {
        return $this->hasMany(Venta::class, 'cliente_id');
    }

    public function direccionesEntrega(): HasMany
    {
        return $this->hasMany(DireccionEntrega::class, 'cliente_id');
    }

    public function datosFiscales(): HasMany
    {
        return $this->hasMany(DatoFiscal::class, 'cliente_id');
    }

    public function direcciones(): HasOne
    {
        return $this->hasOne(DireccionEntrega::class, 'cliente_id', 'id')->where('es_principal', 'si');
    }

    public function fiscales(): HasOne
    {
        return $this->hasOne(DatoFiscal::class, 'cliente_id', 'id')->where('es_principal', 'si');
    }
}
