<?php
require_once __DIR__ . '/api/lib.php';
hw_require_auth();

$user = hw_get_auth_user();
$plan = $_GET['plan'] ?? 'personal';
$returnUrl = $_GET['return_url'] ?? '/atasteofafricanmarketplace/dashboard/user/index.php';

// Plan details
$plans = [
    'personal' => [
        'name' => 'Personal Plan',
        'price' => 14.99,
        'billing_cycle' => 'monthly',
        'features' => ['Personalized coaching', 'Health tracking', 'Monthly check-ins', 'Email support']
    ],
    'family' => [
        'name' => 'Family Plan',
        'price' => 29.99,
        'billing_cycle' => 'monthly',
        'features' => ['Up to 4 family members', 'Personalized coaching', 'Advanced tracking', 'Video consultations', 'Priority support', 'Family wellness reports']
    ]
];

$selectedPlan = $plans[$plan] ?? $plans['personal'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - <?= htmlspecialchars($selectedPlan['name']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #f0fdf4 0%, #f0fdf4 50%, #f9fafb 100%);
        }

        .checkout-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            max-width: 1000px;
            margin: 0 auto;
        }

        @media (max-width: 768px) {
            .checkout-container {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .section-title {
            font-size: 18px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #10b981;
            box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
        }

        .payment-method {
            padding: 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            margin-bottom: 12px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .payment-method:hover {
            border-color: #10b981;
            background: #f0fdf4;
        }

        .payment-method input[type="radio"] {
            margin-right: 12px;
        }

        .payment-method.active {
            border-color: #10b981;
            background: #f0fdf4;
        }

        .order-summary {
            background: linear-gradient(135deg, #f0fdf4 0%, #f9fafb 100%);
            padding: 24px;
            border-radius: 12px;
            margin-bottom: 24px;
            border: 1px solid #e5e7eb;
        }

        .summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
            padding-bottom: 16px;
            border-bottom: 1px solid #e5e7eb;
        }

        .summary-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }

        .summary-label {
            color: #6b7280;
            font-size: 14px;
        }

        .summary-value {
            font-weight: 600;
            color: #1f2937;
        }

        .summary-price {
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, #10b981, #059669);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .btn-primary {
            width: 100%;
            padding: 14px 20px;
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            border: none;
            border-radius: 8px;
            font-weight: 700;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
        }

        .trust-badges {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #e5e7eb;
        }

        .badge {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #6b7280;
        }

        .badge i {
            color: #10b981;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div style="padding: 40px 20px;">
        <div class="checkout-container">
            <!-- Left: Checkout Form -->
            <div>
                <div class="card">
                    <!-- Header -->
                    <div style="margin-bottom: 32px; border-bottom: 2px solid #f3f4f6; padding-bottom: 24px;">
                        <h1 style="font-size: 28px; font-weight: 700; color: #1f2937; margin-bottom: 8px;">
                            <i class="fas fa-lock text-emerald-600 mr-2"></i>Secure Checkout
                        </h1>
                        <p style="color: #6b7280; font-size: 14px;">Complete your subscription upgrade</p>
                    </div>

                    <!-- Billing Information -->
                    <div style="margin-bottom: 32px;">
                        <div class="section-title">
                            <i class="fas fa-user text-emerald-600" style="font-size: 18px;"></i>
                            Billing Information
                        </div>

                        <div class="form-group">
                            <label>Full Name</label>
                            <input type="text" value="<?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>" readonly style="background: #f9fafb; color: #6b7280;">
                        </div>

                        <div class="form-group">
                            <label>Email Address</label>
                            <input type="email" value="<?= htmlspecialchars($user['email']) ?>" readonly style="background: #f9fafb; color: #6b7280;">
                        </div>
                    </div>

                    <!-- Payment Method -->
                    <div style="margin-bottom: 32px;">
                        <div class="section-title">
                            <i class="fas fa-credit-card text-emerald-600" style="font-size: 18px;"></i>
                            Payment Method
                        </div>

                        <div class="payment-method active" style="display: flex; align-items: center;">
                            <input type="radio" name="payment_method" value="paypal" checked>
                            <div style="flex: 1; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-paypal" style="font-size: 24px; color: #0070ba;"></i>
                                <div>
                                    <div style="font-weight: 600; color: #1f2937;">PayPal</div>
                                    <div style="font-size: 12px; color: #6b7280;">Fast, secure payment</div>
                                </div>
                            </div>
                        </div>

                        <div class="payment-method" style="display: flex; align-items: center;">
                            <input type="radio" name="payment_method" value="card">
                            <div style="flex: 1; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-credit-card" style="font-size: 24px; color: #6c63ff;"></i>
                                <div>
                                    <div style="font-weight: 600; color: #1f2937;">Credit Card</div>
                                    <div style="font-size: 12px; color: #6b7280;">Visa, Mastercard, Amex</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Card Details (Hidden initially) -->
                    <div id="cardDetails" style="margin-bottom: 32px; display: none;">
                        <div class="form-group">
                            <label>Card Number</label>
                            <input type="text" placeholder="1234 5678 9012 3456" maxlength="19">
                        </div>

                        <div style="display: grid; grid-cols-2 gap: 16px;">
                            <div class="form-group">
                                <label>Expiry Date</label>
                                <input type="text" placeholder="MM/YY" maxlength="5">
                            </div>
                            <div class="form-group">
                                <label>CVC</label>
                                <input type="text" placeholder="123" maxlength="3">
                            </div>
                        </div>
                    </div>

                    <!-- Agreement -->
                    <div style="margin-bottom: 24px; padding: 16px; background: #f0fdf4; border-radius: 8px; border-left: 4px solid #10b981;">
                        <label style="display: flex; align-items: flex-start; gap: 12px; cursor: pointer; font-size: 14px; color: #374151;">
                            <input type="checkbox" checked style="margin-top: 2px; cursor: pointer;">
                            <span>I agree to the subscription terms and auto-renewal policy. I can cancel anytime.</span>
                        </label>
                    </div>

                    <!-- Submit Button -->
                    <button class="btn-primary" onclick="processPayment(event)">
                        <i class="fas fa-lock"></i>
                        Pay $<?= number_format($selectedPlan['price'], 2) ?> Now
                    </button>

                    <!-- Trust Badges -->
                    <div class="trust-badges">
                        <div class="badge">
                            <i class="fas fa-shield-alt"></i>
                            SSL Secure
                        </div>
                        <div class="badge">
                            <i class="fas fa-lock"></i>
                            256-bit Encrypted
                        </div>
                        <div class="badge">
                            <i class="fas fa-check"></i>
                            PCI Compliant
                        </div>
                    </div>
                </div>
            </div>

            <!-- Right: Order Summary -->
            <div>
                <div class="card">
                    <div class="section-title" style="margin-bottom: 28px;">
                        <i class="fas fa-receipt text-emerald-600" style="font-size: 18px;"></i>
                        Order Summary
                    </div>

                    <div class="order-summary">
                        <!-- Plan Details -->
                        <div style="margin-bottom: 20px;">
                            <div style="font-weight: 700; color: #1f2937; font-size: 18px; margin-bottom: 12px;">
                                <?= htmlspecialchars($selectedPlan['name']) ?>
                            </div>
                            <ul style="list-style: none; padding: 0; margin: 0;">
                                <?php foreach ($selectedPlan['features'] as $feature): ?>
                                    <li style="padding: 8px 0; color: #6b7280; font-size: 13px; display: flex; align-items: center; gap: 8px;">
                                        <i class="fas fa-check" style="color: #10b981; font-size: 12px;"></i>
                                        <?= htmlspecialchars($feature) ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>

                        <!-- Pricing -->
                        <div class="summary-item">
                            <div class="summary-label">Plan Price</div>
                            <div class="summary-value">$<?= number_format($selectedPlan['price'], 2) ?></div>
                        </div>

                        <div class="summary-item">
                            <div class="summary-label">Billing Cycle</div>
                            <div class="summary-value">Monthly</div>
                        </div>

                        <div class="summary-item">
                            <div class="summary-label">Tax (Estimated)</div>
                            <div class="summary-value">$<?= number_format($selectedPlan['price'] * 0.1, 2) ?></div>
                        </div>

                        <!-- Total -->
                        <div style="text-align: right;">
                            <div style="color: #6b7280; font-size: 12px; margin-bottom: 8px;">Total Due Today</div>
                            <div class="summary-price">$<?= number_format($selectedPlan['price'] * 1.1, 2) ?></div>
                        </div>
                    </div>

                    <!-- Billing Details -->
                    <div style="margin-bottom: 24px;">
                        <h4 style="font-weight: 700; color: #1f2937; margin-bottom: 16px;">Billing Details</h4>
                        <div style="background: #f9fafb; padding: 16px; border-radius: 8px; font-size: 13px; color: #6b7280; line-height: 1.6;">
                            <div style="margin-bottom: 12px;">
                                <strong style="color: #1f2937;">Auto-Renewal:</strong> Your subscription will automatically renew on the same date each month.
                            </div>
                            <div style="margin-bottom: 12px;">
                                <strong style="color: #1f2937;">Cancellation:</strong> You can cancel anytime from your account settings. No refunds for partial months.
                            </div>
                            <div>
                                <strong style="color: #1f2937;">Receipt:</strong> A detailed receipt will be sent to your email after payment.
                            </div>
                        </div>
                    </div>

                    <!-- Money Back Guarantee -->
                    <div style="padding: 16px; background: #fef3c7; border-radius: 8px; border-left: 4px solid #f59e0b;">
                        <div style="font-weight: 600; color: #92400e; margin-bottom: 8px;">
                            <i class="fas fa-shield-alt mr-2"></i>30-Day Money Back Guarantee
                        </div>
                        <div style="font-size: 12px; color: #a16207;">
                            Not satisfied? Get a full refund within 30 days, no questions asked.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Toggle card details visibility
        document.querySelectorAll('input[name="payment_method"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const cardDetails = document.getElementById('cardDetails');
                const paymentMethods = document.querySelectorAll('.payment-method');
                
                paymentMethods.forEach(pm => pm.classList.remove('active'));
                this.closest('.payment-method').classList.add('active');
                
                if (this.value === 'card') {
                    cardDetails.style.display = 'block';
                } else {
                    cardDetails.style.display = 'none';
                }
            });
        });

        function processPayment(event) {
            event.preventDefault();
            
            const paymentMethod = document.querySelector('input[name="payment_method"]:checked').value;
            const btn = document.querySelector('.btn-primary');
            
            if (paymentMethod === 'paypal') {
                // PayPal payment simulation
                processPayPalPayment(btn);
            } else if (paymentMethod === 'card') {
                // Card payment processing
                processCardPayment(btn);
            }
        }

        function processPayPalPayment(btn) {
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Redirecting to PayPal...';

            const plan = '<?= htmlspecialchars($plan) ?>';
            const planPrice = <?= $selectedPlan['price'] ?>;

            // Submit payment to backend
            fetch('/atasteofafricanmarketplace/api/membership/subscribe.php', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    plan: plan,
                    payment_method: 'paypal',
                    amount: planPrice
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Payment successful! Your subscription has been activated.');
                    window.location.href = '<?= htmlspecialchars($returnUrl) ?>';
                } else {
                    alert('Payment failed: ' + data.message);
                    btn.disabled = false;
                    btn.innerHTML = 'Pay Now';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                btn.disabled = false;
                btn.innerHTML = 'Pay Now';
            });
        }

        function processCardPayment(btn) {
            const cardNumber = document.querySelector('input[placeholder="1234 5678 9012 3456"]').value;
            const expiry = document.querySelector('input[placeholder="MM/YY"]').value;
            const cvc = document.querySelector('input[placeholder="123"]').value;

            if (!cardNumber || !expiry || !cvc) {
                alert('Please fill in all card details');
                return;
            }

            if (cardNumber.replace(/\s/g, '').length < 13) {
                alert('Please enter a valid card number');
                return;
            }

            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';

            const plan = '<?= htmlspecialchars($plan) ?>';
            const planPrice = <?= $selectedPlan['price'] ?>;

            // Submit payment to backend
            fetch('/atasteofafricanmarketplace/api/membership/subscribe.php', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    plan: plan,
                    payment_method: 'card',
                    amount: planPrice,
                    card: {
                        number: cardNumber.replace(/\s/g, ''),
                        expiry: expiry,
                        cvc: cvc
                    }
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Payment successful! Your subscription has been activated.');
                    window.location.href = '<?= htmlspecialchars($returnUrl) ?>';
                } else {
                    alert('Payment failed: ' + data.message);
                    btn.disabled = false;
                    btn.innerHTML = 'Pay Now';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                btn.disabled = false;
                btn.innerHTML = 'Pay Now';
            });
        }
    </script>
</body>
</html>
