<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <title>Consulta de Faltas por Fecha</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
    @media print {
        .no-print {
            display: none;
        }
    }
    </style>
</head>

<body>

    <?php include 'menuconsultas.php'; ?>

    <div class="container mt-5">
        <h2 class="mb-4">Consulta de Faltas por Rango de Fechas</h2>

        <!-- Formulario de búsqueda -->
        <form method="POST" class="row g-3 mb-4">
            <div class="col-md-4">
                <label for="fecha_inicio" class="form-label">Fecha Inicio</label>
                <input type="date" name="fecha_inicio" id="fecha_inicio" class="form-control" required>
            </div>
            <div class="col-md-4">
                <label for="fecha_fin" class="form-label">Fecha Fin</label>
                <input type="date" name="fecha_fin" id="fecha_fin" class="form-control" required>
            </div>
            <div class="col-md-4 align-self-end">
                <button type="submit" class="btn btn-primary">Consultar</button>
            </div>
        </form>

        <?php
        if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["fecha_inicio"], $_POST["fecha_fin"])) {
            include "../config/conexion.php";

            $inicio = $_POST["fecha_inicio"];
            $fin    = $_POST["fecha_fin"];

            echo "<div class='alert alert-info'>Mostrando resultados del <strong>" . htmlspecialchars($inicio) . "</strong> al <strong>" . htmlspecialchars($fin) . "</strong></div>";

            // Botón para exportar a CSV y para imprimir
            echo "
        <form action='exportar_csv.php' method='POST' class='no-print mb-3 d-inline'>
            <input type='hidden' name='fecha_inicio' value='" . htmlspecialchars($inicio) . "'>
            <input type='hidden' name='fecha_fin' value='" . htmlspecialchars($fin) . "'>
            <button type='submit' class='btn btn-success me-2'>Exportar a CSV (.csv)</button>
        </form>
        <button class='btn btn-secondary no-print mb-3' onclick='window.print()'>Imprimir</button>";

            $sql = "
            SELECT
                rf.idregistro, rf.carnet, rf.nombre, rf.apellidos,
                rf.carrera, rf.grado, rf.seccion, rf.falta,
                rf.bimestre, rf.maestro, rf.fecha, rf.observaciones,
                u.nombre AS usuario
            FROM registro_falta rf
            INNER JOIN usuarios u ON rf.idusuario = u.id
            WHERE rf.fecha BETWEEN ? AND ?
        ";

            if ($stmt = $conexion->prepare($sql)) {
                $stmt->bind_param("ss", $inicio, $fin);
                $stmt->execute();
                $stmt->store_result();

                if ($stmt->num_rows > 0) {
                    $meta = $stmt->result_metadata();
                    $fields = [];
                    while ($field = $meta->fetch_field()) {
                        $fields[] = $field->name;
                    }

                    $params = [];
                    foreach ($fields as $field) {
                        $$field = null;
                        $params[] = &$$field;
                    }

                    call_user_func_array([$stmt, 'bind_result'], $params);

                    echo "<table class='table table-bordered table-striped'>";
                    echo "<thead class='table-secondary'><tr>";
                    foreach ($fields as $field) {
                        echo "<th>" . htmlspecialchars($field) . "</th>";
                    }
                    echo "</tr></thead><tbody>";

                    while ($stmt->fetch()) {
                        echo "<tr>";
                        foreach ($fields as $field) {
                            echo "<td>" . htmlspecialchars($$field) . "</td>";
                        }
                        echo "</tr>";
                    }

                    echo "</tbody></table>";
                } else {
                    echo "<div class='alert alert-warning'>No se encontraron registros en ese rango.</div>";
                }

                $stmt->close();
            } else {
                echo "<div class='alert alert-danger'>Error en la consulta: " . $conexion->error . "</div>";
            }
        }
        ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>