<?php
require_once 'class/c_login.php';
$user = Login::get_user();
$user->access('excel_horario');

if (in_array($user->acceso, ['r', 'n'])) {
    // die($access);
    header('Location: main.php?error=1');
} else {
    $user->print_to_log('Consultar asistencia');
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Cargar horario desde Excel | <?= $user->facultad['facultad'] ?? 'General' ?></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <?php include_once "import/html_css_files.php"; ?>
</head>

<body style="display: block;">
    <?php
    include('include/constantes.php');
    include("import/html_header.php");
    html_header("Cargar horario desde Excel", "Gestión de Checador");
    ?>
    <main class="container content content-margin" id="local-app">
        <section id="message"></section>
        <?php require('import/periodo.php') ?>
        <form>
            <div class="form-group">
                <div class="form-box">
                    <?php
                    $carreras = query("SELECT * FROM FS_CARRERA WHERE FACULTAD = COALESCE(:fac, FACULTAD) AND PERIODO = COALESCE(:per, PERIODO) ORDER BY CARRERA", [":fac" => $user->facultad['facultad_id'], ":per" => $user->periodo_id], single: false);
                    #die(print_r($carreras, true));
                    ?>
                    <div class="form-group row">
                        <label for="filter_carrera" class="col-4 col-form-label">Carrera</label>
                        <div class="col-6 ">
                            <div id="dlcarrera" class="datalist datalist-select mb-1 w-100">
                                <div class="datalist-input">Seleccionar carrera</div>
                                <span class="ing-buscar icono"></span>
                                <ul style="display:none">
                                    <?php
                                    foreach ($carreras as $carrera) {
                                    ?>
                                        <li data-id="<?= $carrera['id'] ?>">
                                            <?= $carrera['carrera'] ?>
                                        </li>
                                    <?php
                                    }
                                    ?>
                                </ul>
                                <input type="hidden" id="filter_carrera" name="carrera" value="">
                            </div>
                        </div>
                    </div>

                    <div class="form-group row">
                        <label for="excel" class="col-4 col-form-label">Archivo de horarios</label>
                        <div class="col-8 col-sm-6">
                            <input class="form-control-file" id="excel" name="archivo" accept=".xlsx, .xls" require>
                        </div>
                    </div>

                    <div class="form-group mt-5 row justify-content-center">

                        <button id="btn-cargar" type="button" class="btn btn-primary" onclick="submit_files()">
                            <span class="ing-guardar"></span>
                            Cargar horario
                        </button>
                    </div>
                </div>
            </div>

        </form>
    </main>
</body>
<?php
require_once("import/html_footer.php");
require_once("js/messages.php")
?>
<script src="js/scrollables.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>

<script src="js/custominputfile.min-es.js"></script>
<link rel="stylesheet" href="css/custominputfile.min.css">
<script src="js/fetchlib.js"></script>
<script lang="jquery">
    var datum = []

    $(document).ready(function() {

        $('#excel').customFile({
            allowed: ['xlsx', 'xls'],
            maxFiles: 1,
            callbacks: {
                onSuccess: async function(item) {
                    var formData = $.customFile.serialize('archivo');

                    const {
                        status,
                        message,
                        data
                    } = await fetch('action/action_revisar_excel.php', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .catch(error => {
                            return {
                                status: 'error',
                                message: 'Error al cargar el archivo',
                            }
                        });

                    if (status == 'error') {
                        triggerMessage(message, 'Error en el formato del archivo');
                        item.destroy();
                        return
                    }

                    triggerMessage(message, `Archivo revisado`, 'success');
                    datum = data;
                },
            }
        });
    })

    async function submit_files() {
        // disable button
        const button = document.querySelector('#btn-cargar');
        // add class disabled to button
        button.classList.add('disabled');
        // disable button
        button.disabled = true;

        // add loading icon
        button.innerHTML = '<span class="ing-cargando"></span> Cargando...';

        let missing = [];

        let carrera = $('#filter_carrera').val();
        if (carrera == '') missing.push('Carrera');

        if (datum.length == 0) missing.push('Archivo de horarios');

        let facultad = <?= $user->facultad['facultad_id'] ?>;

        if (missing.length > 0) {
            messageMissingInputs(missing);

            // remove class disabled to button
            button.classList.remove('disabled');
            // enable button
            button.disabled = false;

            // remove loading icon
            button.innerHTML = '<span class="ing-guardar"></span> Cargar horario';

            return;
        }

        formData.append('carrera', carrera);
        formData.append('facultad', facultad);
        formData.append('data', JSON.stringify(datum));


        const {
            status,
            message
        } = await fetch('action/action_horario_excel.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .catch(error => {
                return {
                    status: 'error',
                    message: 'Error al cargar el archivo',
                }
            });

        if (status == 'error') {
            triggerMessage(message, 'Error al guardar el archivo');
            return
        }

        triggerMessage(message, `Horarios guardados`, 'success');

        // await 1 second
        await new Promise(resolve => setTimeout(resolve, 1000));

        // reload page
        location.reload();
    }
</script>


</html>