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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];
$pdo = db();

$stmt = $pdo->prepare("SELECT c.id, mi.name, mi.price, c.quantity, r.name as restaurant_name, r.id as restaurant_id 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', $userId);
$stmt->execute();
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($cartItems)) {
    header("Location: cart.php");
    exit();
}

$totalPrice = 0;
foreach ($cartItems as $item) {
    $totalPrice += $item['price'] * $item['quantity'];
}

// Fetch settings from the database
$settingsStmt = $pdo->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;
$totalPriceWithFees = $totalPrice + $delivery_fee + $service_fee;



include 'header.php';
?>

<script src="https://www.paypal.com/sdk/js?client-id=<?php echo $paypalClientId; ?>&currency=USD"></script>
<script src="https://js.stripe.com/v3/"></script>

<div class="container mt-5">
    <h2 class="text-center mb-4">Checkout</h2>
    <div class="row">
        <div class="col-md-7">
            <h4>Delivery Information</h4>
            <form id="payment-form" action="create_stripe_session.php" method="POST">
                <div class="mb-3">
                    <label for="name" class="form-label">Full Name</label>
                    <input type="text" class="form-control" id="name" name="name" required>
                </div>
                <div class="mb-3">
                    <label for="address" class="form-label">Address</label>
                    <input type="text" class="form-control" id="address" name="address" required>
                </div>
                <div class="mb-3">
                    <label for="phone" class="form-label">Phone Number</label>
                    <input type="text" class="form-control" id="phone" name="phone" required>
                </div>

                <h4 class="mt-4">Payment Method</h4>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="payment_method" id="stripe-radio" value="stripe" checked>
                    <label class="form-check-label" for="stripe-radio">
                        Pay with Credit Card (Stripe)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="payment_method" id="paypal-radio" value="paypal">
                    <label class="form-check-label" for="paypal-radio">
                        Pay with PayPal
                    </label>
                </div>

                <button id="stripe-button" type="submit" class="btn btn-primary mt-3">Proceed to Payment</button>
            </form>
            <div id="paypal-button-container" class="mt-3" style="display: none;"></div>
        </div>

        <div class="col-md-5">
            <h4>Order Summary</h4>
            <ul class="list-group mb-3">
                <?php foreach ($cartItems as $item): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)
                        <span>$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                    </li>
                <?php endforeach; ?>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    Delivery Fee
                    <span>$<?php echo number_format($delivery_fee, 2); ?></span>
                </li>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    Service Fee (<?php echo htmlspecialchars($service_fee_percentage); ?>%)
                    <span>$<?php echo number_format($service_fee, 2); ?></span>
                </li>
                <li class="list-group-item d-flex justify-content-between align-items-center fw-bold">
                    Total
                    <span>$<?php echo number_format($totalPriceWithFees, 2); ?></span>
                </li>
            </ul>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('payment-form');
    const stripeButton = document.getElementById('stripe-button');
    const paypalButtonContainer = document.getElementById('paypal-button-container');
    const stripeRadio = document.getElementById('stripe-radio');
    const paypalRadio = document.getElementById('paypal-radio');

    function togglePaymentMethod() {
        if (paypalRadio.checked) {
            stripeButton.style.display = 'none';
            paypalButtonContainer.style.display = 'block';
        } else {
            stripeButton.style.display = 'block';
            paypalButtonContainer.style.display = 'none';
        }
    }

    stripeRadio.addEventListener('change', togglePaymentMethod);
    paypalRadio.addEventListener('change', togglePaymentMethod);

    // Initial check
    togglePaymentMethod();

    // PayPal integration
    paypal.Buttons({
        createOrder: function(data, actions) {
            // Basic validation
            if (!document.getElementById('name').value || !document.getElementById('address').value || !document.getElementById('phone').value) {
                alert('Please fill out the delivery information before proceeding.');
                return false;
            }
            return actions.order.create({
                purchase_units: [{
                    amount: {
                        value: '<?php echo number_format($totalPriceWithFees, 2, '.', ''); ?>'
                    }
                }]
            });
        },
        onApprove: function(data, actions) {
            // Capture delivery info and submit
            const name = document.getElementById('name').value;
            const address = document.getElementById('address').value;
            const phone = document.getElementById('phone').value;

            const formData = new FormData();
            formData.append('orderID', data.orderID);
            formData.append('name', name);
            formData.append('address', address);
            formData.append('phone', phone);

            fetch('paypal-capture.php', {
                method: 'POST',
                body: formData
            }).then(res => res.json())
            .then(details => {
                if (details.error) {
                    alert(details.error);
                    window.location.href = 'payment-cancel.php';
                } else {
                    window.location.href = 'order_confirmation.php';
                }
            });
        },
        onError: function(err) {
            console.error('PayPal Error:', err);
            alert('An error occurred with your PayPal payment.');
        }
    }).render('#paypal-button-container');
});
</script>

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