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

$is_guest = !isset($_SESSION['user_id']);
$user_id = $_SESSION['user_id'] ?? null;
$session_id = session_id();
$pdo = db();

$user = [];
if (!$is_guest) {
    $userStmt = $pdo->prepare("SELECT name, email, address, phone FROM users WHERE id = ?");
    $userStmt->execute([$user_id]);
    $user = $userStmt->fetch(PDO::FETCH_ASSOC);
}

// Fetch cart items
if (!$is_guest) {
    $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', $user_id);
} else {
    $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.session_id = :session_id");
    $stmt->bindParam(':session_id', $session_id);
}
$stmt->execute();
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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

$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 = ($subtotal * $service_fee_percentage) / 100;

$discount_amount = $_SESSION['discount_amount'] ?? 0;
$totalPrice = $subtotal + $delivery_fee + $service_fee - $discount_amount;

$_SESSION['total_price'] = $totalPrice;

include 'header.php';
?>

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

<div class="checkout-container">
    <div class="checkout-main">
        <div class="checkout-header">
            <a href="index.php" class="checkout-logo">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" fill="currentColor"/><path d="M12 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z" fill="currentColor"/><path d="M12 14c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" fill="currentColor"/></svg>
                <span>Food Delivery</span>
            </a>
        </div>

        <div id="delivery-step">
            <h3 class="step-title">1. Delivery Details</h3>
            <form id="delivery-form">
                <div class="form-group">
                    <label for="name">Full Name</label>
                    <input type="text" id="name" name="name" class="form-control" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>" required>
                </div>
                <?php if ($is_guest): ?>
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" class="form-control" required>
                </div>
                <?php endif; ?>
                <div class="form-group">
                    <label for="address">Delivery Address</label>
                    <input type="text" id="address" name="address" class="form-control" value="<?php echo htmlspecialchars($user['address'] ?? ''); ?>" required>
                </div>
                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone" class="form-control" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" required>
                </div>
                <button type="button" id="to-payment-btn" class="btn-primary">Continue to Payment</button>
            </form>
        </div>

        <div id="payment-step" style="display: none;">
            <h3 class="step-title">2. Payment Method</h3>
            <div class="payment-methods">
                <div class="payment-method-card" data-method="stripe">
                    <input type="radio" id="stripe-radio" name="payment_method" value="stripe" checked>
                    <label for="stripe-radio">
                        <svg viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg"><path d="M42,12H6A2,2,0,0,0,4,14V34a2,2,0,0,0,2,2H42a2,2,0,0,0,2-2V14A2,2,0,0,0,42,12ZM6,16H42v4H6Zm0,16V24H42v8Z" fill="#000"/><rect x="10" y="28" width="8" height="4" fill="#000"/></svg>
                        <span>Credit or Debit Card</span>
                    </label>
                </div>
                <div class="payment-method-card" data-method="paypal">
                    <input type="radio" id="paypal-radio" name="payment_method" value="paypal">
                    <label for="paypal-radio">
                        <svg viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg"><path d="M24,4A20,20,0,1,0,44,24,20,20,0,0,0,24,4Zm11.2,9.45a.7.7,0,0,1,.6,1l-4.6,17.5a.7.7,0,0,1-1.3.1L24,24.25l-5.9,7.8a.7.7,0,0,1-1.1-.9l4.6-17.5a.7.7,0,0,1,1.3-.1L24,19.75l5.9-7.8A.7.7,0,0,1,35.2,13.45Z" fill="#000"/></svg>
                        <span>PayPal</span>
                    </label>
                </div>
            </div>
            <form id="payment-form" action="create_stripe_session.php" method="POST">
                 <input type="hidden" name="name" id="hidden_name">
                 <input type="hidden" name="email" id="hidden_email">
                 <input type="hidden" name="address" id="hidden_address">
                 <input type="hidden" name="phone" id="hidden_phone">
                <button id="stripe-button" class="btn-primary">Pay with Stripe</button>
            </form>
            <div id="paypal-button-container" style="display: none;"></div>
            <button type="button" id="back-to-delivery-btn" class="btn-secondary">Back to Delivery</button>
        </div>
    </div>

    <div class="checkout-summary">
        <h4>Order Summary</h4>
        <div class="summary-items">
            <?php foreach ($cartItems as $item): ?>
                <div class="summary-item">
                    <span class="item-name"><?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)</span>
                    <span class="item-price">$<?php echo number_format($item['price'] * $item['quantity'], 2); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="summary-total">
            <div class="summary-line">
                <span>Subtotal</span>
                <span>$<?php echo number_format($subtotal, 2); ?></span>
            </div>
            <div class="summary-line">
                <span>Delivery Fee</span>
                <span>$<?php echo number_format($delivery_fee, 2); ?></span>
            </div>
            <div class="summary-line">
                <span>Service Fee</span>
                <span>$<?php echo number_format($service_fee, 2); ?></span>
            </div>
            <?php if ($discount_amount > 0): ?>
            <div class="summary-line discount">
                <span>Discount</span>
                <span>-$<?php echo number_format($discount_amount, 2); ?></span>
            </div>
            <?php endif; ?>
            <div class="summary-line total">
                <span>Total</span>
                <span>$<?php echo number_format($totalPrice, 2); ?></span>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const deliveryStep = document.getElementById('delivery-step');
    const paymentStep = document.getElementById('payment-step');
    const toPaymentBtn = document.getElementById('to-payment-btn');
    const backToDeliveryBtn = document.getElementById('back-to-delivery-btn');
    const deliveryForm = document.getElementById('delivery-form');

    const stripeRadio = document.getElementById('stripe-radio');
    const paypalRadio = document.getElementById('paypal-radio');
    const stripeButton = document.getElementById('stripe-button');
    const paypalButtonContainer = document.getElementById('paypal-button-container');

    const nameInput = document.getElementById('name');
    const emailInput = document.getElementById('email');
    const addressInput = document.getElementById('address');
    const phoneInput = document.getElementById('phone');

    const hiddenName = document.getElementById('hidden_name');
    const hiddenEmail = document.getElementById('hidden_email');
    const hiddenAddress = document.getElementById('hidden_address');
    const hiddenPhone = document.getElementById('hidden_phone');

    toPaymentBtn.addEventListener('click', () => {
        if (deliveryForm.checkValidity()) {
            // Copy values to hidden fields for Stripe form
            hiddenName.value = nameInput.value;
            if (emailInput) {
                hiddenEmail.value = emailInput.value;
            }
            hiddenAddress.value = addressInput.value;
            hiddenPhone.value = phoneInput.value;

            deliveryStep.style.display = 'none';
            paymentStep.style.display = 'block';
        } else {
            deliveryForm.reportValidity();
        }
    });

    backToDeliveryBtn.addEventListener('click', () => {
        paymentStep.style.display = 'none';
        deliveryStep.style.display = 'block';
    });

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

    stripeRadio.addEventListener('change', togglePaymentButtons);
    paypalRadio.addEventListener('change', togglePaymentButtons);
    
    document.querySelectorAll('.payment-method-card').forEach(card => {
        card.addEventListener('click', () => {
            card.querySelector('input[type="radio"]').checked = true;
            togglePaymentButtons();
        });
    });

    togglePaymentButtons();

    paypal.Buttons({
        createOrder: function(data, actions) {
            return actions.order.create({
                purchase_units: [{
                    amount: {
                        value: '<?php echo number_format($totalPrice, 2, '.', ''); ?>'
                    }
                }]
            });
        },
        onApprove: function(data, actions) {
            const formData = new FormData();
            formData.append('orderID', data.orderID);
            formData.append('name', nameInput.value);
            if (emailInput) {
                formData.append('email', emailInput.value);
            }
            formData.append('address', addressInput.value);
            formData.append('phone', phoneInput.value);

            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?order_id=' + details.order_id;
                }
            });
        },
        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'; ?>