<?php
session_start();
require_once 'db/config.php';

$user_id = $_SESSION['user_id'] ?? null;
$session_id = session_id();
$pdoconnection = db();

// Fetch cart items
if ($user_id) {
    $stmt = $pdoconnection->prepare("SELECT c.id, mi.name, mi.price, c.quantity, r.name as restaurant_name FROM cart c JOIN menu_items mi ON c.menu_item_id = mi.id JOIN restaurants r ON mi.restaurant_id = r.id WHERE c.user_id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
} else {
    $stmt = $pdoconnection->prepare("SELECT c.id, mi.name, mi.price, c.quantity, r.name as restaurant_name FROM cart c JOIN menu_items mi ON c.menu_item_id = mi.id JOIN restaurants r ON mi.restaurant_id = r.id WHERE c.session_id = :session_id");
    $stmt->bindParam(':session_id', $session_id);
}

$stmt->execute();
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalPrice = 0;

include 'header.php';
?>

<div class="container mt-5">
    <h2 class="text-center mb-4">Your Shopping Cart</h2>

    <?php if (isset($_SESSION['coupon_error'])): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo $_SESSION['coupon_error']; unset($_SESSION['coupon_error']); ?>
        </div>
    <?php endif; ?>

    <?php if (count($cartItems) > 0): ?>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Item</th>
                    <th scope="col">Price</th>
                    <th scope="col">Quantity</th>
                    <th scope="col">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($cartItems as $item): ?>
                    <?php
                    $itemTotal = $item['price'] * $item['quantity'];
                    $totalPrice += $itemTotal;
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($item['name']); ?></td>
                        <td>$<?php echo number_format($item['price'], 2); ?></td>
                        <td><?php echo $item['quantity']; ?></td>
                        <td>$<?php echo number_format($itemTotal, 2); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="row mt-4">
            <div class="col-md-6">
                <form action="apply_coupon.php" method="POST">
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" placeholder="Coupon Code" name="coupon_code" required>
                        <button class="btn btn-secondary" type="submit">Apply Coupon</button>
                    </div>
                </form>
            </div>
            <div class="col-md-6 text-end">
                <h4>Subtotal: $<?php echo number_format($totalPrice, 2); ?></h4>
                <?php
                // Fetch settings from the database
                $settingsStmt = $pdoconnection->query("SELECT name, value FROM settings WHERE name IN ('delivery_fee', 'service_fee_percentage')");
                $settings = $settingsStmt->fetchAll(PDO::FETCH_KEY_PAIR);

                $delivery_fee = $settings['delivery_fee'] ?? 0;
                $service_fee_percentage = $settings['service_fee_percentage'] ?? 0;
                
                $service_fee = ($totalPrice * $service_fee_percentage) / 100;

                $discount_amount = 0;
                if (isset($_SESSION['coupon_code']) && isset($_SESSION['discount_percentage'])) {
                    $discount_percentage = $_SESSION['discount_percentage'];
                    $discount_amount = ($totalPrice * $discount_percentage) / 100;
                ?>
                    <h5 class="text-success">Discount (<?php echo htmlspecialchars($_SESSION['coupon_code']); ?> @ <?php echo $discount_percentage; ?>%): -$<?php echo number_format($discount_amount, 2); ?></h5>
                    <a href="remove_coupon.php" class="btn btn-danger btn-sm mt-2">Remove Coupon</a>
                <?php
                }
                
                $final_total = $totalPrice - $discount_amount + $delivery_fee + $service_fee;

                ?>
                <h5>Delivery Fee: $<?php echo number_format($delivery_fee, 2); ?></h5>
                <h5>Service Fee (<?php echo htmlspecialchars($service_fee_percentage); ?>%): $<?php echo number_format($service_fee, 2); ?></h5>
                <h3>Total: $<?php echo number_format($final_total, 2); ?></h3>
                <?php

                $_SESSION['total_price'] = $final_total;
                $_SESSION['discount_amount'] = $discount_amount;
                $_SESSION['subtotal'] = $totalPrice;
                ?>
                <a href="checkout.php" class="btn btn-primary mt-3">Proceed to Checkout</a>
            </div>
        </div>
    <?php else: ?>
        <div class="text-center">
            <p>Your cart is empty.</p>
            <a href="index.php" class="btn btn-primary">Continue Shopping</a>
        </div>
    <?php endif; ?>
</div>

<?php require_once 'footer.php'; ?>