<?php
$ruta = "../";
require_once "../vendor/autoload.php";
require_once "../class/c_login.php";

if (!isset($_SESSION['user'])) {
    http_response_code(401);
    die(json_encode(['error' => 'unauthorized']));
}
$user = unserialize($_SESSION['user']);

$facultad_id = $user->facultad["facultad_id"];

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

// Create the Spreadsheet
$spreadsheet = new Spreadsheet();

// Get data for each 'puesto'
$puestos = $db->orderBy('nombre')->where('facultad_id', $facultad_id)->get('puesto', columns: ['nombre', 'puesto_id']);

$sheetIndex = 0;  // To track and switch between sheets

foreach ($puestos as $puesto) {
    // Create a new worksheet for each 'puesto'
    if ($sheetIndex == 0) {
        // Use the first default sheet
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle(substr($puesto['nombre'], 0, 31));  // Name the first sheet
    } else {
        $sheet = $spreadsheet->createSheet(); // Create new sheet
        $sheet->setTitle(substr($puesto['nombre'], 0, 31));  // Set sheet title to puesto name
    }

    // Get associated materias for current puesto
    $materias = $db
        ->join('materia m', 'm.materia_id = pm.materia_id')
        ->orderBy('materia_nombre')
        ->where('puesto_id', $puesto['puesto_id'])
        ->get('puesto_materia pm', columns: ['clave_materia', 'materia_nombre']);

    $sheet->setCellValue('A1', $puesto['nombre']);

    // Add header row for each 'materia' table
    $sheet->setCellValue('A2', 'Clave Materia');
    $sheet->setCellValue('B2', 'Materia Nombre');

    // Set some styling for headers
    $sheet->getStyle('A2:B2')->getFont()->setBold(true);
    $sheet->getStyle('A2:B2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

    // Start populating from the second row
    $row = 2;

    // Populate the sheet with materias data
    foreach ($materias as $materia) {
        $sheet->setCellValue("A$row", $materia['clave_materia']);
        $sheet->setCellValue("B$row", $materia['materia_nombre']);
        $row++;
    }

    // Auto-size columns
    foreach (range('A', 'B') as $column) {
        $sheet->getColumnDimension($column)->setAutoSize(true);
    }

    // Move to the next sheet index
    $sheetIndex++;
}

// Set the first sheet as active when the Excel file is opened
$spreadsheet->setActiveSheetIndex(0);

// Output the file for download
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="materias_por_puesto.xlsx"');
header('Cache-Control: max-age=0');

$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
