<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
   
</head>
<body>
    <div class="cart-items">
        <?php
        // Start the session
        session_start();
        
        // Include the database configuration file
        include 'config.php';
        
        // Initialize total price
        $totalPrice = 0.00;
        
        // Check if the user is logged in and user_id is available in the session
        if(isset($_SESSION['user_id'])) {
            $user_id = $_SESSION['user_id'];
        
            // Retrieve cart items for the specific user from the database
            $sql = "SELECT item_name, item_price, quantity, item_image, time_added FROM cart WHERE user_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
        
            // Check if there are items in the cart
            if ($result->num_rows > 0) {
                // Display cart items
                while ($row = $result->fetch_assoc()) {
                    // Initialize subtotal with 0
                    $subtotal = 0.00;
        
                    // Calculate subtotal if item_price and quantity are available
                    if (isset($row['item_price']) && isset($row['quantity'])) {
                        $subtotal = $row['item_price'] * $row['quantity'];
                        // Add subtotal to total price
                        $totalPrice += $subtotal;
                    }
                    ?>
                    <div class="cart-item">
                        <div class="item-image"><img src="<?php echo $row['item_image']; ?>" alt="Item Image"></div>
                        <div class="item-details">
                            <p>Name: <?php echo $row['item_name']; ?></p>
                            <p>Price: <?php echo $row['item_price']; ?></p>
        
                            <div class="quantity-section">
                                 <button class="remove-button" data-item="<?php echo $row['item_name']; ?>">-</button>
                                 <button class="add-button" data-item="<?php echo $row['item_name']; ?>">+</button>
                                 <p>Quantity: <span class="quantity" id="quantity-<?php echo $row['item_name']; ?>"><?php echo $row['quantity']; ?></span></p>
                            </div>

<!-- Confirm Delete Modal -->
<div id="confirmDeleteModal" style="display:none; position:fixed; top:0; left:0; width:100vw; height:100vh; 
    background: rgba(0,0,0,0.5); justify-content:center; align-items:center; z-index:1000;">
    <div style="background:#fff; padding:20px; border-radius:8px; max-width:300px; text-align:center;">
        <p>Do you want to delete this item from your cart?</p>
        <button id="confirmDeleteBtn" style="margin-right:10px; padding:8px 16px; background:#d9534f; color:#fff; border:none; border-radius:4px; cursor:pointer;">Yes</button>
        <button id="cancelDeleteBtn" style="padding:8px 16px; background:#5bc0de; color:#fff; border:none; border-radius:4px; cursor:pointer;">No</button>
    </div>
</div>


        
                            <p>Added Time: <?php echo $row['time_added']; ?></p>
                            <!-- Display Subtotal -->
                            <p>Subtotal: <span class="subtotal" id="subtotal-<?php echo $row['item_name']; ?>"><?php echo number_format($subtotal, 2); ?></span></p>
                        </div>
                    </div>
                    <?php
                }
            } else {
                // If cart is empty for the user
                echo '<p>Your cart is empty.</p>';
            }
        } else {
            // If user is not logged in or user_id is not available in session
            echo '<p>User ID is not available or user is not logged in.</p>';
        }
        
        // Close the database connection
        $stmt->close();
        $conn->close();
        ?>
    </div>

    <script>
        // Paste the JavaScript code here
        document.querySelectorAll('.add-button').forEach(function(button) {
    button.addEventListener('click', function() {
        var itemName = this.getAttribute('data-item');
        updateQuantity(itemName, 1);
    });
});

document.querySelectorAll('.remove-button').forEach(function(button) {
    button.addEventListener('click', function() {
        var itemName = this.getAttribute('data-item');
        var quantityElement = document.getElementById('quantity-' + itemName);
        var currentQuantity = parseInt(quantityElement.textContent);
        var newQuantity = currentQuantity - 1;

        if (newQuantity <= 0) {
            // Show confirmation popup
            showConfirmDelete(itemName, quantityElement, currentQuantity);
        } else {
            updateQuantity(itemName, -1);
        }
    });
});

function showConfirmDelete(itemName, quantityElement, currentQuantity) {
    var modal = document.getElementById('confirmDeleteModal');
    modal.style.display = 'flex';

    var confirmBtn = document.getElementById('confirmDeleteBtn');
    var cancelBtn = document.getElementById('cancelDeleteBtn');

    // Remove previous listeners to avoid multiple triggers
    confirmBtn.onclick = null;
    cancelBtn.onclick = null;

    confirmBtn.onclick = function() {
        // User confirmed deletion
        deleteItemFromCart(itemName);
        modal.style.display = 'none';
    };

    cancelBtn.onclick = function() {
        // User canceled deletion, restore quantity display
        quantityElement.textContent = currentQuantity;
        modal.style.display = 'none';
    };
}

function updateQuantity(itemName, change) {
    var quantityElement = document.getElementById('quantity-' + itemName);
    var currentQuantity = parseInt(quantityElement.textContent);
    var newQuantity = currentQuantity + change;

    if (newQuantity < 0) newQuantity = 0;

    quantityElement.textContent = newQuantity;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'update_quantity.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
        }
    };
    xhr.send('item_name=' + encodeURIComponent(itemName) + '&quantity=' + newQuantity);
}

function deleteItemFromCart(itemName) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'delete_item.php', true); // new PHP file to handle deletion
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
            // Remove item from the DOM or refresh page
            var quantityElement = document.getElementById('quantity-' + itemName);
            var cartItemDiv = quantityElement.closest('.cart-item');
            cartItemDiv.remove();
        }
    };
    xhr.send('item_name=' + encodeURIComponent(itemName));
}

    </script>
</body>
</html>

<style>
    /* Mobile view (up to 600px) */
@media (max-width: 600px) {
    body {
        font-family: Arial, sans-serif;
        padding: 10px;
       
    }

    .cart-items {
        max-width: 100%;
        margin: 0 auto;
    }

    .cart-item {
       
        margin-bottom: 15px;
        padding: 10px;
        border-radius: 8px;
       
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .item-image img {
        max-width: 100%;
        height: auto;
        border-radius: 6px;
        margin-bottom: 10px;
    }

    .item-details {
        width: 100%;
        text-align: center;
    }

    .quantity-section {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 10px;
        margin: 10px 0;
    }

    .quantity-section button {
        padding: 6px 12px;
        font-size: 18px;
        border: none;
        background-color: #007bff;
        color: white;
        border-radius: 5px;
        cursor: pointer;
    }

    .quantity-section button:hover {
        background-color: #0056b3;
    }

    .quantity-section p {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
    }
    
    p {
        margin: 6px 0;
        font-size: 14px;
        color: #333;
    }
}

/* Tablet view (601px to 900px) */
@media (min-width: 601px) and (max-width: 900px) {
    body {
        font-family: Arial, sans-serif;
        padding: 20px;
        background: #f9f9f9;
    }

    .cart-items {
        max-width: 700px;
        margin: 0 auto;
    }

    .cart-item {
        background: white;
        margin-bottom: 20px;
        padding: 15px;
        border-radius: 10px;
        box-shadow: 0 0 8px rgba(0,0,0,0.1);
        display: flex;
        gap: 15px;
        align-items: center;
    }

    .item-image img {
        max-width: 150px;
        height: auto;
        border-radius: 8px;
    }

    .item-details {
        flex: 1;
        text-align: left;
    }

    .quantity-section {
        display: flex;
        align-items: center;
        gap: 10px;
        margin: 10px 0;
    }

    .quantity-section button {
        padding: 8px 16px;
        font-size: 18px;
        border: none;
        background-color: #007bff;
        color: white;
        border-radius: 6px;
        cursor: pointer;
        user-select: none;
    }

    .quantity-section button:hover {
        background-color: #0056b3;
    }

    .quantity-section p {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
    }
    
    p {
        margin: 6px 0;
        font-size: 15px;
        color: #222;
    }
}

</style>
