<?php

namespace App;

use App\Filtros\FiltroDeProducto;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use League\Csv\CannotInsertRecord;
use League\Csv\Reader;
use League\Csv\Writer;

class Producto extends Model
{
    public $timestamps = false;
    protected $fillable = ["nombre", "precio", "presentacion", "stock", "categoria"];
    static $paginarPorDefecto = 10;

    public function subpedidos()
    {
        return $this->belongsToMany('App\Subpedido', 'productos_subpedidos')->withPivot(["cantidad", "notas"]);
    }

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

    public function pagaTransporte()
    {
        return !($this->bono || Str::contains($this->categoria, 'SUBSIDIADO'));
    }

    //Este método permite que se apliquen los filtros al hacer una request (por ejemplo, de búsqueda)
    public function scopeFiltrar($query, FiltroDeProducto $filtros)
    {
        return $filtros->aplicar($query);
    }

    public static function getPaginar(Request $request)
    {
        return $request->has('paginar') && intval($request->input('paginar')) ? intval($request->input('paginar')) : self::$paginarPorDefecto;
    }

    public static function productosFilaID()
    {
        return Producto::pluck('id', 'fila',)->all();
    }

    public static function productosIDFila()
    {
        return Producto::pluck('fila', 'id',)->all();
    }

    public static function productosIDNombre()
    {
        return Producto::pluck('nombre', 'id',)->all();
    }

    static public function cantidadesPorBarrio()
    {
        $barrios = DB::table('grupos_de_compra')
            ->where('nombre', '<>', 'PRUEBA')
            ->pluck('id', 'nombre');

        $columnasBarrios = $barrios->map(function ($id, $nombre) {
            return DB::raw("SUM(CASE WHEN subpedidos.grupo_de_compra_id = $id AND subpedidos.aprobado = 1 THEN producto_subpedido.cantidad ELSE 0 END) as `$nombre`");
        })->toArray();

        return DB::table('productos')
            ->where('productos.nombre', 'not like', '%barrial%')
            ->leftJoin('producto_subpedido', 'productos.id', '=', 'producto_subpedido.producto_id')
            ->leftJoin('subpedidos', 'subpedidos.id', '=', 'producto_subpedido.subpedido_id')
            ->select(array_merge(
                ['productos.fila as fila'],
                ['productos.nombre as producto'],
                $columnasBarrios
            ))
            ->groupBy('productos.fila', 'productos.id', 'productos.nombre')
            ->orderBy('productos.fila')
            ->get();
    }

    static public function planillaTotales() {
        $headers = ['Producto'];
        $barrios = DB::table('grupos_de_compra')
            ->where('nombre', '<>', 'PRUEBA')
            ->pluck('nombre')->toArray();
        $headers = array_merge($headers, $barrios);

        $cantidadesPorBarrio = self::cantidadesPorBarrio();
        $planilla = [];
        $ultimaFila = 1;

        foreach ($cantidadesPorBarrio as $productoCantidades) {
            $fila = $productoCantidades->fila;
            while ($fila - $ultimaFila > 1) {
                $ultimaFila++;
                $planilla[$ultimaFila] = ['---'];
            }
            $planilla[$fila] = [$productoCantidades->producto];
            foreach ($barrios as $barrio) {
                $planilla[$fila][] = $productoCantidades->$barrio ?? 0;
            }
            $ultimaFila = $fila;
        }

        try {
            $writer = Writer::createFromPath(resource_path('csv/exports/pedidos-por-barrio.csv'), 'w');
            $writer->insertOne($headers);
            $writer->insertAll($planilla);
        } catch (CannotInsertRecord $e) {
            var_export($e->getRecords());
        }
    }

    public static function notasPorBarrio(): \Illuminate\Support\Collection
    {
        return DB::table('productos')
            ->join('producto_subpedido', 'productos.id', '=', 'producto_subpedido.producto_id')
            ->join('subpedidos', 'producto_subpedido.subpedido_id', '=', 'subpedidos.id')
            ->join('grupos_de_compra', 'subpedidos.grupo_de_compra_id', '=', 'grupos_de_compra.id')
            ->where('productos.requiere_notas', 1)
            ->select(
                'productos.nombre as producto',
                'grupos_de_compra.nombre as barrio',
                'producto_subpedido.notas'
            )
            ->get()
            ->groupBy('producto');
    }

    static public function planillaNotas() {
        $headers = ['Producto'];
        $barrios = DB::table('grupos_de_compra')
            ->where('nombre', '<>', 'PRUEBA')
            ->pluck('nombre')->toArray();
        $headers = array_merge($headers, $barrios);

        $notasPorBarrio = self::notasPorBarrio();
        $planilla = [];

        foreach ($notasPorBarrio as $producto => $notasGrupo) {
            $fila = [$producto];
            foreach ($barrios as $barrio) {
                $notas = $notasGrupo->where('barrio', $barrio)->pluck('notas')->implode('; ');
                $fila[] = $notas ?: '';
            }
            $planilla[] = $fila;
        }

        try {
            $writer = Writer::createFromPath(resource_path('csv/exports/notas-por-barrio.csv'), 'w');
            $writer->insertOne($headers);
            $writer->insertAll($planilla);
        } catch (CannotInsertRecord $e) {
            var_export($e->getRecords());
        }
    }
}