<?php
require_once __DIR__ . '/../api/lib.php';
require_once __DIR__ . '/../partials/admin-sidebar.php';
hw_require_auth(['superadmin', 'admin']);
$authUser = hw_get_auth_user();

$db = hw_db();
$message = '';
$messageType = '';

// Handle plan upgrade/downgrade
if ($_POST && isset($_POST['action'])) {
    $action = $_POST['action'];
    $userEmail = $_POST['user_email'] ?? '';
    $newPlan = $_POST['plan'] ?? '';
    
    if ($action === 'upgrade_plan' && $userEmail && $newPlan) {
        // Find user
        $stmt = $db->prepare("SELECT id, email FROM users WHERE email = ?");
        $stmt->execute([$userEmail]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Get plan details
            $plans = [
                'personal' => ['name' => 'Personal Plan', 'price' => 14.99, 'features' => 'Personal coaching'],
                'family' => ['name' => 'Family Plan', 'price' => 29.99, 'features' => 'Family coaching']
            ];
            
            if (isset($plans[$newPlan])) {
                // Update user subscription
                $stmt = $db->prepare("UPDATE users SET subscription_plan = ?, plan_updated_at = NOW() WHERE id = ?");
                $stmt->execute([$newPlan, $user['id']]);
                
                $message = "Plan upgraded to {$plans[$newPlan]['name']} successfully!";
                $messageType = 'success';
            } else {
                $message = 'Invalid plan selected.';
                $messageType = 'error';
            }
        } else {
            $message = 'User not found.';
            $messageType = 'error';
        }
    }
}

// Get all users with subscriptions
$users = $db->query("SELECT id, email, first_name, last_name, subscription_plan, created_at FROM users ORDER BY created_at DESC")->fetchAll();

// Plan definitions
$plans = [
    'personal' => [
        'name' => 'Personal Plan',
        'price' => 14.99,
        'billing' => 'per month',
        'features' => [
            'Personalized health coaching',
            'Nutrition and wellness tracking',
            'Monthly check-in sessions',
            'Email support',
            'Personalized wellness plan'
        ],
        'color' => 'blue'
    ],
    'family' => [
        'name' => 'Family Plan',
        'price' => 29.99,
        'billing' => 'per month',
        'features' => [
            'Up to 4 family members',
            'Individual wellness profiles',
            'Personalized coaching for each member',
            'Advanced health tracking',
            'Video consultations',
            'Priority support',
            'Family wellness reports',
            'Shared health goals'
        ],
        'color' => 'emerald'
    ]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Management - Superadmin</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%);
        }

        .plan-card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transition: all 0.3s;
            border-top: 4px solid #e5e7eb;
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .plan-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
        }

        .plan-card.blue { border-top-color: #3b82f6; }
        .plan-card.emerald { border-top-color: #10b981; }
        .plan-card.purple { border-top-color: #8b5cf6; }

        .plan-header {
            margin-bottom: 24px;
        }

        .plan-name {
            font-size: 22px;
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 8px;
        }

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

        .plan-billing {
            font-size: 14px;
            color: #6b7280;
            margin-top: 4px;
        }

        .plan-features {
            flex: 1;
            margin: 24px 0;
        }

        .plan-features li {
            padding: 12px 0;
            border-bottom: 1px solid #f3f4f6;
            color: #4b5563;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .plan-features li:last-child {
            border-bottom: none;
        }

        .plan-features i {
            color: #10b981;
            font-size: 16px;
        }

        .plan-button {
            width: 100%;
            padding: 14px 20px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 15px;
        }

        .plan-button.blue {
            background: linear-gradient(135deg, #3b82f6, #2563eb);
            color: white;
        }

        .plan-button.emerald {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
        }

        .plan-button.purple {
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            color: white;
        }

        .plan-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }

        .user-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .table-header {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            padding: 16px;
            font-weight: 600;
            display: grid;
            grid-template-columns: 2fr 1.5fr 1.5fr 1.5fr auto;
            gap: 16px;
            align-items: center;
        }

        .table-row {
            padding: 16px;
            display: grid;
            grid-template-columns: 2fr 1.5fr 1.5fr 1.5fr auto;
            gap: 16px;
            align-items: center;
            border-bottom: 1px solid #f3f4f6;
            transition: all 0.3s;
        }

        .table-row:hover {
            background: #f9fafb;
        }

        .badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge.personal {
            background: #dbeafe;
            color: #1e40af;
        }

        .badge.family {
            background: #dcfce7;
            color: #15803d;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 16px;
            padding: 32px;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert {
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 24px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert.success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert.error {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
    </style>
</head>
<body>
    <div class="min-h-screen flex">
        <!-- Sidebar -->
        <?php renderAdminSidebar('subscriptions'); ?>
        
        <!-- Main Content -->
        <div class="flex-1 p-8">
            <div class="mb-12">
                <h2 class="text-4xl font-bold text-gray-900 mb-2">Subscription Management</h2>
                <p class="text-gray-600">Manage user plans and billing, view payment methods, and handle subscriptions</p>
            </div>

            <!-- Success/Error Message -->
            <?php if ($message): ?>
                <div class="alert <?= $messageType ?>">
                    <i class="fas fa-<?= $messageType === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
                    <span><?= htmlspecialchars($message) ?></span>
                </div>
            <?php endif; ?>

            <!-- Tabs -->
            <div class="mb-8 flex gap-4 border-b border-gray-200">
                <button onclick="showTab('plans')" class="active-tab px-6 py-3 font-semibold text-emerald-600 border-b-2 border-emerald-600 transition cursor-pointer" id="tab-plans">
                    <i class="fas fa-tag mr-2"></i>Available Plans
                </button>
                <button onclick="showTab('users')" class="px-6 py-3 font-semibold text-gray-600 border-b-2 border-transparent hover:text-gray-900 transition cursor-pointer" id="tab-users">
                    <i class="fas fa-users mr-2"></i>User Subscriptions
                </button>
                <button onclick="showTab('payments')" class="px-6 py-3 font-semibold text-gray-600 border-b-2 border-transparent hover:text-gray-900 transition cursor-pointer" id="tab-payments">
                    <i class="fas fa-credit-card mr-2"></i>Payment Methods
                </button>
                <button onclick="showTab('analytics')" class="px-6 py-3 font-semibold text-gray-600 border-b-2 border-transparent hover:text-gray-900 transition cursor-pointer" id="tab-analytics">
                    <i class="fas fa-chart-line mr-2"></i>Revenue Analytics
                </button>
            </div>

            <!-- Plans Tab -->
            <div id="tab-content-plans" class="tab-content active">
                <div class="mb-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                        <i class="fas fa-star text-emerald-600"></i>
                        Subscription Plans
                    </h3>
                    <p class="text-gray-600 mb-8">Select a plan to see details or manage user subscriptions</p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-12">
                    <?php foreach ($plans as $planKey => $plan): ?>
                        <div class="plan-card <?= $plan['color'] ?>">
                            <div class="plan-header">
                                <div class="plan-name"><?= htmlspecialchars($plan['name']) ?></div>
                                <div class="plan-price">$<?= number_format($plan['price'], 2) ?></div>
                                <div class="plan-billing"><?= htmlspecialchars($plan['billing']) ?></div>
                            </div>

                            <ul class="plan-features">
                                <?php foreach ($plan['features'] as $feature): ?>
                                    <li>
                                        <i class="fas fa-check"></i>
                                        <?= htmlspecialchars($feature) ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>

                            <button onclick="openAssignModal('<?= $planKey ?>')" class="plan-button <?= $plan['color'] ?>">
                                <i class="fas fa-user-plus mr-2"></i>
                                Assign to User
                            </button>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Users Tab -->
            <div id="tab-content-users" class="tab-content" style="display: none;">
                <div class="mb-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                        <i class="fas fa-users text-emerald-600"></i>
                        User Subscriptions
                    </h3>
                </div>

                <div class="user-table">
                    <div class="table-header">
                        <div>User</div>
                        <div>Email</div>
                        <div>Current Plan</div>
                        <div>Joined</div>
                        <div>Action</div>
                    </div>
                    
                    <?php foreach ($users as $user): ?>
                        <div class="table-row">
                            <div>
                                <div class="font-semibold text-gray-900"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></div>
                            </div>
                            <div class="text-sm text-gray-600"><?= htmlspecialchars($user['email']) ?></div>
                            <div>
                                <span class="badge <?= $user['subscription_plan'] ?? 'basic' ?>">
                                    <?= ucfirst($user['subscription_plan'] ?? 'Basic') ?>
                                </span>
                            </div>
                            <div class="text-sm text-gray-600"><?= date('M d, Y', strtotime($user['created_at'])) ?></div>
                            <div>
                                <button onclick="openChangeModal('<?= htmlspecialchars($user['email']) ?>')" class="text-emerald-600 hover:text-emerald-800 font-semibold text-sm">
                                    <i class="fas fa-edit mr-1"></i>Change
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Payment Methods Tab -->
            <div id="tab-content-payments" class="tab-content" style="display: none;">
                <div class="mb-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                        <i class="fas fa-credit-card text-emerald-600"></i>
                        Payment Methods & Gateways
                    </h3>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                    <!-- PayPal -->
                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-left: 4px solid #0070ba;">
                        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
                            <i class="fas fa-paypal" style="font-size: 28px; color: #0070ba;"></i>
                            <div>
                                <h4 style="font-size: 18px; font-weight: 700; color: #1f2937;">PayPal</h4>
                                <p style="font-size: 13px; color: #6b7280;">Payment Gateway</p>
                            </div>
                        </div>
                        <div style="padding: 12px 16px; background: #f0f8ff; border-radius: 8px; margin-bottom: 16px;">
                            <div style="font-size: 13px; font-weight: 600; color: #0070ba;">Status: Connected & Active</div>
                            <div style="font-size: 12px; color: #0070ba; margin-top: 4px;">Last synced: <?= date('M d, Y H:i'); ?></div>
                        </div>
                        <button onclick="scrollToPaymentGatewaySettings()" style="width: 100%; padding: 10px; background: #0070ba; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                            <i class="fas fa-cog mr-2"></i>Configure
                        </button>
                    </div>

                    <!-- Stripe -->
                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-left: 4px solid #6c63ff;">
                        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;">
                            <i class="fas fa-stripe-s" style="font-size: 28px; color: #6c63ff;"></i>
                            <div>
                                <h4 style="font-size: 18px; font-weight: 700; color: #1f2937;">Stripe</h4>
                                <p style="font-size: 13px; color: #6b7280;">Payment Gateway</p>
                            </div>
                        </div>
                        <div style="padding: 12px 16px; background: #f3f1ff; border-radius: 8px; margin-bottom: 16px;">
                            <div style="font-size: 13px; font-weight: 600; color: #6c63ff;">Status: Not Connected</div>
                            <div style="font-size: 12px; color: #6c63ff; margin-top: 4px;">Ready to integrate</div>
                        </div>
                        <button style="width: 100%; padding: 10px; background: #6c63ff; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                            <i class="fas fa-link mr-2"></i>Connect
                        </button>
                    </div>
                </div>

                <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);">
                    <h4 style="font-size: 18px; font-weight: 700; color: #1f2937; margin-bottom: 16px;">Payment Gateway Configuration</h4>
                    
                    <div style="margin-bottom: 24px;">
                        <h5 style="font-size: 16px; font-weight: 700; color: #374151; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 2px solid #e5e7eb;">PayPal Settings</h5>
                        <form style="display: flex; flex-direction: column; gap: 16px;">
                            <div style="display: grid; grid-cols-1 md:grid-cols-2 gap-16px;">
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Client ID</label>
                                    <div style="display: flex; gap: 8px;">
                                        <input type="password" id="paypalClientId" value="•••••••••••••••••••••" style="flex: 1; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px;" readonly>
                                        <button type="button" onclick="toggleReveal('paypalClientId')" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; cursor: pointer; font-weight: 600;">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Secret Key</label>
                                    <div style="display: flex; gap: 8px;">
                                        <input type="password" id="paypalSecret" value="•••••••••••••••••••••" style="flex: 1; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px;" readonly>
                                        <button type="button" onclick="toggleReveal('paypalSecret')" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; cursor: pointer; font-weight: 600;">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div style="display: grid; grid-cols-1 md:grid-cols-2 gap: 16px;">
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Webhook ID</label>
                                    <input type="text" value="wh_1234567890abcdef" style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px;" readonly>
                                </div>
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Environment</label>
                                    <select style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; background: white; cursor: pointer;">
                                        <option selected>Production</option>
                                        <option>Sandbox</option>
                                    </select>
                                </div>
                            </div>
                            <div style="background: #f0f8ff; padding: 12px 16px; border-radius: 8px; border-left: 4px solid #0070ba;">
                                <p style="font-size: 13px; color: #0070ba;"><strong>Status:</strong> Connected & Active</p>
                                <p style="font-size: 12px; color: #0070ba; margin-top: 4px;">Last tested: <?= date('M d, Y H:i'); ?></p>
                            </div>
                            <div style="display: flex; gap: 8px;">
                                <button type="button" style="padding: 10px 16px; background: #0070ba; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                                    <i class="fas fa-save mr-2"></i>Update Keys
                                </button>
                                <button type="button" onclick="testPayPalConnection()" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; font-weight: 600; cursor: pointer;">
                                    <i class="fas fa-check-circle mr-2"></i>Test Connection
                                </button>
                            </div>
                        </form>
                    </div>

                    <div>
                        <h5 style="font-size: 16px; font-weight: 700; color: #374151; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 2px solid #e5e7eb;">Stripe Settings</h5>
                        <form style="display: flex; flex-direction: column; gap: 16px;">
                            <div style="display: grid; grid-cols-1 md:grid-cols-2 gap: 16px;">
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Publishable Key</label>
                                    <div style="display: flex; gap: 8px;">
                                        <input type="text" id="stripePublishable" placeholder="pk_live_..." style="flex: 1; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; color: #9ca3af;" readonly>
                                        <button type="button" onclick="toggleReveal('stripePublishable')" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; cursor: pointer; font-weight: 600;">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                    </div>
                                </div>
                                <div>
                                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">Secret Key</label>
                                    <div style="display: flex; gap: 8px;">
                                        <input type="password" id="stripeSecret" placeholder="sk_live_..." style="flex: 1; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; color: #9ca3af;" readonly>
                                        <button type="button" onclick="toggleReveal('stripeSecret')" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; cursor: pointer; font-weight: 600;">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div style="background: #fef3c7; padding: 12px 16px; border-radius: 8px; border-left: 4px solid #f59e0b;">
                                <p style="font-size: 13px; color: #b45309;"><strong>Status:</strong> Not Connected</p>
                                <p style="font-size: 12px; color: #b45309; margin-top: 4px;">Ready to integrate - Enter your API keys to enable Stripe payments</p>
                            </div>
                            <div style="display: flex; gap: 8px;">
                                <button type="button" style="padding: 10px 16px; background: #6c63ff; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                                    <i class="fas fa-link mr-2"></i>Connect Stripe
                                </button>
                                <button type="button" style="padding: 10px 16px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; font-weight: 600; cursor: pointer;">
                                    <i class="fas fa-question-circle mr-2"></i>Help
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Analytics Tab -->
            <div id="tab-content-analytics" class="tab-content" style="display: none;">
                <div class="mb-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                        <i class="fas fa-chart-line text-emerald-600"></i>
                        Revenue Analytics
                    </h3>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-top: 4px solid #10b981;">
                        <div style="font-size: 13px; color: #6b7280; font-weight: 600; margin-bottom: 8px;">This Month</div>
                        <div style="font-size: 32px; font-weight: 700; color: #1f2937;">$2,450.00</div>
                        <div style="font-size: 12px; color: #10b981; margin-top: 8px;">
                            <i class="fas fa-arrow-up mr-1"></i>12% increase
                        </div>
                    </div>

                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-top: 4px solid #3b82f6;">
                        <div style="font-size: 13px; color: #6b7280; font-weight: 600; margin-bottom: 8px;">This Year</div>
                        <div style="font-size: 32px; font-weight: 700; color: #1f2937;">$28,900.00</div>
                        <div style="font-size: 12px; color: #3b82f6; margin-top: 8px;">
                            <i class="fas fa-arrow-up mr-1"></i>18% increase
                        </div>
                    </div>

                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-top: 4px solid #8b5cf6;">
                        <div style="font-size: 13px; color: #6b7280; font-weight: 600; margin-bottom: 8px;">Active Subscribers</div>
                        <div style="font-size: 32px; font-weight: 700; color: #1f2937;"><?= count($users) ?></div>
                        <div style="font-size: 12px; color: #8b5cf6; margin-top: 8px;">
                            <i class="fas fa-arrow-up mr-1"></i>5 new this month
                        </div>
                    </div>

                    <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); border-top: 4px solid #f59e0b;">
                        <div style="font-size: 13px; color: #6b7280; font-weight: 600; margin-bottom: 8px;">Avg Monthly Value</div>
                        <div style="font-size: 32px; font-weight: 700; color: #1f2937;">$19.99</div>
                        <div style="font-size: 12px; color: #f59e0b; margin-top: 8px;">
                            <i class="fas fa-info-circle mr-1"></i>Per subscriber
                        </div>
                    </div>
                </div>

                <div style="background: white; border-radius: 12px; padding: 24px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);">
                    <h4 style="font-size: 18px; font-weight: 700; color: #1f2937; margin-bottom: 20px;">Revenue Breakdown</h4>
                    <div style="display: grid; grid-cols-1 md:grid-cols-3 gap-6;">
                        <div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span style="font-weight: 600; color: #1f2937;">Family Plans</span>
                                <span style="font-weight: 700; color: #10b981;">$1,800.00</span>
                            </div>
                            <div style="height: 8px; background: #e5e7eb; border-radius: 4px; overflow: hidden;">
                                <div style="height: 100%; background: linear-gradient(90deg, #10b981, #059669); width: 73%;"></div>
                            </div>
                        </div>

                        <div>
                            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                                <span style="font-weight: 600; color: #1f2937;">Personal Plans</span>
                                <span style="font-weight: 700; color: #3b82f6;">$500.00</span>
                            </div>
                            <div style="height: 8px; background: #e5e7eb; border-radius: 4px; overflow: hidden;">
                                <div style="height: 100%; background: linear-gradient(90deg, #3b82f6, #2563eb); width: 20%;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Assign Plan Modal -->
    <div id="assignModal" class="modal">
        <div class="modal-content">
            <h3 style="font-size: 22px; font-weight: 700; color: #1f2937; margin-bottom: 24px;">
                <i class="fas fa-user-plus text-emerald-600 mr-2"></i>
                Assign Plan to User
            </h3>

            <form method="POST" style="display: flex; flex-direction: column; gap: 16px;">
                <input type="hidden" name="action" value="upgrade_plan">
                <input type="hidden" name="plan" id="selectedPlan">

                <div>
                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">User Email</label>
                    <select name="user_email" required style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px;">
                        <option value="">Select a user...</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?= htmlspecialchars($user['email']) ?>">
                                <?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name'] . ' (' . $user['email'] . ')') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div style="background: #f9fafb; padding: 16px; border-radius: 8px; border-left: 4px solid #10b981;">
                    <div id="planDetails"></div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="closeAssignModal()" style="padding: 10px 20px; border: 1px solid #e5e7eb; background: white; color: #374151; border-radius: 8px; font-weight: 600; cursor: pointer;">
                        Cancel
                    </button>
                    <button type="submit" style="padding: 10px 20px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                        <i class="fas fa-check mr-2"></i>Assign Plan
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Change Plan Modal -->
    <div id="changeModal" class="modal">
        <div class="modal-content">
            <h3 style="font-size: 22px; font-weight: 700; color: #1f2937; margin-bottom: 24px;">
                <i class="fas fa-exchange-alt text-emerald-600 mr-2"></i>
                Change User Plan
            </h3>

            <form method="POST" style="display: flex; flex-direction: column; gap: 16px;">
                <input type="hidden" name="action" value="upgrade_plan">
                <input type="hidden" name="user_email" id="changeUserEmail">

                <div>
                    <label style="display: block; font-weight: 600; color: #1f2937; margin-bottom: 8px;">New Plan</label>
                    <div style="display: grid; grid-cols-1 gap: 8px;">
                        <label style="padding: 12px; border: 2px solid #e5e7eb; border-radius: 8px; cursor: pointer; display: flex; align-items: center;">
                            <input type="radio" name="plan" value="personal" required style="margin-right: 12px;"> 
                            <span><strong>Personal</strong> - $14.99/month</span>
                        </label>
                        <label style="padding: 12px; border: 2px solid #e5e7eb; border-radius: 8px; cursor: pointer; display: flex; align-items: center;">
                            <input type="radio" name="plan" value="family" required style="margin-right: 12px;"> 
                            <span><strong>Family</strong> - $29.99/month</span>
                        </label>
                    </div>
                </div>

                <div style="background: #fff7ed; padding: 16px; border-radius: 8px; border-left: 4px solid #ea580c;">
                    <div style="font-size: 13px; color: #7c2d12;">
                        <i class="fas fa-info-circle mr-2"></i>
                        The plan will be effective immediately. A payment invoice will be sent to the user.
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button type="button" onclick="closeChangeModal()" style="padding: 10px 20px; border: 1px solid #e5e7eb; background: white; color: #374151; border-radius: 8px; font-weight: 600; cursor: pointer;">
                        Cancel
                    </button>
                    <button type="submit" style="padding: 10px 20px; background: linear-gradient(135deg, #10b981, #059669); color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
                        <i class="fas fa-arrow-right mr-2"></i>Proceed to Payment
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const planDetails = {
            personal: { name: 'Personal Plan', price: '$14.99', features: 'Personalized health coaching, Nutrition and wellness tracking, Monthly check-in sessions, Email support' },
            family: { name: 'Family Plan', price: '$29.99', features: 'Up to 4 family members, Individual wellness profiles, Personalized coaching, Advanced tracking, Video consultations, Priority support' }
        };

        function showTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.style.display = 'none';
            });
            document.querySelectorAll('[id^="tab-"]').forEach(btn => {
                btn.classList.remove('active-tab');
            });

            // Show selected tab
            document.getElementById(`tab-content-${tabName}`).style.display = 'block';
            document.getElementById(`tab-${tabName}`).classList.add('active-tab');
        }

        function openAssignModal(planKey) {
            document.getElementById('selectedPlan').value = planKey;
            document.getElementById('planDetails').innerHTML = `
                <div style="font-weight: 600; color: #1f2937; margin-bottom: 8px;">${planDetails[planKey].name}</div>
                <div style="font-size: 20px; font-weight: 700; color: #10b981; margin-bottom: 8px;">${planDetails[planKey].price}/month</div>
                <div style="font-size: 13px; color: #6b7280;">${planDetails[planKey].features}</div>
            `;
            document.getElementById('assignModal').classList.add('active');
        }

        function closeAssignModal() {
            document.getElementById('assignModal').classList.remove('active');
        }

        function openChangeModal(email) {
            document.getElementById('changeUserEmail').value = email;
            document.getElementById('changeModal').classList.add('active');
        }

        function closeChangeModal() {
            document.getElementById('changeModal').classList.remove('active');
        }

        // Payment Gateway Configuration Functions
        function toggleReveal(fieldId) {
            const field = document.getElementById(fieldId);
            if (field.type === 'password') {
                field.type = 'text';
            } else {
                field.type = 'password';
            }
        }

        function testPayPalConnection() {
            const btn = event.target;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Testing...';
            
            setTimeout(() => {
                alert('✓ PayPal connection successful!\n\nClient ID verified\nWebhook configured\nSandbox mode: Disabled');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-check-circle mr-2"></i>Test Connection';
            }, 1500);
        }

        function scrollToPaymentGatewaySettings() {
            document.querySelector('[id$="PaymentGatewaySettings"]')?.scrollIntoView({ behavior: 'smooth' });
        }

        // Close modals on background click
        document.getElementById('assignModal')?.addEventListener('click', (e) => {
            if (e.target.id === 'assignModal') closeAssignModal();
        });

        document.getElementById('changeModal')?.addEventListener('click', (e) => {
            if (e.target.id === 'changeModal') closeChangeModal();
        });

        // Tab switching with border
        document.querySelectorAll('[id^="tab-"]').forEach(tab => {
            if (tab.id.startsWith('tab-') && !tab.id.includes('content')) {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('[id^="tab-"]').forEach(t => {
                        if (!t.id.includes('content')) {
                            t.classList.remove('active-tab');
                            t.style.borderBottomColor = 'transparent';
                            t.style.color = '#666';
                        }
                    });
                    this.classList.add('active-tab');
                    this.style.borderBottomColor = '#10b981';
                    this.style.color = '#10b981';
                });
            }
        });
    </script>
</body>
</html>
