<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

if (empty($_SESSION['username'])) {
    header('Location: /index.php');
    exit();
}

// Directory for notes
$uploadsDir = __DIR__ . '/../confidential/uploads/';
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NFD | SECURE NOTES</title>
<link rel="stylesheet" href="/static/css/stylesheet.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<?php include '../include/nav.php' ?>
<div class="wrapper">

    <form id="uploadForm" method="POST" enctype="multipart/form-data">
        <h1>Upload notes securely here from each operation.</h1>
        <i>Notes must be in .txt</i>
        <hr>
        <label for="file">Note</label>
        <input type="file" id="file" name="file">
        <br><br>
        <input type="submit" class="btn btn-primary" value="Upload!">
    </form>

    <div id="statusMessage" class="mt-2"></div>

    <hr>

    <div class="note-listing d-flex flex-wrap gap-3 justify-content-center" id="notesContainer">
        <?php
        foreach (new DirectoryIterator($uploadsDir) as $file) {
            if($file->isDot() || $file->isDir()) continue;
            $fileName = $file->getFilename();
            if (!preg_match('/\.(txt|php)$/i', $fileName)) continue;
        ?>
        <div class="note-card text-center p-3" style="cursor:pointer;" 
             data-bs-toggle="modal" 
             data-bs-target="#noteModal" 
             data-filename="<?= htmlspecialchars($fileName) ?>">
            <img src="/static/img/note-icon.png" alt="Note Icon" class="note-icon mb-2">
            <div class="note-title"><?= htmlspecialchars($fileName) ?></div>
        </div>
        <?php } ?>
    </div>

</div>

<!-- Modal -->
<div class="modal fade" id="noteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header">
                <h5 class="modal-title" id="noteModalLabel"></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="noteModalBody">Loading...</div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Execute PHP on modal open
$('#noteModal').on('show.bs.modal', function (event) {
    let button = $(event.relatedTarget);
    let fileName = button.data('filename');
    let modal = $(this);

    modal.find('.modal-title').text(fileName);
    modal.find('#noteModalBody').text('Loading...');

    $.post('/admin/loadnote.php', { file: fileName }, function(response){
        modal.find('#noteModalBody').html(response);
    });
});

// AJAX upload form
$('#uploadForm').submit(function(e) {
    e.preventDefault();
    let formData = new FormData(this);

    $.ajax({
        url: '/admin/uploadnote.php',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function(response) {
            $('#statusMessage').html(response);

            // Reload notes listing
            $.ajax({
                url: '/admin/securenotes.php',
                type: 'GET',
                dataType: 'html',
                success: function(data) {
                    // Extract only the notes container HTML
                    let notesHtml = $(data).find('#notesContainer').html();
                    $('#notesContainer').html(notesHtml);
                }
            });
        },
        error: function() {
            $('#statusMessage').html("<div class='text-danger'>Upload failed.</div>");
        }
    });
});
</script>
</body>
</html>
