<?php
// Include the database configuration file
include 'config.php';

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $item_name = $_POST['item_name'];
    $item_price = $_POST['item_price'];
    $item_image = $_POST['item_image'];
    $quantity = $_POST['quantity'];

    // Insert item into the cart table
    $sql = "INSERT INTO cart (item_name, item_price, item_image, quantity) VALUES ('$item_name', '$item_price', '$item_image', '$quantity')";
    if ($conn->query($sql) === TRUE) {
        // Retrieve updated cart items
        $sql = "SELECT item_name, item_price, quantity, item_image, time_added FROM cart";
        $result = $conn->query($sql);

        // Initialize total price variable
        $totalPrice = 0;

        // Check if there are items in the cart
        if ($result->num_rows > 0) {
            // Display cart items
            while ($row = $result->fetch_assoc()) {
                // Calculate subtotal for each item
                $subtotal = $row['item_price'] * $row['quantity'];
                $totalPrice += $subtotal; // Add subtotal to total price
                ?>
                <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">
                            <p>Quantity: <span class="quantity"><?php echo $row['quantity']; ?></span></p>
                            <button class="add-button">+</button>
                        </div>
                        <p>Added Time: <?php echo $row['time_added']; ?></p>
                        <p>Subtotal: <span class="subtotal"><?php echo $subtotal; ?></span></p>
                    </div>
                </div>
                <?php
            }
            // Display total price after all items are listed
            echo "<p id='totalPrice'>Total Price: $totalPrice</p>";
        } else {
            // If cart is empty
            echo "<p>Your cart is empty.</p>";
        }
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Close database connection
$conn->close();
?>
