<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use App\Models\DetalleVenta;
class Venta extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $dates = ["deleted_at"];
    protected $table = 'ventas';
    protected $guarded = ['id'];

    public function sucursal()
    {
        return $this->belongsTo(Sucursal::class);
    }

    public function cliente()
    {
        return $this->belongsTo(Cliente::class);
    }

    public function pago()
    {
        return $this->belongsTo(Pago::class);
    }

    public function documento()
    {
        return $this->belongsTo(Documento::class);
    }

    public function factura()
    {
        return $this->belongsTo(Factura::class);
    }

    public function historial()
    {
        return $this->hasMany(DetalleVenta::class);
    }

    public static function total($id) {
        $total = DetalleVenta::selectRaw('sum(cantidad*precio_unitario) AS total')
                    ->where('venta_id', $id)
                    ->where('estado', '<>', 1)
                    ->whereNull('deleted_at')
                    ->get();
        return $total[0]->total ?? 0;

    }
}
