<?php

namespace App;

use App\Helpers\TransporteHelper;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Log;
use App\Filtros\FiltroDeSubpedido;

class Subpedido extends Model
{
    const COSTO_TRANSPORTE = 15;
    public $timestamps = false;
  protected $fillable = ['grupo_de_compra_id', 'aprobado', 'nombre', 'devoluciones_total', 'devoluciones_notas'];

  public function productos()
  {
    return $this->belongsToMany('App\Producto')->withPivot(["cantidad","total", "notas"]);
  }

  //Bonos del MPS, Sororo, etc. NO devuelve bonos de transporte
  private function bonos()
  {
    return $this->productos()->where('bono',1);
  }

  public function productosSinBonos()
  {
    return $this->productos()->where('bono',false);
  }

  public function grupoDeCompra()
  {
    return $this->belongsTo('App\GrupoDeCompra');
  }

  //Permite que se apliquen los filtros al hacer una request (por ejemplo, de búsqueda)
  public function scopeFiltrar($query, FiltroDeSubpedido $filtros)
  {
      return $filtros->aplicar($query);
  }

    public function total()
    {
        return $this->totalSinDevoluciones() - $this->devoluciones_total;
    }

    public function totalSinDevoluciones()
    {
        return $this->totalBarrial() + $this->totalCentral();
    }

    public function totalBarrial()
    {
        return DB::table('producto_subpedido')
            ->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
            ->where('producto_subpedido.subpedido_id', $this->id)
            ->where('productos.nombre', 'like', '%barrial%')
            ->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
            ->value('total');
    }

    public function totalCentral()
    {
        return $this->totalCentralesQueNoPaganTransporte() + $this->totalCentralesQuePaganTransporte() + $this->totalTransporte();
    }

    public function totalCentralesQueNoPaganTransporte()
    {
        return DB::table('producto_subpedido')
            ->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
            ->where('producto_subpedido.subpedido_id', $this->id)
            ->where('productos.nombre', 'not like', '%barrial%')
            ->where(function ($query) {
                $query->where('productos.categoria', 'like', '%SUBSIDIADO%')
                    ->orWhere('productos.bono', true);
            })
            ->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
            ->value('total');
    }

    public function totalCentralesQuePaganTransporte()
    {
        return DB::table('producto_subpedido')
            ->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
            ->where('producto_subpedido.subpedido_id', $this->id)
            ->where('productos.nombre', 'not like', '%barrial%')
            ->where('productos.bono', false)
            ->where('productos.categoria', 'not like', '%SUBSIDIADO%')
            ->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
            ->value('total');
    }

    public function totalTransporte()
    {
        return TransporteHelper::totalTransporte($this->totalCentralesQuePaganTransporte());
    }

    public function cantidadTransporte()
    {
        return TransporteHelper::cantidadTransporte($this->totalCentralesQuePaganTransporte());
    }

  //Actualiza el pedido, agregando o quitando del subpedido según sea necesario. Debe ser llamado desde el controlador de subpedidos, luego de validar que los parámetros $producto y $cantidad son correctos. También calcula el subtotal por producto.
  public function syncProducto(Producto $producto, Int $cantidad, string $notas) {
        if ($cantidad){
          //si la cantidad es 1 o más se agrega el producto o actualiza la cantidad
          $this->productos()->syncWithoutDetaching([
            $producto->id => [
              'cantidad' => $cantidad,
              'total' => $cantidad * $producto->precio,
              'notas' => $notas,
            ]
          ]);
        } else {
            //si la cantidad es 0, se elimina el producto del subpedido
            $this->productos()->detach($producto->id);
        }
  }

  public function toggleAprobacion(bool $aprobacion) {
      $this->aprobado = $aprobacion;
      $this->save();
  }

  public function generarHTML() {
      $view = view("pdfgen.subpedido_tabla", ["subpedido" => $this]);
      return $view->render();
  }

  public function syncDevoluciones(float $total, string $notas) {
    $this->devoluciones_total = $total;
    $this->devoluciones_notas = $notas;
    $this->save();
  }
}