<?php
#display PHP errors

$ruta = "../";
require_once "../include/bd_pdo.php";
require_once "../include/func_excel.php";
require_once "../include/func_string.php";

use PhpOffice\PhpSpreadsheet\IOFactory;

$reader = IOFactory::createReader("Xlsx");
$reader->setReadDataOnly(true);

$file = $_FILES['archivo'];


$spreadsheet = $reader->load($file['tmp_name'][0]);

$data = [];

try {

    foreach_sheet(
        $spreadsheet, // object $spreadsheet
        function (array $row_data, int $i, string $sheet) {
            global $horario, $data;

            if (renglón_vacío($row_data)) return;
            validar_registro($row_data, $i);

            $horario["horario"] = horario($row_data, $i, $sheet);

            foreach (array_filter($row_data) as $key => $value)
                $horario = array_merge($horario, ($key == 'maestro') ? columna_nombre($value) : [$key => $value]);

            $data[] = $horario;
        }
    );

    die(json_encode([
        "status" => "success",
        "message" => "Horario revisado con éxito, se leyeron: " . count($data) . " registros",
        "data" => $data
    ]));
} catch (Exception $e) {
    die(json_encode([
        "status" => "error",
        "message" => $e->getMessage(),
    ]));
}
