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

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

// Recupera l'elenco dei documenti con il nome della pagina e della sezione
$queryDocuments = $conn->query("
    SELECT d.*, 
           p.namepages AS page_name, 
           s.section_name AS section_name
    FROM documents d 
    LEFT JOIN pages p ON d.page_id = p.idpages
    LEFT JOIN sections s ON d.idsections = s.idsections
    ORDER BY d.document_id DESC
");

$documents = [];
while ($row = $queryDocuments->fetch_assoc()) {
    $documents[] = $row;
}

// Recupera l'elenco dei tag
$queryTags = $conn->query("SELECT tag_id, tag_name FROM tags ORDER BY tag_name ASC");
$tags = [];
while ($row = $queryTags->fetch_assoc()) {
    $tags[$row['tag_id']] = $row['tag_name'];
}
?>

<!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 Documenti</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">
    <link rel="stylesheet" href="https://cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css">
    <!-- Select2 CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        .page-content-wrapper {
            padding-top: 70px;
        }

        .btn-block {
            width: 100%;
        }

        .select2-container .select2-selection--multiple {
            min-height: 38px;
        }
    </style>
</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 mb-4">
                            <div class="col-lg-6">
                                <a href="index.php" class="btn btn-outline-primary btn-block shadow-sm">
                                    <i class="mdi mdi-arrow-left"></i> Torna al Dashboard
                                </a>
                            </div>
                            <div class="col-lg-6">
                                <button class="btn btn-outline-success btn-block shadow-sm" data-toggle="modal" data-target="#addDocumentModal">
                                    <i class="mdi mdi-plus"></i> Aggiungi Documento
                                </button>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-body">
                                        <h4 class="card-title">Elenco Documenti</h4>
                                        <table id="documentsTable" class="table table-striped">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Nome Documento</th>
                                                    <th>Pagina</th>
                                                    <th>Sezione</th>
                                                    <th>Max Documenti</th>
                                                    <th>Obbligatorio</th>
                                                    <th>Tag</th>
                                                    <th>Azioni</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($documents as $document) {
                                                    $tagStmt = $conn->prepare("SELECT t.tag_id, t.tag_name FROM tags t 
                                                                               JOIN document_tags dt ON t.tag_id = dt.tag_id 
                                                                               WHERE dt.document_id = ?");
                                                    $tagStmt->bind_param("i", $document['document_id']);
                                                    $tagStmt->execute();
                                                    $tagResult = $tagStmt->get_result();
                                                    $documentTags = [];
                                                    $documentTagIds = [];
                                                    if ($tagResult) {
                                                        while ($tagRow = $tagResult->fetch_assoc()) {
                                                            $documentTags[] = $tagRow['tag_name'];
                                                            $documentTagIds[] = (int)$tagRow['tag_id'];
                                                        }
                                                    }
                                                    $tagStmt->close();

                                                    // Debug: Stampa il valore di data-tags
                                                    $tagsJson = json_encode($documentTagIds);
                                                    echo "<!-- data-tags value for document_id {$document['document_id']}: $tagsJson -->\n";
                                                ?>
                                                    <tr>
                                                        <td><?php echo $document['document_id']; ?></td>
                                                        <td><?php echo htmlspecialchars($document['document_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($document['page_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($document['section_name']); ?></td>
                                                        <td><?php echo $document['max_documents']; ?></td>
                                                        <td><?php echo $document['is_required'] ? 'Sì' : 'No'; ?></td>
                                                        <td><?php echo implode(', ', $documentTags); ?></td>
                                                        <td>
                                                            <button
                                                                class="btn btn-sm btn-warning"
                                                                data-toggle="modal"
                                                                data-target="#editDocumentModal"
                                                                data-id="<?php echo $document['document_id']; ?>"
                                                                data-name="<?php echo htmlspecialchars($document['document_name']); ?>"
                                                                data-page-id="<?php echo $document['page_id']; ?>"
                                                                data-section-id="<?php echo $document['idsections']; ?>"
                                                                data-max-documents="<?php echo htmlspecialchars($document['max_documents']); ?>"
                                                                data-is-required="<?php echo $document['is_required']; ?>"
                                                                data-notes="<?php echo htmlspecialchars($document['notes']); ?>"
                                                                data-tags="<?php echo json_encode($documentTagIds); ?>">
                                                                <i class="mdi mdi-pencil"></i>
                                                            </button>

                                                            <button class="btn btn-sm btn-danger delete-document" data-id="<?php echo $document['document_id']; ?>">
                                                                <i class="mdi mdi-delete"></i>
                                                            </button>
                                                        </td>
                                                    </tr>
                                                <?php } ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modale: Modifica Documento -->
            <div class="modal fade" id="editDocumentModal" tabindex="-1" role="dialog" aria-labelledby="editDocumentModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <form action="edit-document.php" method="POST">
                            <input type="hidden" id="editDocumentId" name="document_id">
                            <div class="modal-header">
                                <h5 class="modal-title" id="editDocumentModalLabel">Modifica Documento</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <label for="editDocumentName">Nome Documento</label>
                                    <input type="text" class="form-control" id="editDocumentName" name="document_name" required>
                                </div>
                                <div class="form-group">
                                    <label for="editPageId">Pagina</label>
                                    <select class="form-control" id="editPageId" name="page_id" required>
                                        <?php
                                        $pagesQuery = $conn->query("SELECT * FROM pages ORDER BY namepages ASC");
                                        while ($page = $pagesQuery->fetch_assoc()) {
                                            echo "<option value='{$page['idpages']}'>" . htmlspecialchars($page['namepages']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="editSectionId">Sezione</label>
                                    <select class="form-control" id="editSectionId" name="idsections">
                                        <?php
                                        $sectionsQuery = $conn->query("SELECT * FROM sections ORDER BY section_name ASC");
                                        while ($section = $sectionsQuery->fetch_assoc()) {
                                            echo "<option value='{$section['idsections']}'>" . htmlspecialchars($section['section_name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="editMaxDocuments">Max Documenti</label>
                                    <input type="number" class="form-control" id="editMaxDocuments" name="max_documents" min="0">
                                </div>
                                <div class="form-group">
                                    <label for="editIsRequired">Obbligatorio</label>
                                    <select class="form-control" id="editIsRequired" name="is_required">
                                        <option value="0">No</option>
                                        <option value="1">Sì</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="editTags">Tag</label>
                                    <select class="form-control" id="editTags" name="tags[]" multiple="multiple">
                                        <?php foreach ($tags as $tagId => $tagName) {
                                            echo "<option value='$tagId'>" . htmlspecialchars($tagName) . "</option>";
                                        } ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="editNotes">Note</label>
                                    <textarea class="form-control" id="editNotes" name="notes"></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>

            <!-- Modale: Aggiungi Documento -->
            <div class="modal fade" id="addDocumentModal" tabindex="-1" role="dialog" aria-labelledby="addDocumentModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <form action="add-document.php" method="POST">
                            <div class="modal-header">
                                <h5 class="modal-title" id="addDocumentModalLabel">Aggiungi Documento</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">×</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <label for="documentName">Nome Documento</label>
                                    <input type="text" class="form-control" id="documentName" name="document_name" required>
                                </div>
                                <div class="form-group">
                                    <label for="pageId">Pagina</label>
                                    <select class="form-control" id="pageId" name="page_id" required>
                                        <?php
                                        $pagesQuery = $conn->query("SELECT * FROM pages ORDER BY namepages ASC");
                                        while ($page = $pagesQuery->fetch_assoc()) {
                                            echo "<option value='{$page['idpages']}'>" . htmlspecialchars($page['namepages']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="sectionId">Sezione</label>
                                    <select class="form-control" id="sectionId" name="idsections" required>
                                        <?php
                                        $sectionsQuery = $conn->query("SELECT * FROM sections ORDER BY section_name ASC");
                                        while ($section = $sectionsQuery->fetch_assoc()) {
                                            echo "<option value='{$section['idsections']}'>" . htmlspecialchars($section['section_name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="maxDocuments">Max Documenti</label>
                                    <input type="number" class="form-control" id="maxDocuments" name="max_documents" min="0" value="0">
                                </div>
                                <div class="form-group">
                                    <label for="isRequired">Obbligatorio</label>
                                    <select class="form-control" id="isRequired" name="is_required">
                                        <option value="0">No</option>
                                        <option value="1">Sì</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="tags">Tag</label>
                                    <select class="form-control" id="tags" name="tags[]" multiple="multiple">
                                        <?php foreach ($tags as $tagId => $tagName) {
                                            echo "<option value='$tagId'>" . htmlspecialchars($tagName) . "</option>";
                                        } ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="notes">Note</label>
                                    <textarea class="form-control" id="notes" name="notes"></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>

            <?php include('include/footer.php'); ?>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#documentsTable').DataTable({
                "pageLength": 10,
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/Italian.json"
                }
            });

            // Inizializza Select2 per i tag
            $('#tags').select2({
                placeholder: "Seleziona o cerca tag",
                allowClear: true,
                tags: true
            });

            $('#editTags').select2({
                placeholder: "Seleziona o cerca tag",
                allowClear: true,
                tags: true
            });

            $('#editDocumentModal').on('show.bs.modal', function(event) {
                var button = $(event.relatedTarget);

                var documentId = button.data('id');
                var documentName = button.data('name');
                var pageId = button.data('page-id');
                var sectionId = button.data('section-id');
                var maxDocuments = button.data('max-documents');
                var isRequired = button.data('is-required');
                var notes = button.data('notes');
                var tags = button.data('tags') || [];

                console.log("Dati ricevuti dal pulsante:", {
                    documentId,
                    documentName,
                    pageId,
                    sectionId,
                    maxDocuments,
                    isRequired,
                    notes,
                    tags
                });

                $('#editDocumentId').val(documentId);
                $('#editDocumentName').val(documentName);
                $('#editPageId').val(pageId);
                $('#editSectionId').val(sectionId);
                $('#editMaxDocuments').val(maxDocuments);
                $('#editIsRequired').val(isRequired);
                $('#editNotes').val(notes);
                $('#editTags').val(tags).trigger('change');
            });

            $('.delete-document').on('click', function() {
                var documentId = $(this).data('id');

                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) {
                        $.ajax({
                            url: 'delete-document.php',
                            type: 'POST',
                            data: { document_id: documentId },
                            dataType: 'json',
                            success: function(response) {
                                if (response.success) {
                                    Swal.fire(
                                        'Eliminato!',
                                        'Il documento è stato eliminato con successo.',
                                        'success'
                                    ).then(() => {
                                        location.reload();
                                    });
                                } else {
                                    Swal.fire(
                                        'Errore!',
                                        response.message || 'Si è verificato un errore durante l\'eliminazione.',
                                        'error'
                                    );
                                }
                            },
                            error: function() {
                                Swal.fire(
                                    'Errore!',
                                    'Si è verificato un errore durante l\'eliminazione.',
                                    'error'
                                );
                            }
                        });
                    }
                });
            });
        });

        <?php if (isset($_GET['success'])) { ?>
            Swal.fire({
                icon: 'success',
                title: 'Documento aggiunto',
                text: 'Il documento è stato aggiunto con successo.',
            });
        <?php } elseif (isset($_GET['error'])) { ?>
            Swal.fire({
                icon: 'error',
                title: 'Errore',
                text: 'Si è verificato un errore durante l\'aggiunta del documento.',
            });
        <?php } ?>
    </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>

</body>

</html>