<?php
session_start();
$valid_code = '3268'; // Set your secret code here

// Check for session or cookie
if (!isset($_SESSION['authenticated']) && !isset($_COOKIE['authenticated'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $code = $_POST['code'];
        if ($code === $valid_code) {
            $_SESSION['authenticated'] = true;
            setcookie('authenticated', 'true', time() + (86400 * 30), "/"); // Set cookie for 30 days
            header('Location: index.php');
            exit();
        } else {
            $error = 'Invalid code. Please try again.';
        }
    }
    // Show the login form if not authenticated
    ?>
    <form method="POST" action="">
        <input type="password" name="code" placeholder="Enter code" required>
        <button type="submit">Login</button>
        <?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
    </form>
    <?php
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Qnote</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: auto;
            padding: 20px;
        }
        .note {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            background-color: #f9f9f9;
        }
        .note strong {
            font-weight: bold;
            color: red;
        }
        .details {
            display: none;
        }
        .details-toggle {
            color: #007BFF;
            cursor: pointer;
        }
        .note-actions {
            margin-top: 10px;
        }
        .note-actions button {
            margin-right: 10px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
            padding-top: 20px;
        }
        .modal-content {
            background-color: #fefefe;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
        }
        .close, .open-modal {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover, .close:focus, .open-modal:hover, .open-modal:focus {
            color: black;
            text-decoration: none;
        }
        .open-modal {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .note-form {
            display: flex;
            flex-direction: column;
        }
        .note-form input, .note-form textarea, .note-form button {
            margin-bottom: 10px;
            padding: 10px;
            font-size: 16px;
            width: calc(100% - 20px);
            box-sizing: border-box;
        }
        .note-form textarea {
            resize: vertical;
        }
        @media (max-width: 600px) {
            .note-actions {
                display: flex;
                flex-direction: column;
            }
            .note-actions button {
                margin-bottom: 5px;
                width: 100%;
            }
            .modal-content {
                width: 95%;
                height: 95%;
                padding: 20px;
                box-sizing: border-box;
            }
        }
    </style>
</head>
<body>
    <div id="noteModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <form id="note-form" class="note-form">
                <input type="text" id="obj" placeholder="Objective" required>
                <textarea id="more" placeholder="More"></textarea>
                <textarea id="details" placeholder="Details or Remarks"></textarea>
                <button type="submit">Save Note</button>
            </form>
        </div>
    </div>

    <div id="notes">
        <!-- Notes will be displayed here -->
    </div>
    <div id="pagination">
        <!-- Pagination will be handled here -->
    </div>

    <button class="open-modal">+</button>

    <script>
        var modal = document.getElementById("noteModal");
        var span = document.getElementsByClassName("close")[0];
        var openModalBtn = document.getElementsByClassName("open-modal")[0];

        document.addEventListener('DOMContentLoaded', function() {
            loadNotes();

            document.getElementById('note-form').addEventListener('submit', function(e) {
                e.preventDefault();
                if (document.getElementById('note-form').getAttribute('data-editing') === 'true') {
                    const id = document.getElementById('note-form').getAttribute('data-note-id');
                    updateNote(id);
                } else {
                    addNote();
                }
            });

            span.onclick = function() {
                modal.style.display = "none";
                resetForm();
            }

            openModalBtn.onclick = function() {
                modal.style.display = modal.style.display === "block" ? "none" : "block";
                if (modal.style.display === "block") {
                    resetForm();
                }
            }

            window.onclick = function(event) {
                if (event.target == modal) {
                    modal.style.display = "none";
                    resetForm();
                }
            }

            function resetForm() {
                document.getElementById('note-form').reset();
                document.getElementById('note-form').removeAttribute('data-editing');
                document.getElementById('note-form').removeAttribute('data-note-id');
            }
        });

        function loadNotes(page = 1) {
            fetch(`handler.php?action=fetch&page=${page}`)
                .then(response => response.json())
                .then(data => {
                    displayNotes(data.notes);
                    displayPagination(data.totalPages, page);
                });
        }

        function addNote() {
            let obj = document.getElementById('obj').value;
            let more = document.getElementById('more').value;
            let details = document.getElementById('details').value;
            let mmdd = new Date().toLocaleDateString('en-US', { month: '2-digit', day: '2-digit' }).replace(/\//g, '');

            fetch('handler.php?action=add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ mmdd, obj, more, details })
            }).then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadNotes();
                    resetForm();
                    modal.style.display = "none"; // Close modal after submission
                } else {
                    alert('Failed to add note.');
                }
            });
        }

        function editNote(id) {
            console.log('Edit note id:', id); // Debugging
            fetch(`handler.php?action=fetchSingle&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    console.log('Note data:', data); // Debugging
                    if (data) {
                        document.getElementById('obj').value = data.obj;
                        document.getElementById('more').value = data.more;
                        document.getElementById('details').value = data.details;
                        document.getElementById('note-form').setAttribute('data-editing', 'true');
                        document.getElementById('note-form').setAttribute('data-note-id', id);
                        modal.style.display = "block"; // Open modal for editing
                    } else {
                        alert('Failed to fetch note details.');
                    }
                })
                .catch(error => {
                    console.error('Error fetching note details:', error);
                    alert('An error occurred while fetching the note details.');
                });
        }

        function updateNote(id) {
            let obj = document.getElementById('obj').value;
            let more = document.getElementById('more').value;
            let details = document.getElementById('details').value;

            fetch('handler.php?action=edit&id=' + id, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ obj, more, details })
            }).then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadNotes();
                    resetForm();
                    modal.style.display = "none"; // Close modal after updating
                } else {
                    alert('Failed to update note.');
                }
            });
        }

        function deleteNote(id) {
            if (confirm('Are you sure you want to delete this note?')) {
                fetch(`handler.php?action=delete&id=${id}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            loadNotes();
                        } else {
                            alert('Failed to delete note.');
                        }
                    });
            }
        }

        function archiveNoteHandler(id, button) {
            if (confirm('Are you sure you want to archive this note?')) {
                archiveNote(id, button);
            }
        }

        function archiveNote(id, button) {
            fetch(`handler.php?action=archive&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        button.setAttribute('disabled', 'true');
                        button.style.color = 'gray';
                    } else {
                        alert('Failed to archive note.');
                    }
                });
        }

        function displayNotes(notes) {
            let notesContainer = document.getElementById('notes');
            notesContainer.innerHTML = '';
            notes.forEach(note => {
                notesContainer.innerHTML += `
                    <div class="note">
                        ${note.mmdd}: <strong>${note.obj}</strong> ${note.more ? `> ${note.more}` : ''} 
                        ${note.details ? `<span class="details-toggle"> * </span><span class="details">${note.details}</span>` : ''}
                        <div class="note-actions">
                            <button onclick="editNote(${note.id})">Edit</button>
                            <button onclick="deleteNote(${note.id})">Delete</button>
                            <button class="archive-button" onclick="archiveNoteHandler(${note.id}, this)" ${note.archived == 1 ? 'disabled style="color:gray"' : ''}>Archive</button>
                        </div>
                    </div>
                `;
            });

            document.querySelectorAll('.details-toggle').forEach(toggle => {
                toggle.addEventListener('click', function() {
                    let details = this.nextElementSibling;
                    details.style.display = details.style.display === 'none' ? 'block' : 'none';
                });
            });
        }

        function displayPagination(totalPages, currentPage) {
            let paginationContainer = document.getElementById('pagination');
            paginationContainer.innerHTML = '';
            for (let i = 1; i <= totalPages; i++) {
                paginationContainer.innerHTML += `<button onclick="loadNotes(${i})">${i}</button>`;
            }
        }

        function resetForm() {
            document.getElementById('note-form').reset();
            document.getElementById('note-form').removeAttribute('data-editing');
            document.getElementById('note-form').removeAttribute('data-note-id');
        }
    </script>
</body>
</html>