<?php include('include/headscript.php'); ?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Verifica connessione
if ($conn->connect_error) {
    die("Errore di connessione: " . $conn->connect_error);
}

// Recupera l'elenco delle sezioni
$querySections = $conn->query("SELECT * FROM sections ORDER BY idsections DESC");
$sections = [];
while ($row = $querySections->fetch_assoc()) {
    $sections[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>Gestione Sezioni</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body class="fixed-left">

    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>
        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-12">
                                <h4 class="page-title">Gestione Sezioni</h4>
                                <button class="btn btn-success mb-3" data-toggle="modal" data-target="#addSectionModal">
                                    <i class="mdi mdi-plus"></i> Aggiungi Sezione
                                </button>
                                <table id="sectionsTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Nome</th>
                                            <th>Descrizione</th>
                                            <th>Azioni</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($sections as $section) { ?>
                                            <tr>
                                                <td><?php echo $section['idsections']; ?></td>
                                                <td><?php echo htmlspecialchars($section['section_name']); ?></td>
                                                <td><?php echo htmlspecialchars($section['description']); ?></td>
                                                <td>
                                                    <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#editSectionModal"
                                                        data-id="<?php echo $section['idsections']; ?>"
                                                        data-name="<?php echo htmlspecialchars($section['section_name']); ?>"
                                                        data-description="<?php echo htmlspecialchars($section['description']); ?>">
                                                        <i class="mdi mdi-pencil"></i>
                                                    </button>
                                                    <button class="btn btn-danger btn-sm delete-section"
                                                        data-id="<?php echo $section['idsections']; ?>">
                                                        <i class="mdi mdi-delete"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div> <!-- container -->
                </div> <!-- Page content Wrapper -->
            </div> <!-- content -->
            <?php include('include/footer.php'); ?>
        </div> <!-- End Right content here -->
    </div> <!-- END wrapper -->

    <!-- Modale: Aggiungi Sezione -->
    <div class="modal fade" id="addSectionModal" tabindex="-1" role="dialog" aria-labelledby="addSectionModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form action="add-section.php" method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addSectionModalLabel">Aggiungi Sezione</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="sectionName">Nome Sezione</label>
                            <input type="text" class="form-control" id="sectionName" name="section_name" required>
                        </div>
                        <div class="form-group">
                            <label for="sectionDescription">Descrizione</label>
                            <textarea class="form-control" id="sectionDescription" name="description"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
                        <button type="submit" class="btn btn-success">Salva</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modale: Modifica Sezione -->
    <div class="modal fade" id="editSectionModal" tabindex="-1" role="dialog" aria-labelledby="editSectionModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form action="edit-section.php" method="POST">
                    <input type="hidden" id="editSectionId" name="idsections">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editSectionModalLabel">Modifica Sezione</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="editSectionName">Nome Sezione</label>
                            <input type="text" class="form-control" id="editSectionName" name="section_name" required>
                        </div>
                        <div class="form-group">
                            <label for="editSectionDescription">Descrizione</label>
                            <textarea class="form-control" id="editSectionDescription" name="description"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
                        <button type="submit" class="btn btn-warning">Salva Modifiche</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#sectionsTable').DataTable();

            // Popola i campi del modale di modifica
            $('#editSectionModal').on('show.bs.modal', function(event) {
                var button = $(event.relatedTarget);
                var id = button.data('id');
                var name = button.data('name');
                var description = button.data('description');

                $('#editSectionId').val(id);
                $('#editSectionName').val(name);
                $('#editSectionDescription').val(description);
            });

            // Elimina sezione con SweetAlert2
            $('.delete-section').on('click', function() {
                var sectionId = $(this).data('id'); // Recupera l'id dal pulsante

                Swal.fire({
                    title: 'Sei sicuro?',
                    text: "Questa azione non può essere annullata!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Sì, elimina!',
                    cancelButtonText: 'Annulla'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Effettua la chiamata per eliminare la sezione
                        fetch(`delete-section.php?idsections=${sectionId}`, {
                                method: 'GET'
                            })
                            .then(response => response.text())
                            .then(data => {
                                Swal.fire(
                                    'Eliminato!',
                                    'La sezione è stata eliminata con successo.',
                                    'success'
                                ).then(() => {
                                    // Ricarica la pagina per aggiornare la tabella
                                    location.reload();
                                });
                            })
                            .catch(error => {
                                Swal.fire(
                                    'Errore!',
                                    'Si è verificato un errore durante l\'eliminazione.',
                                    'error'
                                );
                            });
                    }
                });
            });
        });
    </script>

</body>

</html>