<?php
require '../conexao/conexao.php';
require '../configuacoes.php';
require '../sessao.php';

$id_departamento = $_GET['id_departamento'] ?? null;
$departamento = $_GET['departamento'] ?? null;

if (isset($_GET['id']) && $_GET['id'] == '0') {
    $pageTitle = "Incluir Novo Departamento";
} else {
    $pageTitle = "Adicionar Novo Setor ao Departamento $departamento";

    $sql_perfil_acessos = "SELECT * FROM setores s JOIN departamentos d  ON d.id_departamento = s.id_departamento WHERE d.id_departamento = ?";
    $stmt = $connectionmysql->prepare($sql_perfil_acessos);
    $stmt->bind_param("i", $id_departamento);
    $stmt->execute();
    $result_departamento_acessos = $stmt->get_result();
    $departamentos = [];
    while ($row = $result_departamento_acessos->fetch_assoc()) {
        $departamentos[] = $row;
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<?php
include('../geral/header.php');
?>
<style>
    #addModuloButton {
        background-color: #1351b4;
        color: white;
        border: none;
        margin-left: 18px;
        margin-top: 30px;
        border-radius: 3px;
        width: 37px;
        height: 37px;
        font-size: large;
    }
</style>

<body>

    <!-- Navigation Bar-->
    <?php
    include('../geral/menu.php');
    ?>
    <!-- End Navigation Bar-->

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="wrapper">
        <div class="container-fluid">
            <div class="card-box mt-3">
                <div class="row">
                    <div class="col-6 text-left">
                        <h4 class="page-title">
                            <?php echo $pageTitle; ?>
                        </h4>
                    </div>
                    <div class="col-6 text-right">
                        <a href="index.php" class="btn btn-light"><i class="mdi mdi-keyboard-backspace"></i> Voltar</a>
                    </div>
                    <div class="col-12">
                        <hr>
                    </div>
                    <div class="col-12">
                        <form id="PasswordForm" method="post" action="processa_inclusao_alteracao_departamento.php" onsubmit="return validarFormulario();">
                            <div class="form-row-mb-3">
                                <div class="d-flex">
                                    <?php if (isset($_GET['id']) && $_GET['id'] == '0') { ?>
                                        <div class="form-group col-md-3">
                                            <label for="novodepartamento" class="form-label">Novo Departamento</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" id="novodepartamento" placeholder="Novo Departamento" name="novodepartamento" oninput="validarCampo('novodepartamento', this.value)">
                                            </div>
                                        </div>
                                    <?php } else { ?>
                                        <div class="form-group col-md-3">
                                            <label for="novodepartamento" class="form-label">Departamento</label>
                                            <div class="input-group">
                                                <input type="text" class="form-control" id="novodepartamento" placeholder="Departamento" name="novodepartamento" oninput="validarCampo('novodepartamento', this.value)" value="<?php echo (!empty($departamento)) ? $departamento : ""; ?>">
                                            </div>
                                        </div>
                                    <?php } ?>

                                    <div class="form-group col-md-3">
                                        <label for="setor" class="form-label">Novo Setor</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" id="setor" placeholder="Nome Setor" name="setor" oninput="validarCampo('setor', this.value)" value="<?php echo (!empty($meuPerfil)) ? $meuPerfil : ""; ?>">
                                        </div>
                                    </div>

                                    <div class="input-group-append">
                                        <button type="button" id="addModuloButton" onclick="addSetor()">+</button>
                                    </div>
                                </div>

                                <input type="hidden" name="setores" id="setores">
                                <input type="hidden" name="setores_removidos" id="setores_removidos">
                                <input type="hidden" name="id_departamento" id="id_departamento" value="<?php echo htmlspecialchars($id_departamento); ?>">

                                <div class="text-right mb-2">
                                    <button type="submit" class="btn btn-primary">Salvar</button>
                                </div>
                            </div>
                        </form>
                        <?php if (isset($_GET['id']) && $_GET['id'] == '0') {  ?>
                            <table class="table table-striped d-none" id="setorTable">
                                <thead>
                                    <tr>
                                        <th>Nome Setor</th>
                                        <th>Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Setores adicionados aparecerão aqui -->
                                </tbody>
                            </table>
                        <?php }
                        if (isset($_GET['id']) && $_GET['id'] == '1') { ?>
                            <table class="table table-striped" id="setorTable">
                                <thead>
                                    <tr>
                                        <th>Nome Setor</th>
                                        <th>Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($departamentos as $d) { ?>
                                        <tr data-setor-id="<?php echo htmlspecialchars($d['id_setor']); ?>">
                                            <td><?php echo htmlspecialchars($d['nome_setor']); ?></td>
                                            <td>
                                                <button type="button" onclick="markSetorForRemoval(this)" class="remove-modulo">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div> <!-- end container -->
    </div>

    <!-- end wrapper -->

    <!-- ============================================================== -->
    <!-- End Page content -->
    <!-- ============================================================== -->

    <!-- Footer Start -->
    <?php
    include('../geral/footer.php');
    ?>
    <!-- end Footer -->

    <?php
    include('../geral/mensagens_modais.php');
    ?>

    <!-- Vendor js -->
    <script src="../../assets/js/vendor.min.js"></script>


    <!-- Init js-->
    <script src="../../assets/js/pages/form-advanced.init.js"></script>

    <!-- knob plugin -->
    <script src="../../assets/libs/jquery-knob/jquery.knob.min.js"></script>
    <!-- App js-->
    <script src="../../assets/js/app.min.js"></script>

    <script src="../geral/javascript.js"></script>



    <script>
        document.addEventListener('DOMContentLoaded', function() {
            verificarErroNaURL();
        });

        function showModal(modalId, title, message) {
            const modalElement = document.getElementById(modalId);
            const modal = new bootstrap.Modal(modalElement);
            modalElement.querySelector('.modal-title').textContent = title;
            modalElement.querySelector('.modal-body p').innerHTML = message;
            modal.show();
        }

        function verificarErroNaURL() {
            const urlParams = new URLSearchParams(window.location.search);
            const errorMessage = urlParams.get('error');
            if (errorMessage) {
                showModal('exampleModal', 'Erro', errorMessage);
            }
        }

        function addSetor() {
            var setor = document.getElementById("setor");
            var setorValue = setor.value.trim();

            if (setorValue === "") {
                setor.classList.add('is-invalido');
                showModal('exampleModal', 'Informação', 'Por favor, insira o nome do setor.');
                return;
            }

            var table = document.getElementById("setorTable");
            var tbody = table.getElementsByTagName('tbody')[0];
            var newRow = tbody.insertRow();

            var cell1 = newRow.insertCell(0);
            var cell2 = newRow.insertCell(1);

            cell1.innerHTML = setorValue;
            cell2.innerHTML = '<button type="button" onclick="markSetorForRemoval(this)" class="remove-modulo"><i class="fas fa-trash"></i></button>';

            setor.value = "";
            setor.classList.remove('is-invalido');

            updateSetoresField();
            table.classList.remove('d-none');
        }

        function markSetorForRemoval(button) {
            var row = button.parentNode.parentNode;
            var setorId = row.getAttribute('data-setor-id');

            if (setorId) {
                var setoresRemovidosField = document.getElementById("setores_removidos");
                var setoresRemovidos = JSON.parse(setoresRemovidosField.value || "[]");
                setoresRemovidos.push(setorId);
                setoresRemovidosField.value = JSON.stringify(setoresRemovidos);
            }

            row.remove();
            updateSetoresField();
        }

        function updateSetoresField() {
            var setores = [];
            var table = document.getElementById("setorTable");
            var tbody = table.getElementsByTagName('tbody')[0];
            for (var i = 0; i < tbody.rows.length; i++) {
                var row = tbody.rows[i];
                setores.push(row.cells[0].innerText);
            }
            document.getElementById("setores").value = JSON.stringify(setores);
        }

        function validarCampo(id) {
            const campo = document.getElementById(id);
            const valor = campo.value.trim();
            let campoValido = true;

            if (!valor) {
                campoValido = false;
                campo.classList.add('is-invalido');
            } else {
                campo.classList.remove('is-invalido');
            }
            return campoValido;
        }

        function validarFormulario() {
            let novodepartamento = validarCampo("novodepartamento");
            if (!novodepartamento) {
                showModal('exampleModal', 'Informação', 'Por favor, insira o nome do novo Departamento.');
            }
            return novodepartamento;
        }
    </script>

    <style>
        .is-invalido {
            box-shadow: 0 0 5px red;
        }

        .remove-modulo {
            background-color: white;
            color: red;
            border: 1px solid red;
            border-radius: 5px;
            width: 35px;
            padding: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }
    </style>
</body>

</html>