<?php
require '../vendor/autoload.php';
include("../config/conexion.php");

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;

if (isset($_POST['maestro'])) {
    $maestro = $_POST['maestro'];

    $sql = "SELECT rf.idregistro, rf.carnet, rf.nombre, rf.apellidos, rf.carrera, rf.grado, rf.seccion,
                   rf.falta, rf.bimestre, rf.fecha, rf.observaciones, u.nombre AS usuario
            FROM registro_falta rf
            INNER JOIN usuarios u ON rf.idusuario = u.id
            WHERE rf.maestro = ?";
    $stmt = $conexion->prepare($sql);
    $stmt->bind_param("s", $maestro);
    $stmt->execute();
    $resultado = $stmt->get_result();

    if ($resultado->num_rows > 0) {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $encabezados = ['ID', 'Carnet', 'Nombre', 'Apellidos', 'Carrera', 'Grado', 'Sección', 'Falta', 'Bimestre', 'Fecha', 'Observaciones', 'Usuario'];
        $col = 'A';
        foreach ($encabezados as $titulo) {
            $sheet->setCellValue($col . '1', $titulo);
            $sheet->getStyle($col . '1')->getFont()->setBold(true)->getColor()->setARGB(Color::COLOR_WHITE);
            $sheet->getStyle($col . '1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('4B6584');
            $col++;
        }

        $fila = 2;
        while ($row = $resultado->fetch_assoc()) {
            $col = 'A';
            foreach ($row as $valor) {
                $sheet->setCellValue($col . $fila, $valor);
                $col++;
            }
            $fila++;
        }

        foreach (range('A', $sheet->getHighestColumn()) as $col) {
            $sheet->getColumnDimension($col)->setAutoSize(true);
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=\"faltas_maestro_{$maestro}.xlsx\"");
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    } else {
        echo "No se encontraron registros.";
    }
}
