<?php
require_once 'class/c_login.php';
require_once 'include/bd_pdo.php';

$user = Login::get_user();

$user->access();
if ($user->acceso == null) {
    // die($access);
    header('Location: main.php?error=1');
} else {
    $user->print_to_log('Materias');
}
$facultad = $user->facultad['facultad_id'] ?? -1;
if ($user->admin) {
    $facultad = null;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Materias</title>
    <?php
    include 'import/html_css_files.php';
    ?>

</head>

<body>
    <?php
    include "import/html_header.php";
    html_header(
        "MATERIAS",
        "Gestión de Checador "
    );
    $user->access();
    $max_count = 30;

    $sql = "SELECT * FROM fs_materias(:nombre, :carrera, :facultad)";
    if (isset($_POST["desc"])) {
        $desc = $_POST["desc"];
        $filter_desc = htmlspecialchars($desc, ENT_QUOTES, 'UTF-8');
    } else {
        $desc = null;
    }

    if (isset($_POST["carrera"])) {
        $pcarrera = $_POST["carrera"];
        $filter_carrera = htmlspecialchars($pcarrera, ENT_QUOTES, 'UTF-8');
    } else {
        $pcarrera = null;
    }

    if ($pcarrera == "") {
        $sql .= "LIMIT 30";
    }
    $fs_materias = query(
        $sql,
        array(":nombre" => $desc, ":carrera" => $pcarrera, ":facultad" => $facultad),
        single: false
    );
    $fs_carreras = query(
        "SELECT * FROM fs_carreras(:facultad, null, null) ORDER BY unaccent(carrera_nombre)",
        array(":facultad" => $facultad),
        single: false
    );

    //print_r($fs_materias);
    
    ?>
    <main class="content marco">

        <!-- Filtro -->
        <div class="row">
            <div class="col-12">
                <form action="materias.php" method="post">
                    <div class="form-box">
                        <div class="form-group row">
                            <label for="filter_desc" class="col-4 col-form-label">Materia</label>
                            <div class="col-8 col-sm-4">
                                <input id="filter_desc" name="desc" type="text" class="form-control" <?php if (isset($filter_desc)) {
                                    echo 'value="' . $filter_desc . '"';
                                } ?>>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="filter_carrera" class="col-4 con-form-label">Carrera</label>
                            <div class="col-8 col-sm-4">
                                <div class="datalist datalist-select mb-1 w-100">
                                    <div class="datalist-input">Mostrar todas</div>
                                    <span class="ing-buscar icono"></span>
                                    <ul style="display:none">
                                        <li data-id="">Mostrar todas</li>
                                        <?php
                                        $nivel_ac = -1;
                                        foreach ($fs_carreras as $carrera) {

                                            if ($nivel_ac != $carrera["nivel_id"]) {
                                                $nivel_ac = $carrera["nivel_id"];
                                                ?>
                                                <li data-id="" class="not-selectable">
                                                    <?= $carrera["nivel_nombre"]; ?>
                                                </li>
                                                <?php
                                            }
                                            ?>
                                            <li data-id="<?= $carrera["carrera_nombre"]; ?>"
                                                class="pl-4 <?= !(isset($filter_carrera) && $carrera["carrera_nombre"] == $filter_carrera) ?: 'selected'; ?>">
                                                <?= $carrera["carrera_nombre"] ?>
                                            </li>
                                            <?php

                                        }
                                        ?>
                                    </ul>
                                    <input type="hidden" id="filter_carrera" name="carrera" value="">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-12 text-center">
                            <button type="submit" class="btn btn-outline-primary">
                                <span class="ing-buscar ing-fw"></span>
                                Filtrar
                            </button>
                            <button type="submit" class="btn btn-outline-danger btn-reset">
                                <span class="ing-borrar ing-fw"></span>
                                Limpiar
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Tabla -->
        <div class="row">
            <div class="col-12 table-responsive">
                <?php
                if ($pcarrera == "") {
                    ?>
                    <p> Se muestran los primeros <strong>
                            <?= $max_count; ?>
                        </strong> resultados. Utiliza los filtros para encontrar la materia que buscas.</p>
                <?php } ?>
                <table class="table table-sm table-striped table-white">
                    <thead class="thead-dark">
                        <tr>
                            <th>Nombre</th>
                            <th>Carrera</th>
                            <th>Editar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if ($fs_materias) {
                            foreach ($fs_materias as $materia) {

                                ?>
                                <tr data-id="<?= $materia["materia_id"]; ?>" id="<?= $materia["materia_id"]; ?>">
                                    <td class="text-primary">
                                        <small>(<?= $materia["clave_materia"]; ?>)</small>
                                        <?= $materia["materia_nombre"]; ?>
                                    </td>
                                    <td class="text-primary">
                                        <?= $materia["carrera_nombre"]; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-outline-primary" data-toggle="modal"
                                            data-target="#modal">
                                            <span class="ing-editar ing-fw"></span>
                                        </button>
                                    </td>
                                </tr>
                                <?php

                            }
                        }
                        ?>
                    </tbody>
                </table>
                <div id="message"></div>
            </div>
        </div>
    </main>
    <!-- Footer -->
    <?php
    include "import/html_footer.php";
    ?>
    <!-- Modal -->
    <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="col-12 modal-title text-center">
                        <span id="modalLable">
                            Editar nombre de Materia
                        </span>
                        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </h4>
                </div>
                <div class="modal-body">
                    <form action="./action/action_materias_update.php" method="post" id="formaModal"
                        onsubmit="return valida_campos()">
                        <input type="hidden" name="id" id="id">
                        <div class="form-box">
                            <div class="form-group row">
                                <label for="nombre" class="col-4 col-form-label">Nombre *</label>
                                <div class="col-8">
                                    <input id="nombre" name="nombre" type="text" class="form-control" maxlength="100"
                                        readonly>
                                </div>
                            </div>
                            <div class="form-group row">
                                <label for="carrera" class="col-4 col-form-label">Carrera *</label>
                                <div class="col-8">
                                    <select id="carrera" name="carrera" class="form-control">
                                        <?php
                                        foreach ($fs_carreras as $carrera) {
                                            echo '<option value="' . $carrera["carrera_id"] . '">' . $carrera["carrera_nombre"] . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="offset-4 col-8">
                                    <button type="submit" class="btn btn-outline-primary" id="submitBtn" data-tipo="1">
                                        <span class="ing-aceptar ing-fw"></span> Guardar
                                    </button>
                                    <button type="reset" class="btn btn-outline-danger" data-dismiss="modal">
                                        <span class="ing-cancelar ing-fw"></span> Cancelar
                                    </button>
                                </div>
                            </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/datalist.js"></script>
    <?php
    require_once 'js/messages.php';
    ?>
    <script>
        function valida_campos() {
            var error = false;
            if ($("#nombre").val() == "") {
                $("#nombre").addClass("is-invalid");
                error = true;
            } else {
                $("#nombre").removeClass("is-invalid");
            }
            if (error) {
                return false;
            } else {
                return true;
            }
        }

        <?php if ($facultad == -1 && !$user->admin) { ?>
            triggerMessage("No se encontraron materias en tu facultad", "Error");
        <?php } else if (!$fs_materias) { ?>
                triggerMessage("No se encontraron materias con estos datos", "Error");
        <?php } ?>

        $(document).on("click", ".btn-reset", function (event) {
            var forma = $(this).parents("form");
            forma.find("input[type=text]").val("");
            setDatalistFirst("#filter_carrera");
            forma.submit();
        });

        $('#modal').on('show.bs.modal', function (event) {
            var id = $(event.relatedTarget).parents("tr").data("id");
            $.ajax({
                url: "action/action_materias_select.php",
                type: "post",
                dataType: "json",
                data: {
                    idmateria: id
                },
                success: function (result) {
                    $("#nombre").val(result[0]["materia_nombre"]);
                    $("#carrera").val(result[0]["carrera_id"]);  // establecer el valor de la carrera
                    $("#id").val(result[0]["materia_id"]);
                },
                error: function () {
                    console.log("Error")
                }
            });
        });

    </script>
</body>

</html>