<?php
// Conexión a la base de datos
session_start();
$conn = new mysqli('localhost', 'yoveraes_userdb', 't7@s5FxYn1GB', 'yoveraes_botica');
if ($conn->connect_error) {
    die("Error de conexión: " . $conn->connect_error);
}

// Consultar productos
$sql = "SELECT codproducto , descripcion, costos, precio, existencia FROM producto WHERE existencia > 0 ORDER BY existencia DESC";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reporte Productos</title>
    <script src="/Botica/views/ventas/js/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script language="javascript" src="/Botica/views/ventas/js/jquery-3.1.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script language="javascript"></script>
    <style>
        /* Estilos personalizados para el botón */
        .boton-personalizado {
            background-color: #4CAF50;
            /* Verde */
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 18px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 12px;
        }

        .boton-personalizado:hover {
            background-color: #45a049;
            /* Verde más oscuro */
        }
    </style>
    <style>
        /* Estilos básicos */
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        .container {
            max-width: 1000px;
            margin: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            padding: 10px;
            border: 1px solid #ccc;
            text-align: center;
        }

        button {
            padding: 5px 10px;
            color: #fff;
            background: #e74c3c;
            border: none;
            cursor: pointer;
        }

        button:hover {
            background: #c0392b;
        }
    </style>
    <style>
        /* Estilo para reducir la fuente */
        .tabla-pequena {
            font-size: 14px;
            /* Ajusta el tamaño de la fuente */
            border-collapse: collapse;
            width: 100%;
        }

        .tabla-pequena th,
        .tabla-pequena td {
            border: 1px solid #ddd;
            padding: 8px;
        }

        .tabla-pequena th {
            background-color: #3e64d3;
            text-align: left;
        }
    </style>
    <script>
        // Función para sumar los valores de la columna de montos
        function sumarMontos() {
            let total = 0;
            let montos = document.querySelectorAll('.total'); // Seleccionamos todos los elementos con la clase 'monto'
            montos.forEach(function (element) {
                total += parseFloat(element.innerText) || 0;  // Sumamos el contenido de cada elemento
            });
            // Mostrar el total en el campo de texto con id "totalMonto"
            document.getElementById('totalMonto').value = total.toFixed(2);
        }
    </script>
</head>
<h2 class="subtitle"><i class="fas fa-clipboard-check"></i> &nbsp;Reporte Productos | INVENTARIOS &nbsp;<i
        class="fas fa-clipboard-check"></i>
</h2>

<body>
    <div class="table-responsive">
        <h2 style="text-align:center;">Lista de Productos</h2>

        <div class="botones">
            <form action="/Botica/views/ventas/exportarexcel.php" method="post" style="display:inline;">
                <button class="btn-success  btn-sm" type="submit">
                    <i class="fas fa-file-excel">
                    </i>&nbsp;&nbsp;Inventario a Excel
                </button>
            </form>
            <form action="/Botica/views/ventas/generarpdf.php" method="post" target="_blank" style="display:inline;">
                <button type="submit" class="btn-primary  btn-sm" target="_blank"><i
                        class="fas fa-file-pdf"></i>&nbsp;&nbsp;Inventario
                    a PDF</button>
            </form>
        </div>

        <table class="table table-striped table-hover tabla-pequena" style="width: 100%;">
            <thead class="table-dark table-bordered">
                <tr>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">It.</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">Barcod.</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">Producto</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">P.Costo</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">Total Costo</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">P.V.P.</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">Total P.V.P.</th>
                    <th style="cursor:pointer;color:rgb(255,255,255);text-align:center;" scope="col">STOCK</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $correlativo = 1; // Inicializamos en 1
                $totalGeneralcosto = 0;
                $totalGeneralprecio = 0;
                while ($row = $result->fetch_assoc()) {
                    $total_costo = $row['costos'] * $row['existencia']; // cálculo 
                    $total_pvp = $row['precio'] * $row['existencia']; // cálculo
                    $totalGeneralcosto += $total_costo;
                    $totalGeneralprecio += $total_pvp;
                    // // Color dinámico según stock
                    $color_stock = ($row['existencia'] > 0) ? "blue" : "red"; ?>
                    <tr>
                        <td style="text-align:center;"><?= $correlativo++ ?></td> <!-- Correlativo -->
                        <td style="text-align:center; width:100px;"><?= $row['codproducto'] ?></td>
                        <td style="text-align:left;"><?= mb_convert_encoding($row['descripcion'],'ISO-8859-1') ?></td>
                        <td style="text-align:right;"><?= number_format($row['costos'], 2) ?></td>
                        <td style="text-align:right; font-weight:bold; color:red;"><?= number_format($total_costo, 2) ?>
                        </td> <!-- Costo × Existencia -->
                        <td style="text-align:right;"><?= number_format($row['precio'], 2) ?></td>
                        <td style="text-align:right; font-weight:bold; color:blue;"><?= number_format($total_pvp, 2) ?></td>
                        <!-- Costo × Existencia -->
                        <td style="text-align:center; font-weight:bold; color:<?= $color_stock ?>;">
                            <?= $row['existencia'] ?>
                        </td>
                    </tr>
                <?php } ?>
                <!-- Mostrar totales arriba -->
                <div style="font-weight:bold; margin-bottom:24px;">
                    <h4 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <span style="color:red;">Total Costo S/. :
                        <?= number_format($totalGeneralcosto, 2) ?></span>
                        &nbsp;&nbsp; | &nbsp;&nbsp;
                        <span style="color:blue;">Total Venta S/.:
                            <?= number_format($totalGeneralprecio, 2) ?></span>
                        &nbsp;&nbsp; | &nbsp;&nbsp;
                        <span style="color:blue;">Total Diferencia S/. :
                            <?= number_format($totalGeneralprecio - $totalGeneralcosto, 2) ?></span>
                    </h4>
                </div>
            </tbody>

        </table>
    </div>
</body>

</html>