<?php
require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (isset($_POST['carnet'], $_POST['fecha_inicio'], $_POST['fecha_fin'])) {
    include("../config/conexion.php");

    $carnet = $_POST['carnet'];
    $inicio = $_POST['fecha_inicio'];
    $fin    = $_POST['fecha_fin'];

    $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.carnet = ? AND rf.fecha BETWEEN ? AND ?
    ";

    $stmt = $conexion->prepare($sql);
    $stmt->bind_param("sss", $carnet, $inicio, $fin);
    $stmt->execute();
    $res = $stmt->get_result();

    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setTitle("Faltas Alumno");

    $columns = $res->fetch_fields();
    $col = 'A';

    foreach ($columns as $field) {
        $sheet->setCellValue($col . '1', $field->name);
        $col++;
    }

    $rowNum = 2;
    while ($row = $res->fetch_assoc()) {
        $col = 'A';
        foreach ($row as $value) {
            $sheet->setCellValue($col . $rowNum, $value);
            $col++;
        }
        $rowNum++;
    }

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="faltas_alumno_' . date('Ymd') . '.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
}
