<?php
session_start();
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';
require_once __DIR__ . '/../src/SuperAdmin/PlatformSettings.php';

// Get parameters
$planId = (int) ($_GET['plan'] ?? $_POST['plan'] ?? 0);
$cycle = ($_GET['cycle'] ?? $_POST['cycle'] ?? 'monthly') === 'yearly' ? 'yearly' : 'monthly';
$currency = $_GET['currency'] ?? $_POST['currency'] ?? $_SESSION['currency'] ?? 'USD';
$workspaceName = $_GET['workspace_name'] ?? $_POST['workspace_name'] ?? '';
$workspaceUsername = $_GET['workspace_username'] ?? $_POST['workspace_username'] ?? '';

// For new signups (from signup.php redirect)
$isNewSignup = isset($_GET['new_signup']) || isset($_POST['new_signup']);
$userId = $_SESSION['pending_user_id'] ?? null;
$companyId = $_SESSION['pending_company_id'] ?? null;

// If new signup but no pending data, redirect to signup
if ($isNewSignup && (!$userId || !$companyId)) {
    header('Location: /signup.php?plan=' . $planId . '&cycle=' . $cycle . '&currency=' . $currency);
    exit;
}

// For existing users creating new workspace
$user = null;
if (!$isNewSignup) {
    $user = AuthManager::getCurrentUser();
    if (!$user) {
        header('Location: /login.php');
        exit;
    }
}

if (!$planId) {
    header('Location: /signup-plans.php');
    exit;
}

$plan = SubscriptionManager::getPlan($planId);
if (!$plan) {
    header('Location: /signup-plans.php');
    exit;
}

// Currency settings
$currencySymbol = $currency === 'INR' ? '₹' : '$';
$paymentGateway = $currency === 'INR' ? 'razorpay' : 'stripe';

// Get price based on currency and cycle
if ($currency === 'INR') {
    $price = $cycle === 'yearly' 
        ? (float)($plan['price_yearly_inr'] ?? $plan['price_yearly'] * 83)
        : (float)($plan['price_monthly_inr'] ?? $plan['price_monthly'] * 83);
} else {
    $price = $cycle === 'yearly' ? (float)$plan['price_yearly'] : (float)$plan['price_monthly'];
}

$originalPrice = $price;
$discountAmount = 0;
$discountCode = '';
$discountError = '';
$finalPrice = $price;

// Get payment gateway settings
$stripeEnabled = PlatformSettings::get('stripe_enabled', false);
$stripePublicKey = PlatformSettings::get('stripe_public_key', '');
$razorpayEnabled = PlatformSettings::get('razorpay_enabled', false);
$razorpayKeyId = PlatformSettings::get('razorpay_key_id', '');

// Handle discount code validation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['apply_discount'])) {
    $discountCode = strtoupper(trim($_POST['discount_code'] ?? ''));
    
    if ($discountCode) {
        $pdo = getPDO();
        $stmt = $pdo->prepare("
            SELECT * FROM discount_codes 
            WHERE code = ? 
            AND is_active = 1 
            AND (valid_from IS NULL OR valid_from <= NOW())
            AND (valid_until IS NULL OR valid_until >= NOW())
            AND (max_uses IS NULL OR used_count < max_uses)
        ");
        $stmt->execute([$discountCode]);
        $discount = $stmt->fetch();
        
        if ($discount) {
            if ($discount['discount_type'] === 'percent') {
                $discountAmount = $price * ($discount['discount_value'] / 100);
            } else {
                $discountAmount = (float)$discount['discount_value'];
            }
            $finalPrice = max(0, $price - $discountAmount);
            $_SESSION['discount_code'] = $discountCode;
            $_SESSION['discount_id'] = $discount['id'];
        } else {
            $discountError = 'Invalid or expired discount code';
        }
    }
} elseif (isset($_SESSION['discount_code'])) {
    // Re-validate stored discount
    $discountCode = $_SESSION['discount_code'];
    $pdo = getPDO();
    $stmt = $pdo->prepare("SELECT * FROM discount_codes WHERE code = ? AND is_active = 1");
    $stmt->execute([$discountCode]);
    $discount = $stmt->fetch();
    
    if ($discount) {
        if ($discount['discount_type'] === 'percent') {
            $discountAmount = $price * ($discount['discount_value'] / 100);
        } else {
            $discountAmount = (float)$discount['discount_value'];
        }
        $finalPrice = max(0, $price - $discountAmount);
    }
}

// Handle checkout completion (free checkout with discount)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['complete_checkout'])) {
    if ($finalPrice <= 0) {
        $pdo = getPDO();
        $pdo->beginTransaction();
        
        try {
            // Update discount usage
            if (isset($_SESSION['discount_id'])) {
                $stmt = $pdo->prepare("UPDATE discount_codes SET used_count = used_count + 1 WHERE id = ?");
                $stmt->execute([$_SESSION['discount_id']]);
            }
            
            if ($isNewSignup && $companyId) {
                // Complete the pending signup
                $stmt = $pdo->prepare("UPDATE companies SET subscription_status = 'active' WHERE id = ?");
                $stmt->execute([$companyId]);
                
                $stmt = $pdo->prepare("UPDATE subscriptions SET status = 'active' WHERE company_id = ?");
                $stmt->execute([$companyId]);
                
                // Get company and user info for redirect
                $stmt = $pdo->prepare("SELECT username FROM companies WHERE id = ?");
                $stmt->execute([$companyId]);
                $company = $stmt->fetch();
                
                // Get user email for login
                $stmt = $pdo->prepare("SELECT email FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $newUser = $stmt->fetch();
                
                $pdo->commit();
                
                // Log the user in using AuthManager with stored password
                $pendingEmail = $_SESSION['pending_email'] ?? ($newUser['email'] ?? '');
                $pendingPassword = $_SESSION['pending_password'] ?? '';
                
                if ($pendingEmail && $pendingPassword) {
                    AuthManager::login($pendingEmail, $pendingPassword);
                }
                
                // Clear pending session data
                unset($_SESSION['pending_user_id'], $_SESSION['pending_company_id'], $_SESSION['pending_email'], $_SESSION['pending_password'], $_SESSION['discount_code'], $_SESSION['discount_id']);
                
                header('Location: /index.php?welcome=1&workspace=' . urlencode($company['username']));
                exit;
            } elseif ($user && $workspaceName && $workspaceUsername) {
                // Create new workspace for existing user
                $stmt = $pdo->prepare("INSERT INTO companies (name, username, subdomain, plan_id, subscription_status, billing_cycle, preferred_currency, owner_id, created_at) VALUES (?, ?, ?, ?, 'active', ?, ?, ?, NOW())");
                $stmt->execute([$workspaceName, $workspaceUsername, $workspaceUsername, $planId, $cycle, $currency, $user['id']]);
                $newCompanyId = $pdo->lastInsertId();
                
                // Create subscription
                $currentPeriodStart = date('Y-m-d H:i:s');
                $currentPeriodEnd = date('Y-m-d H:i:s', strtotime($cycle === 'yearly' ? '+1 year' : '+1 month'));
                $stmt = $pdo->prepare("INSERT INTO subscriptions (company_id, plan_id, status, billing_cycle, current_period_start, current_period_end, created_at) VALUES (?, ?, 'active', ?, ?, ?, NOW())");
                $stmt->execute([$newCompanyId, $planId, $cycle, $currentPeriodStart, $currentPeriodEnd]);
                
                // Add user access
                $stmt = $pdo->prepare("INSERT INTO user_company_access (user_id, company_id, role, created_at) VALUES (?, ?, 'admin', NOW())");
                $stmt->execute([$user['id'], $newCompanyId]);
                
                $pdo->commit();
                
                unset($_SESSION['discount_code'], $_SESSION['discount_id']);
                
                header('Location: /index.php?welcome=1&workspace=' . urlencode($workspaceUsername));
                exit;
            } else {
                // No valid checkout scenario
                $discountError = 'Unable to complete checkout. Please try signing up again.';
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $discountError = 'Failed to complete checkout: ' . $e->getMessage();
        }
    } else {
        $discountError = 'Payment is required to complete checkout.';
    }
}

$cycleLabel = $cycle === 'yearly' ? 'year' : 'month';
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkout - Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || 'dark';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
    <?php if ($paymentGateway === 'stripe' && $stripePublicKey): ?>
    <script src="https://js.stripe.com/v3/"></script>
    <?php elseif ($paymentGateway === 'razorpay' && $razorpayKeyId): ?>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <?php endif; ?>
</head>
<body class="checkout-page">
    <div class="funnel-shell">
        <header class="funnel-shell__header">
            <div class="funnel-shell__header-inner">
                <a href="/" class="funnel-shell__brand">
                    <img src="/assets/Keelance-Logo Light.svg" alt="Keelance" class="funnel-shell__logo theme-logo--dark">
                    <img src="/assets/KeelanceLogo.png" alt="Keelance" class="funnel-shell__logo theme-logo--light">
                </a>
                <div class="funnel-shell__header-text">
                    <h1 class="funnel-shell__title">Complete Your Purchase</h1>
                    <p class="funnel-shell__subtitle">Secure checkout powered by <?= $paymentGateway === 'stripe' ? 'Stripe' : 'Razorpay' ?></p>
                </div>
            </div>
        </header>

        <main class="funnel-shell__main">
            <div class="checkout-container">
                <div class="checkout-grid">
                    <section class="card checkout-card">
                        <div class="checkout-card__header">
                            <h2 class="card-title">Order Summary</h2>
                        </div>

                        <div class="checkout-summary">
                            <div class="checkout-summary__line">
                                <div>
                                    <p class="checkout-summary__name"><?= htmlspecialchars($plan['name']) ?> Plan</p>
                                    <p class="checkout-summary__hint">Billed <?= htmlspecialchars($cycle) ?></p>
                                </div>
                                <p class="checkout-summary__amount"><?= $currencySymbol ?><?= number_format($originalPrice, 2) ?></p>
                            </div>

                            <?php if ($discountAmount > 0): ?>
                            <div class="checkout-summary__line">
                                <div class="checkout-summary__discount">
                                    <span>Discount (<?= htmlspecialchars($discountCode) ?>)</span>
                                    <button type="button" onclick="removeDiscount()" class="btn-secondary btn-sm">Remove</button>
                                </div>
                                <p class="checkout-summary__amount">-<?= $currencySymbol ?><?= number_format($discountAmount, 2) ?></p>
                            </div>
                            <?php endif; ?>

                            <div class="checkout-summary__total">
                                <div>
                                    <p class="checkout-summary__total-label">Total</p>
                                    <p class="checkout-summary__total-hint">per <?= htmlspecialchars($cycleLabel) ?></p>
                                </div>
                                <p class="checkout-summary__total-amount"><?= $currencySymbol ?><?= number_format($finalPrice, 2) ?></p>
                            </div>
                        </div>

                        <div class="checkout-section">
                            <form method="POST" class="form-stack">
                                <input type="hidden" name="plan" value="<?= $planId ?>">
                                <input type="hidden" name="cycle" value="<?= htmlspecialchars($cycle) ?>">
                                <input type="hidden" name="currency" value="<?= htmlspecialchars($currency) ?>">
                                <?php if ($isNewSignup): ?>
                                <input type="hidden" name="new_signup" value="1">
                                <?php endif; ?>
                                <input type="hidden" name="workspace_name" value="<?= htmlspecialchars($workspaceName) ?>">
                                <input type="hidden" name="workspace_username" value="<?= htmlspecialchars($workspaceUsername) ?>">

                                <div class="form-field">
                                    <label class="form-label" for="discount_code">Discount code</label>
                                    <div class="checkout-discount__row">
                                        <input id="discount_code" type="text" name="discount_code" value="<?= htmlspecialchars($discountCode) ?>" placeholder="Enter code" class="form-input" style="text-transform: uppercase;">
                                        <button type="submit" name="apply_discount" value="1" class="btn-secondary btn-sm">Apply</button>
                                    </div>
                                    <?php if ($discountError): ?>
                                    <p class="checkout-error"><?= htmlspecialchars($discountError) ?></p>
                                    <?php endif; ?>
                                </div>
                            </form>
                        </div>

                        <div class="checkout-section">
                            <p class="checkout-hint">
                                <?php if ($paymentGateway === 'stripe'): ?>
                                    Pay securely with Stripe.
                                <?php else: ?>
                                    Pay with UPI, Cards, Net Banking via Razorpay.
                                <?php endif; ?>
                            </p>
                        </div>
                    </section>

                    <section class="card checkout-card">
                        <div class="checkout-card__header">
                            <h2 class="card-title">Payment Details</h2>
                        </div>

                        <?php if ($finalPrice <= 0): ?>
                        <div class="checkout-payment">
                            <div class="checkout-free">
                                <p class="checkout-free__title">No payment required</p>
                                <p class="checkout-free__subtitle">Your discount code covers the full amount.</p>
                            </div>

                            <form method="POST">
                                <input type="hidden" name="plan" value="<?= $planId ?>">
                                <input type="hidden" name="cycle" value="<?= htmlspecialchars($cycle) ?>">
                                <input type="hidden" name="currency" value="<?= htmlspecialchars($currency) ?>">
                                <?php if ($isNewSignup): ?>
                                <input type="hidden" name="new_signup" value="1">
                                <?php endif; ?>
                                <input type="hidden" name="workspace_name" value="<?= htmlspecialchars($workspaceName) ?>">
                                <input type="hidden" name="workspace_username" value="<?= htmlspecialchars($workspaceUsername) ?>">

                                <button type="submit" name="complete_checkout" value="1" class="btn-primary btn-block">
                                    Complete Setup &amp; Go to Dashboard
                                </button>
                            </form>
                        </div>

                        <?php elseif ($paymentGateway === 'stripe' && $stripePublicKey): ?>
                        <div id="stripe-payment" class="checkout-payment">
                            <div id="card-element" class="checkout-stripe-element"></div>
                            <div id="card-errors" class="checkout-error"></div>
                            <button id="stripe-submit" class="btn-primary btn-block">
                                Pay <?= $currencySymbol ?><?= number_format($finalPrice, 2) ?>
                            </button>
                        </div>

                        <script>
                            const stripe = Stripe('<?= htmlspecialchars($stripePublicKey) ?>');
                            const elements = stripe.elements();
                            const cardElement = elements.create('card', {
                                style: {
                                    base: {
                                        fontSize: '14px',
                                        color: '#1e293b',
                                        '::placeholder': { color: '#94a3b8' }
                                    }
                                }
                            });
                            cardElement.mount('#card-element');

                            cardElement.on('change', function(event) {
                                const displayError = document.getElementById('card-errors');
                                displayError.textContent = event.error ? event.error.message : '';
                            });

                            document.getElementById('stripe-submit').addEventListener('click', async function() {
                                this.disabled = true;
                                this.textContent = 'Processing...';

                                // In production, create PaymentIntent on server and confirm here
                                alert('Stripe integration requires server-side setup. For testing, use discount code FREETEST');

                                this.disabled = false;
                                this.textContent = 'Pay <?= $currencySymbol ?><?= number_format($finalPrice, 2) ?>';
                            });
                        </script>

                        <?php elseif ($paymentGateway === 'razorpay' && $razorpayKeyId): ?>
                        <div class="checkout-payment">
                            <button id="razorpay-btn" class="btn-primary btn-block">
                                Pay <?= $currencySymbol ?><?= number_format($finalPrice, 2) ?> with Razorpay
                            </button>
                        </div>

                        <script>
                            document.getElementById('razorpay-btn').addEventListener('click', function() {
                                const options = {
                                    key: '<?= htmlspecialchars($razorpayKeyId) ?>',
                                    amount: <?= $finalPrice * 100 ?>,
                                    currency: 'INR',
                                    name: 'Keelance',
                                    description: '<?= htmlspecialchars($plan['name']) ?> Plan - <?= ucfirst($cycle) ?>',
                                    handler: function(response) {
                                        // In production, verify payment on server
                                        alert('Payment successful! ID: ' + response.razorpay_payment_id);
                                        window.location.href = '/index.php?welcome=1';
                                    },
                                    prefill: {
                                        email: '<?= htmlspecialchars($user['email'] ?? '') ?>'
                                    },
                                    theme: { color: '#2563eb' }
                                };

                                const rzp = new Razorpay(options);
                                rzp.open();
                            });
                        </script>

                        <?php else: ?>
                        <div class="checkout-payment">
                            <div class="alert alert--danger">
                                Payment gateway not configured. For testing, use code: <code class="pill">FREETEST</code>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="checkout-section">
                            <p class="checkout-hint">🔒 SSL Encrypted · 💳 PCI Compliant · ✓ Secure Checkout</p>
                        </div>
                    </section>
                </div>

                <div class="checkout-back">
                    <a href="/signup-plans.php" class="btn-secondary btn-sm">← Back to plans</a>
                </div>
            </div>
        </main>

        <?php include __DIR__ . '/footer.php'; ?>
    </div>

    <script>
        function removeDiscount() {
            const newSignupField = <?= $isNewSignup ? "'<input type=\\\"hidden\\\" name=\\\"new_signup\\\" value=\\\"1\\\">'" : "''" ?>;
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="plan" value="<?= $planId ?>">
                <input type="hidden" name="cycle" value="<?= htmlspecialchars($cycle) ?>">
                <input type="hidden" name="currency" value="<?= htmlspecialchars($currency) ?>">
                ${newSignupField}
                <input type="hidden" name="workspace_name" value="<?= htmlspecialchars($workspaceName) ?>">
                <input type="hidden" name="workspace_username" value="<?= htmlspecialchars($workspaceUsername) ?>">
                <input type="hidden" name="discount_code" value="">
                <input type="hidden" name="apply_discount" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    </script>
</body>
</html>
