<?php

namespace App\Models\Pedidos;

class PedidoLineaModel extends \App\Models\BaseModel
{
    protected $table = "pedidos_linea";

    /**
     * Whether primary key uses auto increment.
     *
     * @var bool
     */
    protected $useAutoIncrement = true;

    const SORTABLE = [
        0 => "t2.id",
        1 => "t2.updated_at",
        2 => "t2.fecha_entrega_real",
        3 => "t4.nombre",
        4 => "CONCAT(t5.first_name, ' ', t5.last_name)",
        5 => "t3.titulo",
        6 => "t6.nombre",
        7 => "t3.inc_rei",
        8 => "t3.paginas",
        9 => "t3.tirada",
        10 => "t3.total_aceptado",
        11 => "t2.estado"
    ];
    
    protected $allowedFields = [
        "pedido_id", 
        "presupuesto_id", 
        "ubicacion_id",
        "user_created_id", 
        "user_updated_id", 
        "created_at",
        "updated_at",
        "cantidad",
        "descripcion",
    ];
    protected $returnType = "App\Entities\Pedidos\PedidoLineaEntity";

    protected $useTimestamps = true;
    protected $useSoftDeletes = false;

    protected $createdField = "created_at";
    protected $updatedField = "updated_at";

    public static $labelField = "id";

    
    public function getResource($search = [], $estado="", $cliente_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t2.id AS id, t2.updated_at AS fecha, t2.fecha_entrega_real AS fecha_entrega, 
                t4.nombre AS cliente, CONCAT(t5.first_name, ' ', t5.last_name) AS comercial, 
                t3.titulo AS titulo, t6.nombre AS ubicacion, t3.inc_rei AS inc_rei,
                t3.paginas AS paginas, t3.tirada AS tirada, t3.total_aceptado AS total_presupuesto,
                t2.estado AS estado"
            );

        $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");        
        $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");    
        $builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
        $builder->join("users t5", "t5.id = t4.comercial_id", "left");
        $builder->join("ubicaciones t6", "t6.id = t1.ubicacion_id", "left");
        
        if($estado != "") {
            if($estado == "activo") {
                $sql = "t2.estado = 'validacion' OR t2.estado = 'produccion'";
                $builder->where($sql);
            } else {
                $builder->where("t2.estado", $estado);
            }
        }

        if($cliente_id != -1 && $cliente_id != "-1") {
            $builder->where("t3.cliente_id", $cliente_id);
        }

        if (empty($search))
            return $builder;
        else {
            $builder->groupStart();
            foreach ($search as $col_search) {
                if ($col_search[0] != 1 && $col_search[0] != 2)
                    $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
                else {
                    $dates = explode(" ", $col_search[2]);
                    $builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
                    $builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
                }
            }
            $builder->groupEnd();
            return $builder;
        }
    }

    public function getSumOfTirada(array $search, $estado = '', $cliente_id=-1, $start = 0, $length = 5)
    {

        $builder = $this->db
            ->table($this->table . " t1")
            ->selectSum('t3.tirada', 'total_tirada');
            
        $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");        
        $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");    
        $builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
        $builder->join("users t5", "t5.id = t4.comercial_id", "left");
        $builder->join("ubicaciones t6", "t6.id = t1.ubicacion_id", "left");
            
        if($cliente_id != -1 && $cliente_id != "-1") {
            $builder->where("t3.cliente_id", $cliente_id);
        }

        // Aplica los filtros de búsqueda y estado
        if (!empty($search)) {
            $builder->groupStart();
            foreach ($search as $col_search) {
                if ($col_search[0] != 1 && $col_search[0] != 2)
                    $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
                else {
                    $dates = explode(" ", $col_search[2]);
                    $builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
                    $builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
                }
            }
            $builder->groupEnd();
        }

        if ($estado !== '') {
            $builder->where('t2.estado', $estado);
        }

        // Aplicar el orden y el límite
        $builder->limit($length, $start);

        return $builder->get()->getRow()->total_tirada;
    }

    public function getSumOfTotalAceptado(array $search, $estado = '', $cliente_id=-1, $start = 0, $length = 5)
    {

        $builder = $this->db
            ->table($this->table . " t1")
            ->selectSum('t3.total_aceptado', 'total');
            
        $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");        
        $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");    
        $builder->join("clientes t4", "t4.id = t3.cliente_id", "left");
        $builder->join("users t5", "t5.id = t4.comercial_id", "left");
        $builder->join("ubicaciones t6", "t6.id = t1.ubicacion_id", "left");
        
        if($cliente_id != -1 && $cliente_id != "-1") {
            $builder->where("t3.cliente_id", $cliente_id);
        }

        // Aplica los filtros de búsqueda y estado
        if (!empty($search)) {
            $builder->groupStart();
            foreach ($search as $col_search) {
                if ($col_search[0] != 1 && $col_search[0] != 2)
                    $builder->like(self::SORTABLE[$col_search[0]], $col_search[2]);
                else {
                    $dates = explode(" ", $col_search[2]);
                    $builder->where(self::SORTABLE[$col_search[0]] . ">=", $dates[0]);
                    $builder->where(self::SORTABLE[$col_search[0]] . "<=", $dates[1]);
                }
            }
            $builder->groupEnd();
        }

        if ($estado !== '') {
            $builder->where('t2.estado', $estado);
        }

        // Aplicar el orden y el límite
        $builder
                ->limit($length, $start);

        return $builder->get()->getRow()->total;
    }

    public function getTotalOfTotalAceptado($estado = "")
    {

        $builder = $this->db
            ->table($this->table . " t1")
            ->selectSum('t3.total_aceptado', 'total');
            
        $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");        
        $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");    
        
        if ($estado !== '') {
            $builder->where('t2.estado', $estado);
        }
        
        return $builder->get()->getRow()->total;
    }

    public function getTotalTirada($estado = "")
    {

        $builder = $this->db
            ->table($this->table . " t1")
            ->selectSum('t3.tirada', 'total_tirada');
            
        $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left");        
        $builder->join("presupuestos t3", "t1.presupuesto_id = t3.id", "left");    
         
        if ($estado !== '') {
            $builder->where('t2.estado', $estado);
        }

        return $builder->get()->getRow()->total_tirada;
    }

    public function obtenerLineasPedidoSinFacturar($cliente_id) {
        $resultaArray = [];
    
        $subquery = $this->db
            ->table('facturas_pedidos_lineas')
            ->select('pedido_linea_id, SUM(cantidad) AS total_cantidad')
            ->groupBy('pedido_linea_id')
            ->getCompiledSelect();
    
        $builder = $this->db
            ->table($this->table . " t1")
            ->select("t1.id AS id, t1.pedido_id AS pedido_id, t3.titulo AS titulo, t4.codigo AS tipo_impresion")
            ->join("pedidos t2", "t2.id = t1.pedido_id", "left")
            ->join("presupuestos t3", "t3.id = t1.presupuesto_id", "left")
            ->join("tipos_presupuestos t4", "t4.id = t3.tipo_impresion_id", "left")
            ->join("($subquery) fpl", "fpl.pedido_linea_id = t1.id", "left")
            ->where("t3.cliente_id", $cliente_id)
            ->whereIn("t2.estado", ["produccion", "enviado","finalizado"])
            ->where("(t3.tirada > IFNULL(fpl.total_cantidad, 0))");
    
        // Ejecutar la consulta y devolver resultados
        $query = $builder->get();
        $data = $query->getResult();
    
        foreach($data as $register) {
            $item = (object)[
                'id' => $register->id,
                'text' => '['. lang('Pedidos.pedido') . ' ' . $register->pedido_id . '] ' . $register->titulo . ' - ' . lang('Presupuestos.' . $register->tipo_impresion),
            ];
            array_push($resultaArray, $item);
        }
    
        return $resultaArray;
    }
    public function findByPresupuesto(int $presupuestoId){
        $builder = $this->db
            ->table($this->table)
            ->select();
        return $builder->where('presupuesto_id',$presupuestoId)->get()->getFirstRow();
    }
}