<?php

namespace App\Models\Facturas;

 
class FacturaLineaModel extends \App\Models\BaseModel { 

    protected $table = 'facturas_lineas';

    // Lista de columnas basada en los campos de la tabla, para asignación masiva
    protected $allowedFields = [
        'factura_id',
        'pedido_linea_impresion_id',
        'pedido_maquetacion_id',
        'descripcion',
        'cantidad',
        'iva',
        'base',
        'total_iva',
        'total',
        'data',
        'deleted_at',
        'user_updated_id'
    ];

    protected $returnType = "App\Entities\Facturas\FacturaLineaEntity";

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

    public static $labelField = "id";

    public function getResource($factura_id)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.factura_id AS factura_id, 
                t1.pedido_linea_impresion_id AS pedido_linea_impresion_id, t1.pedido_maquetacion_id AS pedido_maquetacion_id, 
                t1.descripcion AS descripcion, t1.cantidad as cantidad, t1.iva AS iva,
                t1.base AS base, t1.total_iva AS total_iva, t1.total AS total, t1.data AS data, t2.pedido_id AS pedido_id,
                t3.total_aceptado_revisado AS total_aceptado, t4.tirada_flexible AS tirada_flexible, t4.descuento_tirada_flexible AS descuento_tirada_flexible,
                t6.cantidad AS cantidad_albaran"
            )
            ->join("pedidos_linea t2", "t2.id = t1.pedido_linea_impresion_id", "left")
            ->join("presupuestos t3", "t3.id = t2.presupuesto_id", "left")
            ->join("clientes t4", "t4.id = t3.cliente_id", "left")
            ->join("albaranes t5", "t5.pedido_id = t2.pedido_id", "left")
            ->join("albaranes_lineas t6", "t6.albaran_id = t5.id", "left")
            ->where("t1.factura_id", $factura_id)
            ->where("t1.deleted_at", null)
            ->groupBy('t1.id');

        return $builder;
    }


    public function getResourceResumenIVAsForPdf($factura_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.iva, 
                        ROUND(SUM(t1.base), 2) AS base, 
                        ROUND(SUM(t1.total_iva), 2) AS total_iva, 
                        ROUND(SUM(t1.total), 2) AS total"
            )
            ->where("t1.factura_id", $factura_id)
            ->where("t1.deleted_at", null)
            ->groupBy('t1.iva')
            ->orderBy('t1.iva', 'ASC');  // Ordena por iva en forma ascendente

        return $builder;
    }


    /**
     * Get resource data for creating PDFs.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResourceForPdf($factura_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t1.id AS id, t1.factura_id AS factura_id, 
                t1.pedido_linea_impresion_id AS pedido_linea_impresion_id, t1.pedido_maquetacion_id AS pedido_maquetacion_id, 
                t1.descripcion AS descripcion, t1.cantidad as cantidad, t1.iva AS iva,
                t1.base AS base, t1.total_iva AS total_iva, t1.total AS total, t1.data AS data"
            )
            ->where("t1.factura_id", $factura_id)
            ->where("t1.deleted_at", null);

        return $builder;
    }

    /**
     * Get resource data for creating PDFs.
     *
     * @param string $search
     *
     * @return \CodeIgniter\Database\BaseBuilder
     */
    public function getResourceForExcel($factura_id = -1)
    {
        $builder = $this->db
            ->table($this->table . " t1")
            ->select(
                "t2.numero AS ref_factura, 
                t3.pedido_id AS pedido_id, 
                t4.referencia_cliente AS referencia_cliente, 
                t1.base AS base"
            )
            ->join("facturas t2", "t2.id = t1.factura_id", "left")
            ->join("pedidos_linea t3", "t3.id = t1.pedido_linea_impresion_id", "left")
            ->join("presupuestos t4", "t4.id = t3.presupuesto_id", "left")
            ->where("t1.factura_id", $factura_id)
            ->where("t1.deleted_at", null);

        return $builder;
    }


    public function addFacturaPedidoLinea($factura_id, $pedido_linea_id, $cantidad)
    {
        $data = [
            "factura_id" => $factura_id,
            "pedido_linea_id" => $pedido_linea_id,
            "cantidad" => $cantidad
        ];

        return $this->db->table("facturas_pedidos_lineas")->insert($data);
    }

    public function deleteFacturasLineasPedido($factura_id, $pedido_linea_id, $cantidad){
        
        $this->db->table("facturas_pedidos_lineas")
            ->where("factura_id", $factura_id)
            ->where("pedido_linea_id", $pedido_linea_id)
            ->where("cantidad", $cantidad)
            ->delete();
    }
    
    public function updateFacturaPedidoLinea($factura_id, $pedido_linea_id, $cantidad, $cantidad_new)
    {
        // Obtener la ID del registro que queremos actualizar
        $record = $this->db->table("facturas_pedidos_lineas")
            ->select('id')
            ->where("factura_id", $factura_id)
            ->where("pedido_linea_id", $pedido_linea_id)
            ->where("cantidad", $cantidad)
            ->limit(1)
            ->get()
            ->getRow();

        // Si existe el registro
        if ($record) {
            $data = [
                "cantidad" => $cantidad_new
            ];

            // Actualizar el registro especificado por su ID
            $this->db->table("facturas_pedidos_lineas")
                ->where("id", $record->id)
                ->update($data);
        }
    }
}