<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
use App\Models\DetalleTraspaso;

class Traspaso extends Model
{
    use HasFactory;
    use SoftDeletes;

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

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

    public function detalle()
    {
        return $this->hasOne(DetalleTraspaso::class);
    }

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

    public static function traspasoTotal($id) {
        $total = DetalleTraspaso::selectRaw('sum(cantidad*precio_unitario) AS total')
                    ->where('traspaso_id', $id)
                    ->whereNull('deleted_at')
                    ->get();
        return $total[0]->total ?? 0;

    }

    public static function traspasoTotalCosto($id) {
        $total = DetalleTraspaso::selectRaw('sum(detalle_traspasos.cantidad*productos.precio_compra) AS total')
                    ->join('productos', 'detalle_traspasos.producto_id', '=', 'productos.id')
                    ->where('detalle_traspasos.traspaso_id', $id)
                    ->whereNull('detalle_traspasos.deleted_at')
                    ->whereNull('productos.deleted_at')
                    ->get();
        return $total[0]->total ?? 0;
    }
}
