<?php
/**
 * GymFuel Titan - Official License Storefront
 * Accessible at: https://gethire.probuy.php
 */

session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/CashfreeService.php';

$pdo = getDatabaseConnection();
$cfService = new CashfreeService($pdo);

// Check if athlete is already logged in
$isLoggedIn = !empty($_SESSION['athlete_user_id']);
$loggedInUser = null;
if ($isLoggedIn) {
    $stmtUser = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmtUser->execute([$_SESSION['athlete_user_id']]);
    $loggedInUser = $stmtUser->fetch(PDO::FETCH_ASSOC);
    if (!$loggedInUser) {
        $isLoggedIn = false;
    }
}

// Fetch Pricing & Settings
$settings = [];
try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    // Ignore
}

$price30 = !empty($settings['plan_price_30']) ? (float)$settings['plan_price_30'] : 199;
$price90 = !empty($settings['plan_price_90']) ? (float)$settings['plan_price_90'] : 499;
$price365 = !empty($settings['plan_price_365']) ? (float)$settings['plan_price_365'] : 999;
$priceLifetime = !empty($settings['plan_price_lifetime']) ? (float)$settings['plan_price_lifetime'] : 1999;
$currency = !empty($settings['currency']) ? $settings['currency'] : 'INR';
$cfEnv = $cfService->getEnvironment();
$isGatewayReady = $cfService->isConfigured();

// Handle AJAX Order Creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_checkout'])) {
    header('Content-Type: application/json');

    $planId = trim($_POST['plan_id'] ?? '365');

    if ($isLoggedIn && $loggedInUser) {
        // Logged-in user: use existing account credentials without asking for password
        $name = $loggedInUser['name'];
        $email = $loggedInUser['email'];
        $phone = $loggedInUser['phone'];
        $userId = (int)$loggedInUser['id'];
    } else {
        // Guest user: validate input details and create account password
        $name = trim($_POST['customer_name'] ?? '');
        $email = trim($_POST['customer_email'] ?? '');
        $phone = trim($_POST['customer_phone'] ?? '');
        $password = trim($_POST['customer_password'] ?? '');

        if (empty($name) || empty($email) || empty($phone) || empty($password)) {
            echo json_encode(["success" => false, "error" => "Please fill in all details including account password."]);
            exit();
        }

        if (strlen($password) < 6) {
            echo json_encode(["success" => false, "error" => "Password must be at least 6 characters long."]);
            exit();
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(["success" => false, "error" => "Please provide a valid email address."]);
            exit();
        }

        // Check if user already exists or create new user account
        $userId = 0;
        try {
            $chkUser = $pdo->prepare("SELECT id, name, phone, password_hash FROM users WHERE email = ?");
            $chkUser->execute([$email]);
            $existingUser = $chkUser->fetch(PDO::FETCH_ASSOC);

            if ($existingUser) {
                // Verify existing password
                if (!password_verify($password, $existingUser['password_hash'])) {
                    echo json_encode([
                        "success" => false, 
                        "error" => "An athlete account with email {$email} already exists. Please enter your correct account password, or log in first."
                    ]);
                    exit();
                }
                $userId = (int)$existingUser['id'];
                // Set session
                $_SESSION['athlete_user_id'] = $userId;
                $_SESSION['athlete_email'] = $email;
                $_SESSION['athlete_phone'] = $existingUser['phone'] ?: $phone;
                $_SESSION['athlete_name'] = $existingUser['name'] ?: $name;
            } else {
                // Create user account with bcrypt password
                $hash = password_hash($password, PASSWORD_BCRYPT);
                $insUser = $pdo->prepare("INSERT INTO users (name, email, phone, password_hash) VALUES (?, ?, ?, ?)");
                $insUser->execute([$name, $email, $phone, $hash]);
                $userId = (int)$pdo->lastInsertId();

                // Set session
                $_SESSION['athlete_user_id'] = $userId;
                $_SESSION['athlete_email'] = $email;
                $_SESSION['athlete_phone'] = $phone;
                $_SESSION['athlete_name'] = $name;
            }
        } catch (Exception $e) {
            echo json_encode(["success" => false, "error" => "Account initialization error: " . $e->getMessage()]);
            exit();
        }
    }

    // Determine Plan Details
    $amount = $price365;
    $planTitle = "1 Year Titan Pro (365 Days)";
    $durationDays = 365;

    switch ($planId) {
        case '30':
            $amount = $price30;
            $planTitle = "1 Month Starter Shred (30 Days)";
            $durationDays = 30;
            break;
        case '90':
            $amount = $price90;
            $planTitle = "3 Months Beast Mode (90 Days)";
            $durationDays = 90;
            break;
        case '365':
            $amount = $price365;
            $planTitle = "1 Year Titan Pro (365 Days)";
            $durationDays = 365;
            break;
        case 'lifetime':
            $amount = $priceLifetime;
            $planTitle = "Lifetime VIP Beast Pass (Forever)";
            $durationDays = 0;
            break;
    }

    $orderId = "GF_ORD_" . strtoupper(uniqid()) . "_" . rand(100, 999);

    // Save pending order in database
    try {
        $stmt = $pdo->prepare("
            INSERT INTO orders (order_id, user_id, customer_name, customer_email, customer_phone, plan_id, plan_title, duration_days, amount, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')
        ");
        $stmt->execute([$orderId, $userId, $name, $email, $phone, $planId, $planTitle, $durationDays, $amount]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "error" => "Failed to initialize order: " . $e->getMessage()]);
        exit();
    }

    // Construct Return URL
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    $dir = rtrim(dirname($_SERVER['REQUEST_URI']), '/\\');
    $returnUrl = "{$protocol}://{$host}{$dir}/verify_payment.php?order_id={$orderId}";

    // Call Cashfree API
    $cfResponse = $cfService->createOrder(
        $orderId,
        $amount,
        $name,
        $email,
        $phone,
        $returnUrl,
        "GymFuel License: {$planTitle}"
    );

    if ($cfResponse['success']) {
        // Update cf_order_id
        if (!empty($cfResponse['cf_order_id'])) {
            $update = $pdo->prepare("UPDATE orders SET cf_order_id = ? WHERE order_id = ?");
            $update->execute([$cfResponse['cf_order_id'], $orderId]);
        }

        echo json_encode([
            "success" => true,
            "payment_session_id" => $cfResponse['payment_session_id'],
            "order_id" => $orderId,
            "environment" => $cfEnv
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "error" => $cfResponse['error'] ?? "Failed to create Cashfree payment session."
        ]);
    }
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>GymFuel Titan • Get Official License Key</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@700;800&display=swap" rel="stylesheet">
    
    <!-- Cashfree JS SDK v3 -->
    <script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>

    <style>
        :root {
            --bg-dark: #07090E;
            --card-bg: #0E131F;
            --card-elevated: #151C2C;
            --border: rgba(255, 255, 255, 0.08);
            --border-hover: rgba(255, 94, 0, 0.4);
            --primary: #FF5E00;
            --primary-gradient: linear-gradient(135deg, #FF5E00 0%, #FF8533 100%);
            --primary-glow: rgba(255, 94, 0, 0.4);
            --gold: #FFB300;
            --gold-gradient: linear-gradient(135deg, #FFB300 0%, #FFE082 100%);
            --cyan: #00E5FF;
            --green: #00E676;
            --red: #FF3D71;
            --text-primary: #F4F7FB;
            --text-muted: #8A97AC;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: 'Plus Jakarta Sans', -apple-system, sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-primary);
            min-height: 100vh;
            line-height: 1.5;
            overflow-x: hidden;
            background-image: 
                radial-gradient(circle at 50% -10%, rgba(255, 94, 0, 0.18) 0%, transparent 60%),
                radial-gradient(circle at 100% 70%, rgba(0, 229, 255, 0.08) 0%, transparent 50%),
                radial-gradient(circle at 0% 90%, rgba(255, 179, 0, 0.06) 0%, transparent 50%);
            background-attachment: fixed;
        }

        .mono { font-family: 'JetBrains Mono', monospace; }

        /* Top Bar */
        .topbar {
            background: rgba(14, 19, 31, 0.85);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border);
            padding: 14px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .logo-box {
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: inherit;
        }

        .logo-badge {
            background: var(--primary-gradient);
            color: #000;
            width: 34px;
            height: 34px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 900;
            box-shadow: 0 4px 14px var(--primary-glow);
        }

        .logo-name {
            font-weight: 900;
            font-size: 16px;
            letter-spacing: -0.4px;
        }

        .portal-link {
            color: var(--gold);
            text-decoration: none;
            font-size: 12.5px;
            font-weight: 800;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            background: rgba(255, 179, 0, 0.12);
            border: 1px solid rgba(255, 179, 0, 0.3);
            padding: 7px 14px;
            border-radius: 10px;
            transition: all 0.2s ease;
        }

        .portal-link:hover {
            background: rgba(255, 179, 0, 0.22);
            transform: translateY(-1px);
        }

        .container {
            max-width: 1080px;
            margin: 0 auto;
            padding: 32px 18px 80px;
        }

        /* Hero */
        .hero {
            text-align: center;
            margin-bottom: 36px;
        }

        .hero-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255, 94, 0, 0.12);
            border: 1px solid rgba(255, 94, 0, 0.35);
            padding: 6px 16px;
            border-radius: 100px;
            color: var(--primary);
            font-weight: 800;
            font-size: 11.5px;
            letter-spacing: 1.2px;
            text-transform: uppercase;
            margin-bottom: 14px;
        }

        .hero-title {
            font-size: clamp(28px, 6vw, 46px);
            font-weight: 900;
            letter-spacing: -1.2px;
            line-height: 1.15;
            background: linear-gradient(180deg, #FFFFFF 20%, #B8C4D6 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .hero-sub {
            font-size: 15px;
            color: var(--text-muted);
            max-width: 580px;
            margin: 10px auto 0;
            padding: 0 10px;
        }

        /* Features Bar */
        .features-pill-row {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 8px;
            margin: 20px 0 32px;
        }

        .feature-pill {
            background: var(--card-bg);
            border: 1px solid var(--border);
            padding: 7px 12px;
            border-radius: 100px;
            font-size: 12px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 5px;
            color: var(--text-primary);
        }

        /* Plans Grid */
        .plans-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 16px;
            margin-bottom: 36px;
        }

        .plan-card {
            background: var(--card-bg);
            border: 1.5px solid var(--border);
            border-radius: 22px;
            padding: 24px 20px;
            cursor: pointer;
            position: relative;
            transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .plan-card:hover {
            transform: translateY(-4px);
            border-color: var(--border-hover);
            box-shadow: 0 12px 30px rgba(0, 0, 0, 0.5);
        }

        .plan-card.selected {
            background: linear-gradient(180deg, #182030 0%, #0E131F 100%);
            border-color: var(--primary);
            box-shadow: 0 0 0 2px var(--primary), 0 14px 34px var(--primary-glow);
            transform: scale(1.02);
        }

        .popular-badge {
            position: absolute;
            top: 0;
            right: 0;
            background: var(--primary-gradient);
            color: #000;
            font-size: 10px;
            font-weight: 900;
            padding: 5px 14px;
            border-bottom-left-radius: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .plan-name {
            font-size: 16px;
            font-weight: 800;
            color: var(--text-primary);
        }

        .plan-price-box {
            margin: 14px 0 8px;
        }

        .plan-currency {
            font-size: 16px;
            font-weight: 800;
            color: var(--primary);
            vertical-align: top;
        }

        .plan-price {
            font-size: 36px;
            font-weight: 900;
            letter-spacing: -1px;
        }

        .plan-period {
            font-size: 12px;
            color: var(--text-muted);
            font-weight: 600;
        }

        .plan-features {
            list-style: none;
            margin-top: 14px;
            border-top: 1px solid var(--border);
            padding-top: 14px;
            font-size: 12.5px;
            color: var(--text-muted);
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .plan-features li {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .plan-features li.highlight {
            color: #fff;
            font-weight: 700;
        }

        /* Checkout Card */
        .checkout-card {
            background: var(--card-bg);
            border: 1px solid rgba(255, 94, 0, 0.4);
            border-radius: 26px;
            padding: clamp(22px, 5vw, 36px);
            max-width: 580px;
            margin: 0 auto;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.7);
            position: relative;
        }

        .checkout-header {
            margin-bottom: 20px;
        }

        /* Logged In User Card */
        .user-logged-card {
            background: linear-gradient(135deg, rgba(0, 229, 255, 0.08) 0%, rgba(255, 94, 0, 0.08) 100%);
            border: 1px solid rgba(0, 229, 255, 0.3);
            border-radius: 18px;
            padding: 16px 18px;
            margin-bottom: 20px;
        }

        .user-avatar {
            width: 42px;
            height: 42px;
            border-radius: 12px;
            background: var(--primary-gradient);
            color: #000;
            font-weight: 900;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 12px var(--primary-glow);
        }

        .login-shortcut-banner {
            background: rgba(255, 255, 255, 0.03);
            border: 1px dashed rgba(255, 255, 255, 0.15);
            border-radius: 14px;
            padding: 10px 14px;
            font-size: 12.5px;
            color: var(--text-muted);
            margin-bottom: 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 6px;
        }

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

        .form-label {
            display: block;
            font-size: 11.5px;
            font-weight: 800;
            color: var(--text-muted);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-input {
            width: 100%;
            background: var(--bg-dark);
            border: 1.5px solid var(--border);
            padding: 14px 16px;
            border-radius: 14px;
            color: var(--text-primary);
            font-size: 15px;
            font-family: inherit;
            outline: none;
            transition: all 0.2s ease;
        }

        .form-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
            background: #0B0F19;
        }

        .btn-pay {
            width: 100%;
            background: var(--primary-gradient);
            color: #000;
            font-weight: 900;
            font-size: 16px;
            padding: 16px 24px;
            border-radius: 14px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            transition: all 0.2s ease;
            box-shadow: 0 6px 20px var(--primary-glow);
            margin-top: 18px;
        }

        .btn-pay:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 28px rgba(255, 94, 0, 0.6);
        }

        .btn-pay:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .payment-methods-row {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 18px;
            font-size: 11px;
            color: var(--text-muted);
            font-weight: 600;
        }

        .trust-badge-box {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            margin-top: 14px;
            font-size: 11px;
            color: var(--green);
            font-weight: 700;
        }

        .gateway-warning {
            background: rgba(255, 61, 113, 0.15);
            border: 1px solid var(--red);
            color: #FF708F;
            padding: 14px;
            border-radius: 14px;
            font-size: 13px;
            margin-bottom: 24px;
            text-align: center;
        }

        @media (max-width: 600px) {
            .plans-grid {
                grid-template-columns: 1fr;
            }
            .plan-card.selected {
                transform: none;
            }
            .topbar {
                padding: 12px 16px;
            }
            .portal-link {
                padding: 6px 10px;
                font-size: 11.5px;
            }
        }
    </style>
</head>
<body>

<!-- TOP NAVIGATION -->
<div class="topbar">
    <a href="buy.php" class="logo-box">
        <div class="logo-badge">⚡</div>
        <div class="logo-name">GymFuel Titan</div>
    </a>
    <a href="portal.php" class="portal-link">
        <?= $isLoggedIn ? '👤 ' . htmlspecialchars($loggedInUser['name']) : '🔑 Access My Keys' ?>
    </a>
</div>

<div class="container">

    <!-- HERO SECTION -->
    <div class="hero">
        <div class="hero-badge">⚡ Instant Key Delivery</div>
        <h1 class="hero-title">Unlock GymFuel Titan OS</h1>
        <p class="hero-sub">Get your official activation key in seconds with UPI, Cards, QR & NetBanking via Cashfree.</p>

        <div class="features-pill-row">
            <div class="feature-pill">🔍 AI Food Vision</div>
            <div class="feature-pill">🏋️ Muscle Biomechanics</div>
            <div class="feature-pill">🥩 Coach Titan AI</div>
            <div class="feature-pill">📱 Offline Gym Mode</div>
        </div>
    </div>

    <?php if (!$isGatewayReady): ?>
        <div class="gateway-warning">
            ⚠️ <strong>Admin Notice:</strong> Cashfree Payment Gateway is not configured yet. Admin needs to add Cashfree App ID & Secret Key in the Admin Dashboard (`index.php`).
        </div>
    <?php endif; ?>

    <!-- STEP 1: SELECT PLAN -->
    <div class="plans-grid">
        <!-- 30 Days -->
        <div class="plan-card" onclick="selectPlan('30', <?= $price30 ?>, '1 Month Starter Shred')">
            <div>
                <div class="plan-name">Starter Shred</div>
                <div class="plan-price-box">
                    <span class="plan-currency">₹</span>
                    <span class="plan-price"><?= (int)$price30 ?></span>
                    <span class="plan-period">/ 30 Days</span>
                </div>
                <ul class="plan-features">
                    <li class="highlight">✓ 30 Days Full Access</li>
                    <li>✓ AI Camera Food Scanner</li>
                    <li>✓ 1 Bound Device</li>
                </ul>
            </div>
        </div>

        <!-- 90 Days -->
        <div class="plan-card" onclick="selectPlan('90', <?= $price90 ?>, '3 Months Beast Mode')">
            <div>
                <div class="plan-name">Beast Mode</div>
                <div class="plan-price-box">
                    <span class="plan-currency">₹</span>
                    <span class="plan-price"><?= (int)$price90 ?></span>
                    <span class="plan-period">/ 90 Days</span>
                </div>
                <ul class="plan-features">
                    <li class="highlight">✓ 90 Days Full Access</li>
                    <li>✓ AI Food & Coach Titan</li>
                    <li>✓ 1 Bound Device</li>
                </ul>
            </div>
        </div>

        <!-- 365 Days (Default) -->
        <div class="plan-card selected" id="card_365" onclick="selectPlan('365', <?= $price365 ?>, '1 Year Titan Pro')">
            <div class="popular-badge">🔥 Most Popular</div>
            <div>
                <div class="plan-name" style="color: var(--primary);">Titan Pro (1 Year)</div>
                <div class="plan-price-box">
                    <span class="plan-currency">₹</span>
                    <span class="plan-price"><?= (int)$price365 ?></span>
                    <span class="plan-period">/ 365 Days</span>
                </div>
                <ul class="plan-features">
                    <li class="highlight">✓ 1 Full Year Access</li>
                    <li class="highlight">✓ All AI Features Unlocked</li>
                    <li>✓ 2 Bound Devices</li>
                    <li>✓ Priority Offline Mode</li>
                </ul>
            </div>
        </div>

        <!-- Lifetime VIP -->
        <div class="plan-card" id="card_lifetime" onclick="selectPlan('lifetime', <?= $priceLifetime ?>, 'Lifetime VIP Beast')">
            <div class="popular-badge" style="background: var(--gold-gradient);">👑 Best Value</div>
            <div>
                <div class="plan-name" style="color: var(--gold);">Lifetime VIP</div>
                <div class="plan-price-box">
                    <span class="plan-currency">₹</span>
                    <span class="plan-price"><?= (int)$priceLifetime ?></span>
                    <span class="plan-period">/ Forever</span>
                </div>
                <ul class="plan-features">
                    <li class="highlight">✓ Lifetime Access (No Expiry)</li>
                    <li class="highlight">✓ All Future Updates Free</li>
                    <li>✓ 3 Bound Devices</li>
                    <li>✓ VIP Priority AI Token</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- STEP 2: ATHLETE DETAILS & CHECKOUT FORM -->
    <div class="checkout-card">
        <div class="checkout-header">
            <h2 style="font-size: 20px; font-weight: 900; margin-bottom: 4px;">⚡ Athlete Checkout</h2>
            <p style="font-size: 13px; color: var(--text-muted);">
                Selected: <strong id="summary_plan_title" style="color: var(--primary);">1 Year Titan Pro (365 Days)</strong> • <strong id="summary_plan_price" style="color: #fff;">₹<?= (int)$price365 ?></strong>
            </p>
        </div>

        <form id="checkoutForm" onsubmit="handleCheckout(event)">
            <input type="hidden" id="selected_plan_id" value="365">
            <input type="hidden" id="selected_amount" value="<?= $price365 ?>">

            <?php if ($isLoggedIn && $loggedInUser): ?>
                <!-- 1-TAP CHECKOUT FOR LOGGED IN USERS (No Re-entry needed) -->
                <div class="user-logged-card">
                    <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div class="user-avatar"><?= strtoupper(substr($loggedInUser['name'], 0, 1)) ?></div>
                            <div>
                                <div style="font-weight: 800; font-size: 15px;"><?= htmlspecialchars($loggedInUser['name']) ?></div>
                                <div style="font-size: 12px; color: var(--text-muted);"><?= htmlspecialchars($loggedInUser['email']) ?> • <?= htmlspecialchars($loggedInUser['phone']) ?></div>
                            </div>
                        </div>
                        <a href="portal.php?action=logout" style="font-size: 11.5px; color: #FF708F; text-decoration: none; font-weight: 800; background: rgba(255, 61, 113, 0.15); padding: 5px 10px; border-radius: 8px;">Switch Account</a>
                    </div>
                    <div style="font-size: 11.5px; color: var(--cyan); margin-top: 10px; font-weight: 700; display: flex; align-items: center; gap: 6px;">
                        ✨ 1-Tap Checkout: Key will be automatically saved to your Athlete Account!
                    </div>
                </div>
            <?php else: ?>
                <!-- GUEST CHECKOUT WITH LOGIN SHORTCUT -->
                <div class="login-shortcut-banner">
                    <span>Already have an account?</span>
                    <a href="portal.php?tab=login&redirect=buy.php" style="color: var(--primary); font-weight: 800; text-decoration: none;">
                        🔑 Log in to 1-tap checkout ➔
                    </a>
                </div>

                <div class="form-group">
                    <label class="form-label">Full Name</label>
                    <input type="text" id="cust_name" class="form-input" placeholder="e.g. Vikram Malhotra" required>
                </div>

                <div class="form-group">
                    <label class="form-label">WhatsApp / Phone Number</label>
                    <input type="tel" id="cust_phone" class="form-input" placeholder="e.g. 9876543210" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Email Address (Key will be sent here)</label>
                    <input type="email" id="cust_email" class="form-input" placeholder="e.g. vikram@gmail.com" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Create Account Password</label>
                    <div style="position: relative;">
                        <input type="password" id="cust_password" class="form-input" placeholder="Create a secure password (min 6 characters)" minlength="6" required style="padding-right: 44px;">
                        <button type="button" onclick="togglePassVisibility(this)" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 6px;" title="Show/Hide Password">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        </button>
                    </div>
                    <small style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 4px;">🔒 Use this password to log in and access your bought keys anytime in the <a href="portal.php" target="_blank" style="color: var(--primary);">Athlete Portal</a>.</small>
                </div>
            <?php endif; ?>

            <button type="submit" id="payButton" class="btn-pay">
                <span>🔒 Pay ₹<span id="btn_pay_amount"><?= (int)$price365 ?></span> with Cashfree</span>
            </button>

            <div class="payment-methods-row">
                <span>⚡ GPay</span> • <span>PhonePe</span> • <span>Paytm</span> • <span>UPI QR</span> • <span>Cards & NetBanking</span>
            </div>

            <div class="trust-badge-box">
                🛡️ 256-Bit Encrypted Secure Checkout (Cashfree Verified)
            </div>
        </form>
    </div>

</div>

<script>
    const isUserLoggedIn = <?= $isLoggedIn ? 'true' : 'false' ?>;
    let selectedPlan = '365';
    let selectedAmount = <?= $price365 ?>;

    function togglePassVisibility(btn) {
        const inp = document.getElementById('cust_password');
        if (inp.type === 'password') {
            inp.type = 'text';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF5E00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>';
        } else {
            inp.type = 'password';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
        }
    }

    function selectPlan(planId, price, title) {
        selectedPlan = planId;
        selectedAmount = price;

        document.querySelectorAll('.plan-card').forEach(el => el.classList.remove('selected'));
        event.currentTarget.classList.add('selected');

        document.getElementById('selected_plan_id').value = planId;
        document.getElementById('selected_amount').value = price;
        document.getElementById('summary_plan_title').innerText = title;
        document.getElementById('summary_plan_price').innerText = '₹' + price;
        document.getElementById('btn_pay_amount').innerText = price;
    }

    async function handleCheckout(e) {
        e.preventDefault();

        const planId = document.getElementById('selected_plan_id').value;
        const btn = document.getElementById('payButton');

        const formData = new FormData();
        formData.append('ajax_checkout', '1');
        formData.append('plan_id', planId);

        if (!isUserLoggedIn) {
            const name = document.getElementById('cust_name').value.trim();
            const phone = document.getElementById('cust_phone').value.trim();
            const email = document.getElementById('cust_email').value.trim();
            const password = document.getElementById('cust_password').value.trim();

            if (!name || !phone || !email || !password) {
                alert("Please fill all required fields including password.");
                return;
            }

            if (password.length < 6) {
                alert("Password must be at least 6 characters long.");
                return;
            }

            formData.append('customer_name', name);
            formData.append('customer_phone', phone);
            formData.append('customer_email', email);
            formData.append('customer_password', password);
        }

        btn.disabled = true;
        btn.innerHTML = '<span>⚡ Connecting to Cashfree...</span>';

        try {
            const res = await fetch('buy.php', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();

            if (data.success && data.payment_session_id) {
                // Initialize Cashfree JS SDK
                const cashfree = Cashfree({
                    mode: data.environment === 'production' ? 'production' : 'sandbox'
                });

                // Launch Cashfree Checkout
                const checkoutOptions = {
                    paymentSessionId: data.payment_session_id,
                    redirectTarget: "_self" // Direct redirect to verify_payment.php on completion
                };

                cashfree.checkout(checkoutOptions);
            } else {
                alert("Error: " + (data.error || "Could not initialize payment session."));
                btn.disabled = false;
                btn.innerHTML = `<span>🔒 Pay ₹${selectedAmount} with Cashfree</span>`;
            }
        } catch (err) {
            alert("Connection error: " + err.message);
            btn.disabled = false;
            btn.innerHTML = `<span>🔒 Pay ₹${selectedAmount} with Cashfree</span>`;
        }
    }
</script>

</body>
</html>
