<?php 
session_start();
require_once ("../conexion.php");
require_once('../include/sesiones.php');

$pen_id = $_GET['id'];
?>

<label>Valor Abonar</label>
<input type="number" name="valor1" id="valor1" class="form-control name_list" min="1" autocomplete="off" readonly >
<br>

<?php
$elementos = [];

// Obtener artículos
$sql_articulos = mysqli_query($con, "SELECT * FROM pedido_detalle WHERE pedido_pen_id='$pen_id' AND pend_estado='facturado'");
while ($row = mysqli_fetch_array($sql_articulos)) {
    $row['tipo'] = 'articulo';
    $elementos[] = $row;
}

// Obtener combos
$sql_combos = mysqli_query($con, "SELECT * FROM pedido_detalle_combo WHERE pedido_pen_id='$pen_id' AND pend_estado='facturado'");
while ($row = mysqli_fetch_array($sql_combos)) {
    $row['tipo'] = 'combo';
    $elementos[] = $row;
}

// Ordenar: primero los que no tienen abonos
usort($elementos, function ($a, $b) {
    $a_abono = $a['pend_abonos'] ?? $a['pend_abonos_combo'] ?? 'no';
    $b_abono = $b['pend_abonos'] ?? $b['pend_abonos_combo'] ?? 'no';
    return ($a_abono === 'si') - ($b_abono === 'si');
});


// Mostrar elementos ordenados
foreach ($elementos as $row) {
    if ($row['tipo'] === 'articulo') {
        $pend_id = $row["pend_id"];
        $pend_cantidad = $row["pend_cantidad"];
        $pend_precio = $row['pend_precio'];
        $pend_descuento = $row['pend_descuento'];
        $pend_nombre = $row['pend_nombre'];
        $pend_abonos = $row['pend_abonos'];

        $precio_base = $pend_precio * $pend_cantidad;

        $suma_sab = 0;
        $sabores_array = [];
        $sql2 = mysqli_query($con, "SELECT * FROM sabores_pedido_temp WHERE pend_id='$pend_id'");
        while ($sab1 = mysqli_fetch_array($sql2)) {
            $sabor = $sab1["sabor"];
            $sab_precio = $sab1["precio"] * $sab1['cantidad'] * $pend_cantidad;
            $suma_sab += $sab_precio;
            $sabores_array[] = $sabor;
        }

        $precio_total = $precio_base + $suma_sab;
        $descuento = ($pend_descuento / 100) * $precio_total;
        $precio_final = $precio_total - $descuento;

        $sabores_texto = implode(', ', $sabores_array);
        $checked_disabled = ($pend_abonos == 'si') ? 'checked disabled' : '';

        if ($pend_abonos=='si') {
           $col='col-md-11';
        } else {  
           $col='col-md-12'; 
        }

        ?>
        <div class="<?php echo $col; ?>">
            <input class="articulo-check" id="art_<?php echo $pend_id; ?>" data-precio="<?php echo $precio_final; ?>" type="checkbox" name="articulos[]" value="<?php echo $pend_id; ?>" onchange="calcularTotal()" <?php echo $checked_disabled; ?> >
            <label class="lab" for="art_<?php echo $pend_id; ?>">
                <?php echo $pend_cantidad; ?> - <?php echo $pend_nombre; ?><?php if (!empty($sabores_texto)) echo " ($sabores_texto)"; ?> - $<?php echo number_format($precio_final); ?>
            </label>
        </div>
        <?php 
        if ($pend_abonos=='si') { 
            // Obtener el ped_abo_id relacionado
            $sql3 = mysqli_query($con, "SELECT * FROM pedido_abono_temp WHERE pedido_detalle_pend_id='$pend_id' LIMIT 1");
            $ped_abo_id = null;
            if ($row3 = mysqli_fetch_array($sql3)) {
                $ped_abo_id  = $row3['ped_abo_id'];
            }
        ?>
        <div class="col-md-1">
            <a id="del-<?php echo $ped_abo_id;?>" class="btn btn-danger btn-sm" title="Eliminar"><i class="btn-icon-only icon-remove"></i></a>
        </div>
    <?php }  ?>

        <input type="hidden" name="precios_articulos[<?php echo $pend_id; ?>]" value="<?php echo $precio_final; ?>">

        <?php
    } elseif ($row['tipo'] === 'combo') {
        $pedcom_id = $row['pedcom_id'];
        $pedcom_nombre = $row['pedcom_nombre'];
        $pedcom_cantidad = $row['pedcom_cantidad'];
        $pend_desc = $row['pend_desc'];
        $pedcom_precio = $row['pedcom_precio'];
        $pend_abonos_combo = $row['pend_abonos_combo'];

        $precio_total = $pedcom_cantidad * $pedcom_precio;
        $descuento = ($pend_desc / 100) * $precio_total;
        $precio_final = $precio_total - $descuento;

        $sabores_array = [];
        $sql2 = mysqli_query($con, "SELECT * FROM sabores_pedido_combos_temp WHERE pedido_pen_id='$pen_id'");
        while ($sab1 = mysqli_fetch_array($sql2)) {
            $sabor = $sab1["sabor"];
            $sabores_array[] = $sabor;
        }
        $sabores_texto = implode(', ', $sabores_array);
        $checked_disabled = ($pend_abonos_combo == 'si') ? 'checked disabled' : '';

        if ($pend_abonos_combo=='si') {
           $col='col-md-11';
        } else {  
           $col='col-md-12'; 
        }
        ?>

        <div class="<?php echo $col; ?>">
            <input class="combos-check" id="com_<?php echo $pedcom_id; ?>" data-preciocom="<?php echo $precio_final; ?>" type="checkbox" name="combos[]" value="<?php echo $pedcom_id; ?>" onchange="calcularTotal()" <?php echo $checked_disabled; ?> >
            <label class="lab" for="com_<?php echo $pedcom_id; ?>">
                <?php echo $pedcom_cantidad; ?> - <?php echo $pedcom_nombre; ?><?php if (!empty($sabores_texto)) echo " ($sabores_texto)"; ?> - $<?php echo number_format($precio_final); ?>
            </label> 
        </div>
        <?php 
        if ($pend_abonos_combo=='si') { 
            // Obtener el ped_abo_id relacionado al combo
            $sql3 = mysqli_query($con, "SELECT * FROM pedido_abono_temp WHERE pedido_detalle_pend_id='$pedcom_id' LIMIT 1");
            $ped_abo_id = null;
            if ($row3 = mysqli_fetch_array($sql3)) {
                $ped_abo_id  = $row3['ped_abo_id'];
            }
        ?>
            
        <div class="col-md-1">
            <a id="del_com-<?php echo $ped_abo_id;?>" class="btn btn-danger btn-sm" title="Eliminar"><i class="btn-icon-only icon-remove"></i></a>
        </div>
    <?php }  ?>

        <input type="hidden" name="precios_combos[<?php echo $pedcom_id; ?>]" value="<?php echo $precio_final; ?>">

        <?php
    }
}
?>

<script type="text/javascript">
function calcularTotal() {
    console.log("✅ Se ejecutó calcularTotal");

    let total = 0;

    // Artículos
    document.querySelectorAll('.articulo-check:checked:not(:disabled)').forEach(function(item) {
        total += parseFloat(item.getAttribute('data-precio')) || 0;
    });

    // Combos
    document.querySelectorAll('.combos-check:checked:not(:disabled)').forEach(function(item) {
        total += parseFloat(item.getAttribute('data-preciocom')) || 0;
    });

    document.getElementById('valor1').value = total;
}
</script>

