<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
// Get the logged-in user's full name, default to 'Customer' if not set
$loggedInUserName = isset($_SESSION['user_full_name']) ? htmlspecialchars($_SESSION['user_full_name']) : 'Customer';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>PharmaEase</title>
    <link rel="stylesheet" href="history.css" />
</head>

<body>
    <section id="homebg">
        <nav class="navbar">
            <div class="navbar-container">
                <a href="#" class="navbar-brand">
                    <img src="Frame 6.png" alt="PharmaEase Logo">
                    <span>PharmaEase</span> </a>
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a href="home.php" class="nav-link">Home</a>
                    </li>
                    <li class="nav-item">
                        <a href="cart.php" class="nav-link">Cart</a>
                    </li>
                    <li class="nav-item">
                        <a href="users.php" class="nav-link">User</a>
                    </li>
                    <li class="nav-item">
                        <a href="index.php" class="nav-link">Logout</a>
                    </li>
                </ul>
            </div>
        </nav>
		
        <h2>History</h2>
        <section id="history-section">
            <div class="history-container">
                <div class="search-wrapper">
                    <input type="text" id="search-bar" placeholder="Search..." />
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Item</th>
                            <th>Quantity</th>
                            <th>PDF Receipt</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- rows will be populated here by JavaScript -->
                    </tbody>
                </table>
            </div>
        </section>

        <script>
            const currentUserName = '<?php echo $loggedInUserName; ?>'; // Make PHP session name available to JS
            const historyData = JSON.parse(localStorage.getItem('checkoutHistory')) || [];
            const tbody = document.querySelector('tbody');

            // Clear any existing hardcoded rows
            tbody.innerHTML = '';

            // Populate table with history data
            historyData.slice().reverse().forEach((entry, index) => {
                const tr = document.createElement('tr');

                const dateTd = document.createElement('td');
                dateTd.textContent = entry.date;

                const itemTd = document.createElement('td');
                let itemNames = 'N/A';
                if (Array.isArray(entry.products)) {
                    itemNames = entry.products.map(p => p.title).join(', ');
                }
                itemTd.textContent = itemNames;

                const quantityTd = document.createElement('td');
                let totalQuantity = 0;
                if (Array.isArray(entry.products)) {
                    totalQuantity = entry.products.reduce((sum, item) => sum + (item.quantity || 0), 0);
                }
                quantityTd.textContent = totalQuantity;

                const pdfTd = document.createElement('td');
                const viewPdfBtn = document.createElement('button');
                viewPdfBtn.textContent = "view";
                viewPdfBtn.className = "view-pdf-btn";

                pdfTd.appendChild(viewPdfBtn);

                viewPdfBtn.addEventListener('click', () => {
                    const historicalOrderProducts = entry.products;
                    const orderDate = entry.date;

                    if (!historicalOrderProducts || historicalOrderProducts.length === 0) {
                        alert("No product details found for this historical order.");
                        return;
                    }

                    // Create a hidden form to POST data to generateOrderPDF.php
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = '../../controller/generateOrderPDF.php';
                    form.style.display = 'none';

                    // Add cart items (historical products) as a JSON string
                    const cartInput = document.createElement('input');
                    cartInput.type = 'hidden';
                    cartInput.name = 'cart_items_json';
                    cartInput.value = JSON.stringify(historicalOrderProducts);
                    form.appendChild(cartInput);

                    // Add a placeholder for queue number (using order date)
                    const queueInput = document.createElement('input');
                    queueInput.type = 'hidden';
                    queueInput.name = 'queue_number';
                    queueInput.value = 'Order Date: ' + orderDate;
                    form.appendChild(queueInput);

                    // Add a placeholder for user name
                    const nameInput = document.createElement('input');
                    nameInput.type = 'hidden';
                    nameInput.name = 'user_name';
                    nameInput.value = currentUserName; // Use the logged-in user's name
                    form.appendChild(nameInput);

                    document.body.appendChild(form);
                    form.submit();
                    document.body.removeChild(form); // Clean up
                });

                const actionTd = document.createElement('td');
                const deleteBtn = document.createElement('button');
                deleteBtn.textContent = "Delete";
                deleteBtn.className = "delete-btn";

                deleteBtn.addEventListener('click', () => {
                    if (confirm("Are you sure you want to delete this history entry?")) {
                        historyData.splice(historyData.length - 1 - index, 1); // Remove from original array
                        localStorage.setItem('checkoutHistory', JSON.stringify(historyData));
                        tr.remove();
                    }
                });

                actionTd.appendChild(deleteBtn);

                tr.appendChild(dateTd);
                tr.appendChild(itemTd);
                tr.appendChild(quantityTd);
                tr.appendChild(pdfTd);
                tr.appendChild(actionTd);

                tbody.appendChild(tr);
            });
        </script>
</body>

</html>