<?php
session_start();
if (!isset($_SESSION['user_email'])) { // Or any other session variable that indicates a logged-in user
    header("Location: index.php"); // Redirect to login page
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PharmaEase</title>
    <link rel="stylesheet" href="navbar_styles.css">
    <link rel="stylesheet" href="cart.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Days+One&family=Lexend:wght@100..900&family=Teko:wght@300..700&display=swap');
    </style>
</head>

<body>
    <section id="homebg">
        <nav class="navbar">
            <div class="navbar-container">
                <a href="home.php" 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="../../controller/logout.php" class="nav-link">Logout</a>
                    </li>
                </ul>
            </div>
        </nav>
        <section id="welcome">
            <h1>Welcome to PharmaEase <br>
                A service you can trust</h1>
        </section>
        <section id="whitespace">
            <br><br><br><br><br><br><br><br>

        </section>
    </section>

    <section id="mycart">
        <h1>My Cart</h1>
        <div id="cart-items"></div>
        <h2 id="cart-total"></h2>
    </section>


    <script>
        const cart = JSON.parse(localStorage.getItem('cart')) || [];
        const cartContainer = document.getElementById('cart-items');
        const cartTotal = document.getElementById('cart-total');

        function renderCart() {
            cartContainer.innerHTML = '';
            let totalAmount = 0;

            if (cart.length === 0) {
                cartContainer.textContent = 'Your cart is empty.';
                cartTotal.textContent = '';
            } else {
                cart.forEach((item, index) => {
                    const div = document.createElement('div');
                    div.style.marginBottom = '15px';
                    div.style.padding = '10px';
                    div.style.border = '1px solid #ccc';
                    div.style.borderRadius = '8px';
                    div.style.display = 'flex';
                    div.style.justifyContent = 'space-between';
                    div.style.alignItems = 'center';
                    div.style.maxWidth = '600px';

                    const itemInfo = document.createElement('span');
                    let cleanPrice = parseFloat(item.price.toString().replace('₱', ''));
                    itemInfo.textContent = `${item.name} - ₱${cleanPrice.toFixed(2)} x ${item.quantity}`;

                    const removeBtn = document.createElement('button');
                    removeBtn.textContent = 'Remove';
                    removeBtn.style.backgroundColor = '#e74c3c';
                    removeBtn.style.color = 'white';
                    removeBtn.style.border = 'none';
                    removeBtn.style.padding = '5px 10px';
                    removeBtn.style.borderRadius = '5px';
                    removeBtn.style.cursor = 'pointer';

                    removeBtn.addEventListener('click', () => {
                        removeItem(index);
                    });

                    div.appendChild(itemInfo);
                    div.appendChild(removeBtn);
                    cartContainer.appendChild(div);

                    totalAmount += cleanPrice * item.quantity;
                });

                cartTotal.textContent = `Total: ₱${totalAmount.toFixed(2)}`;
            }

            // Buttons wrapper (always shown)
            let buttonWrapper = document.createElement('div');
            buttonWrapper.style.display = 'flex';
            buttonWrapper.style.marginTop = '15px';

            // Checkout button (only shown if cart has items)
            if (cart.length > 0) {
                let checkoutBtn = document.createElement('button');
                checkoutBtn.textContent = 'Checkout';
                checkoutBtn.style.marginRight = '10px';
                checkoutBtn.style.padding = '8px 16px';
                checkoutBtn.style.backgroundColor = '#4a7c8a';
                checkoutBtn.style.color = 'white';
                checkoutBtn.style.border = 'none';
                checkoutBtn.style.borderRadius = '6px';
                checkoutBtn.style.cursor = 'pointer';
                checkoutBtn.style.fontSize = '14px';
                checkoutBtn.style.width = 'fit-content';
                checkoutBtn.style.transition = 'background-color 0.3s ease';

                checkoutBtn.addEventListener('mouseover', () => {
                    checkoutBtn.style.backgroundColor = '#3a6b76';
                });
                checkoutBtn.addEventListener('mouseout', () => {
                    checkoutBtn.style.backgroundColor = '#4a7c8a';
                });
                checkoutBtn.addEventListener('click', () => {
                    const cartDataForCheckout = JSON.parse(localStorage.getItem('cart')) || [];

                    if (cartDataForCheckout.length === 0) {
                        alert('Your cart is empty. Cannot proceed to checkout.');
                        return;
                    }

                    let history = JSON.parse(localStorage.getItem('checkoutHistory')) || [];
                    const now = new Date();
                    const formattedDate = `${now.getMonth() + 1}/${now.getDate()}/${now.getFullYear().toString().slice(-2)}`;
                    const totalQuantity = cartDataForCheckout.reduce((sum, item) => sum + item.quantity, 0);
                    const entry = {
                        date: formattedDate,
                        items: cartDataForCheckout.map(item => item.name),
                        quantity: totalQuantity,
                        products: cartDataForCheckout
                    };
                    history.push(entry);
                    localStorage.setItem('checkoutHistory', JSON.stringify(history));
                    localStorage.removeItem('cart'); // Clear cart AFTER preparing data for submission

                    alert('Checkout successful! Proceeding to get your queue number...');

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

                    const cartInput = document.createElement('input');
                    cartInput.type = 'hidden';
                    cartInput.name = 'cart_items_json';
                    cartInput.value = JSON.stringify(cartDataForCheckout); // Use the cart data captured before clearing
                    form.appendChild(cartInput);

                    document.body.appendChild(form);
                    form.submit();
                });

                buttonWrapper.appendChild(checkoutBtn);
            }

            // Check History button (always shown)
            let historyBtn = document.createElement('button');
            historyBtn.textContent = 'Check History';
            historyBtn.style.padding = '8px 16px';
            historyBtn.style.backgroundColor = '#4a7c8a';
            historyBtn.style.color = 'white';
            historyBtn.style.border = 'none';
            historyBtn.style.borderRadius = '6px';
            historyBtn.style.cursor = 'pointer';
            historyBtn.style.fontSize = '14px';
            historyBtn.style.width = 'fit-content';
            historyBtn.style.transition = 'background-color 0.3s ease';

            historyBtn.addEventListener('mouseover', () => {
                historyBtn.style.backgroundColor = '#3a6b76';
            });
            historyBtn.addEventListener('mouseout', () => {
                historyBtn.style.backgroundColor = '#4a7c8a';
            });
            historyBtn.addEventListener('click', () => {
                window.location.href = 'history.php';
            });

            buttonWrapper.appendChild(historyBtn);
            cartContainer.appendChild(buttonWrapper);
        }

        function removeItem(index) {
            cart.splice(index, 1);
            localStorage.setItem('cart', JSON.stringify(cart));
            renderCart();
        }

        renderCart();

    </script>



</body>

</html>