<?php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';
require_once __DIR__ . '/../src/Billing/PlanLimits.php';
require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../src/Permissions/PermissionManager.php';

AuthManager::requireAuth();
TenantManager::initialize();

$user = AuthManager::getCurrentUser();
$company = TenantManager::getCurrentCompany();

function getWorkspaceSlug(array $workspace): string
{
    return $workspace['username'] ?? (string) $workspace['id'];
}

function resolveSubscriptionStatus(?array $subscription): string
{
    if (!$subscription) {
        return 'none';
    }

    $status = strtolower($subscription['subscription_status'] ?? '');
    $hasPlan = !empty($subscription['plan_id']);
    $expiresAt = !empty($subscription['subscription_expires_at']) ? strtotime($subscription['subscription_expires_at']) : null;
    $isExpired = $expiresAt !== null && $expiresAt < time();

    // Respect explicit terminal states
    if (in_array($status, ['canceled', 'past_due'], true)) {
        return $status;
    }

    if ($hasPlan && !$isExpired) {
        return 'active';
    }

    if ($status === 'trial' && !$hasPlan) {
        return 'trial';
    }

    return $status ?: ($hasPlan ? ($isExpired ? 'expired' : 'active') : 'none');
}

function loadUserWorkspaces(?array $user): array
{
    if (!$user) {
        return [];
    }

    $pdo = getPDO();
    $workspaces = [];

    if (!empty($user['company_id'])) {
        $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ? LIMIT 1');
        $stmt->execute([$user['company_id']]);
        if ($row = $stmt->fetch()) {
            $workspaces[$row['id']] = $row;
        }
    }

    $stmt = $pdo->prepare('
        SELECT c.* FROM companies c
        JOIN user_company_access uca ON c.id = uca.company_id
        WHERE uca.user_id = ?
        ORDER BY c.name ASC
    ');
    $stmt->execute([$user['id']]);
    foreach ($stmt->fetchAll() ?: [] as $row) {
        $workspaces[$row['id']] = $row;
    }

    return array_values($workspaces);
}

function findWorkspaceById(int $id, array $workspaces): ?array
{
    foreach ($workspaces as $workspace) {
        if ((int) $workspace['id'] === $id) {
            return $workspace;
        }
    }

    return null;
}

function findWorkspaceBySlugOrId(?string $identifier, array $workspaces): ?array
{
    if ($identifier === null || $identifier === '') {
        return null;
    }

    foreach ($workspaces as $workspace) {
        if (!empty($workspace['username']) && (string) $workspace['username'] === (string) $identifier) {
            return $workspace;
        }

        if ((string) $workspace['id'] === (string) $identifier) {
            return $workspace;
        }
    }

    return null;
}

$userWorkspaces = loadUserWorkspaces($user);
$requestedWorkspaceParam = $_GET['workspace'] ?? null;
$selectedWorkspace = findWorkspaceBySlugOrId($requestedWorkspaceParam, $userWorkspaces);

if ($selectedWorkspace) {
    $_SESSION['current_company_id'] = (int) $selectedWorkspace['id'];
    $_SESSION['current_company'] = $selectedWorkspace;
    TenantManager::setCurrentCompany((int) $selectedWorkspace['id'], $selectedWorkspace);

    if (class_exists('TenantDB')) {
        TenantDB::setTenant((int) $selectedWorkspace['id']);
    }

    $company = $selectedWorkspace;
}

$flashSuccess = $_SESSION['success'] ?? null;
$flashError = $_SESSION['error'] ?? null;
unset($_SESSION['success'], $_SESSION['error']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manage_action'])) {
    $action = $_POST['manage_action'];
    $targetWorkspaceId = (int) ($_POST['workspace_id'] ?? 0);
    $targetWorkspace = findWorkspaceById($targetWorkspaceId, $userWorkspaces);

    if (!$targetWorkspace) {
        $_SESSION['error'] = 'Workspace not found or access denied.';
        header('Location: /billing.php');
        exit;
    }

    $redirectSlug = getWorkspaceSlug($targetWorkspace);

    try {
        switch ($action) {
            case 'renew_plan':
                $cycle = $_POST['billing_cycle'] === 'yearly' ? 'yearly' : ($_POST['billing_cycle'] === 'monthly' ? 'monthly' : null);
                SubscriptionManager::renewSubscription($targetWorkspaceId, $cycle);
                // Log subscription renewal
                workspace_log(
                    'subscription_renewed',
                    'workspace',
                    $targetWorkspaceId,
                    $targetWorkspace['name'] ?? null,
                    null,
                    [
                        'billing_cycle' => $cycle,
                    ]
                );
                $_SESSION['success'] = 'Plan renewed successfully.';
                break;

            case 'upgrade_plan':
                $planId = (int) ($_POST['plan_id'] ?? 0);
                $cycle = $_POST['billing_cycle'] === 'yearly' ? 'yearly' : 'monthly';
                $newCurrency = $_POST['currency'] ?? null;
                
                if ($planId <= 0) {
                    throw new Exception('Choose a plan before updating.');
                }

                SubscriptionManager::updateSubscriptionPlan($targetWorkspaceId, $planId, $cycle);
                
                // Update currency if changed
                if ($newCurrency && in_array($newCurrency, ['USD', 'INR'])) {
                    $pdo = getPDO();
                    $stmt = $pdo->prepare('UPDATE companies SET preferred_currency = ? WHERE id = ?');
                    $stmt->execute([$newCurrency, $targetWorkspaceId]);
                }

                // Log plan and billing update
                workspace_log(
                    'subscription_updated',
                    'workspace',
                    $targetWorkspaceId,
                    $targetWorkspace['name'] ?? null,
                    null,
                    [
                        'plan_id' => $planId,
                        'billing_cycle' => $cycle,
                        'currency' => $newCurrency,
                    ]
                );
                
                $_SESSION['success'] = 'Plan and billing preferences updated.';
                break;

            case 'cancel_plan':
                SubscriptionManager::cancelSubscription($targetWorkspaceId, true);
                // Log subscription cancellation
                workspace_log(
                    'subscription_canceled',
                    'workspace',
                    $targetWorkspaceId,
                    $targetWorkspace['name'] ?? null,
                    null,
                    null
                );
                $_SESSION['success'] = 'Subscription canceled.';
                break;

            default:
                throw new Exception('Unknown billing action.');
        }
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
    }

    header('Location: /billing.php?workspace=' . urlencode($redirectSlug));
    exit;
}

$activeWorkspace = $company;
$activeWorkspaceId = $activeWorkspace['id'] ?? null;
$activeWorkspaceName = $activeWorkspace['name'] ?? 'Workspace';

// Check if user is owner of this workspace
$isOwner = $activeWorkspaceId ? PermissionManager::isOwner((int)$user['id'], (int)$activeWorkspaceId) : false;

$plans = SubscriptionManager::getPlans();
$activeSubscription = $activeWorkspaceId ? SubscriptionManager::getCompanySubscription((int) $activeWorkspaceId) : null;
$billingHistory = $activeWorkspaceId ? SubscriptionManager::getBillingHistory((int) $activeWorkspaceId) : [];

// Get workspace's preferred currency
$workspaceCurrency = $activeWorkspace['preferred_currency'] ?? 'USD';
$currencySymbol = $workspaceCurrency === 'INR' ? '₹' : '$';
$isIndia = $workspaceCurrency === 'INR';

$currentPlanName = $activeSubscription['plan_name'] ?? 'No plan selected';
$currentCycle = $activeSubscription['billing_cycle'] ?? 'monthly';
$nextBillingDate = !empty($activeSubscription['subscription_expires_at'])
    ? date('M j, Y', strtotime($activeSubscription['subscription_expires_at']))
    : 'N/A';

// Get plan limits and usage for the active workspace
$planLimits = $activeWorkspaceId ? PlanLimits::getLimits((int) $activeWorkspaceId) : [];
$planUsage = $activeWorkspaceId ? PlanLimits::getUsage((int) $activeWorkspaceId) : [];
$usageSummary = $activeWorkspaceId ? PlanLimits::getSummary((int) $activeWorkspaceId) : [];
// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Billing - <?= htmlspecialchars($activeWorkspaceName) ?> | Keelance</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --page-bg: #050506;
            --surface-base: #0c0d11;
            --surface-card: #111318;
            --surface-muted: #151821;
            --surface-border: #1c2028;
            --surface-border-strong: #2a2f3c;
            --text-primary: #f4f5f7;
            --text-muted: #9aa1b0;
            --accent: #10b981;
            --accent-outline: rgba(16, 185, 129, 0.35);
            --accent-shadow: 0 25px 55px rgba(16, 185, 129, 0.16);
            --shadow-soft: 0 25px 65px rgba(3, 5, 9, 0.52);
        }

        [data-theme='light'] {
            --page-bg: #f5f7fa;
            --surface-base: #ffffff;
            --surface-card: #ffffff;
            --surface-muted: #f3f4f6;
            --surface-border: #e5e7eb;
            --surface-border-strong: #d1d5db;
            --text-primary: #0f172a;
            --text-muted: #6b7280;
            --accent: #10b981;
            --accent-outline: rgba(16, 185, 129, 0.35);
            --accent-shadow: 0 20px 45px rgba(16, 185, 129, 0.18);
            --shadow-soft: 0 12px 30px rgba(15, 23, 42, 0.14);
        }

        body {
            background: var(--page-bg);
            color: var(--text-primary);
        }

        .billing-shell {
            background: var(--page-bg);
            color: var(--text-primary);
        }

        .btn-emerald {
            background: linear-gradient(120deg, rgba(16, 185, 129, 0.95), rgba(52, 211, 153, 0.9));
            border: 1px solid rgba(16, 185, 129, 0.65);
            color: #04130c;
            font-weight: 600;
            border-radius: 0.375rem;
            box-shadow: 0 15px 35px rgba(16, 185, 129, 0.25);
            transition: transform 0.2s ease, box-shadow 0.2s ease, filter 0.2s ease;
        }

        .btn-emerald:hover {
            transform: translateY(-1px);
            box-shadow: 0 18px 40px rgba(16, 185, 129, 0.35);
            filter: brightness(1.05);
        }

        .dashboard-card {
            background: var(--surface-card);
            border: 1px solid var(--surface-border);
            border-radius: 18px;
            box-shadow: var(--shadow-soft);
            position: relative;
            overflow: hidden;
            transition: border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease;
        }

        .dashboard-card::before {
            content: '';
            position: absolute;
            inset: 0;
            border-radius: inherit;
            border-top: 1px solid rgba(255, 255, 255, 0.02);
            pointer-events: none;
        }

        .dashboard-card:hover {
            border-color: var(--accent-outline);
            box-shadow: var(--accent-shadow);
            transform: translateY(-2px);
        }

        .status-banner {
            border-radius: 14px;
            padding: 12px 16px;
            font-size: 0.75rem;
            display: flex;
            align-items: center;
            gap: 10px;
            border: 1px solid transparent;
        }

        .status-banner.success {
            background: rgba(52, 211, 153, 0.12);
            border-color: rgba(52, 211, 153, 0.35);
            color: #a6f4c5;
        }

        .status-banner.error {
            background: rgba(248, 113, 113, 0.12);
            border-color: rgba(248, 113, 113, 0.35);
            color: #fecaca;
        }

        .section-title {
            font-size: 0.95rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .section-subtitle {
            font-size: 0.8rem;
            color: var(--text-muted);
        }

        .stat-card {
            border-radius: 16px;
            border: 1px solid var(--surface-border);
            padding: 16px;
            background: linear-gradient(140deg, var(--surface-card), var(--surface-muted));
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.01);
            transition: border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease;
        }

        .stat-card:hover {
            border-color: var(--accent-outline);
            box-shadow: var(--accent-shadow);
            transform: translateY(-3px);
        }

        .workspace-card {
            border-radius: 16px;
            border: 1px solid var(--surface-border);
            background: var(--surface-card);
            padding: 18px;
            transition: border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease;
        }

        .workspace-card:hover {
            border-color: var(--accent-outline);
            box-shadow: var(--accent-shadow);
            transform: translateY(-2px);
        }

        .workspace-card.active {
            border-color: var(--accent);
            background: var(--surface-card);
            box-shadow: 0 0 0 1px var(--accent);
        }

        .plan-header {
            background: rgba(16, 185, 129, 0.08);
            border-bottom: 1px solid var(--surface-border);
        }

        .table-shell {
            border-radius: 16px;
            border: 1px solid var(--surface-border);
            overflow: hidden;
            transition: border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease;
        }

        .table-shell:hover {
            border-color: var(--accent-outline);
            box-shadow: var(--accent-shadow);
            transform: translateY(-2px);
        }
    </style>
</head>
<body class="min-h-screen font-sans antialiased">
    <div class="min-h-screen flex flex-col billing-shell">
        <?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Billing', $currentTheme); ?>

        <div class="hidden md:block"></div>

        <main class="flex-1 flex flex-col md:ml-56">
            <!-- Top Header -->
            <header class="sticky top-0 z-30 flex items-center justify-between px-3 md:px-6 h-12 border-b border-neutral-800 bg-neutral-950">
                <div class="flex items-center gap-3 text-sm text-neutral-400">
                    <button id="mobile-menu-btn" class="md:hidden inline-flex items-center justify-center p-2 rounded-lg text-neutral-400 hover:text-neutral-100 hover:bg-neutral-800 transition">
                        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                        </svg>
                    </button>
                    <nav class="flex items-center gap-2 text-xs">
                        <span class="inline-flex items-center gap-1 text-[#A1A1A1]">
                            <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                            </svg>
                            Profile
                        </span>
                        <svg class="h-3 w-3 text-neutral-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                        <span class="text-neutral-50 font-semibold truncate max-w-[140px] md:max-w-xs">Billing</span>
                    </nav>
                </div>
                <div class="flex items-center gap-2 text-xs">
                    <?php 
                    $workspaceQuery = '';
                    if (!empty($activeWorkspace['username'])) {
                        $workspaceQuery = '?workspace=' . urlencode($activeWorkspace['username']);
                    } elseif (!empty($activeWorkspaceId)) {
                        $workspaceQuery = '?workspace=' . $activeWorkspaceId;
                    }
                    ?>
                    <a href="/settings.php<?= $workspaceQuery ?>" class="inline-flex items-center gap-1 rounded-md border border-neutral-800 px-3 py-1 text-neutral-200 hover:border-neutral-700">
                        <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11.983 6.042a1.958 1.958 0 110 3.917 1.958 1.958 0 010-3.917zm0-4.042a.958.958 0 00-.958.958V4.3a5.958 5.958 0 00-2.042.918l-1.1-1.1a.958.958 0 00-1.355 1.355l1.1 1.1A5.958 5.958 0 004.3 10.04H2.958a.958.958 0 000 1.917H4.3a5.958 5.958 0 00.918 2.042l-1.1 1.1a.958.958 0 101.355 1.355l1.1-1.1a5.958 5.958 0 002.042.918v1.342a.958.958 0 001.917 0V16.3a5.958 5.958 0 002.042-.918l1.1 1.1a.958.958 0 001.355-1.355l-1.1-1.1a5.958 5.958 0 00.918-2.042h1.342a.958.958 0 000-1.917H17.7a5.958 5.958 0 00-.918-2.042l1.1-1.1a.958.958 0 10-1.355-1.355l-1.1 1.1A5.958 5.958 0 0012.94 4.3V2.958a.958.958 0 00-.958-.958z"></path>
                        </svg>
                        Settings
                    </a>
                    <a href="/workspace-plans.php<?= $workspaceQuery ?>" class="btn-emerald inline-flex items-center gap-1 px-3 py-1 text-xs">
                        <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"></path>
                        </svg>
                        New Workspace
                    </a>
                </div>
            </header>

            <div class="flex-1">
                <div class="max-w-7xl mx-auto px-3 md:px-6 pt-6 pb-4 space-y-6">
                    <section class="dashboard-card overflow-hidden">
                        <div class="bg-gradient-to-r from-emerald-500/10 via-transparent to-transparent px-6 py-6 space-y-4">
                            <p class="text-[11px] uppercase tracking-[0.35em] text-neutral-500">Workspace Billing</p>
                            <div class="flex flex-col gap-5 md:flex-row md:items-center md:justify-between">
                                <div class="space-y-2 max-w-2xl">
                                    <h2 class="text-lg font-semibold text-neutral-50">Stay on top of your plan and invoices</h2>
                                    <p class="text-xs text-neutral-400">Review subscriptions, usage, and payment history for <span class="font-semibold text-neutral-50"><?= htmlspecialchars($activeWorkspaceName) ?></span>. Update your plan or currency anytime.</p>
                                </div>
                                <div class="grid grid-cols-1 gap-2 text-xs text-neutral-400">
                                    <div class="hero-chip inline-flex items-center gap-2 rounded-full border border-emerald-500/30 bg-emerald-500/10 px-3 py-1 text-emerald-200">
                                        <span class="text-[10px] uppercase tracking-[0.2em]">Current plan</span>
                                        <span class="font-semibold text-neutral-50"><?= htmlspecialchars($currentPlanName ?? 'N/A') ?></span>
                                    </div>
                                    <div class="hero-chip inline-flex items-center gap-2 rounded-full border border-neutral-800 bg-neutral-900/60 px-3 py-1">
                                        <span class="text-[10px] uppercase tracking-[0.2em] text-neutral-500">Currency</span>
                                        <span class="font-semibold text-neutral-100"><?= htmlspecialchars($preferredCurrency ?? ($isIndia ? 'INR' : 'USD')) ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <?php if ($flashSuccess): ?>
                        <div class="status-banner success">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                            </svg>
                            <span><?= htmlspecialchars($flashSuccess) ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($flashError): ?>
                        <div class="status-banner error">
                            <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm-.75-11.5a.75.75 0 011.5 0v5a.75.75 0 01-1.5 0v-5zm.75 8a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"></path>
                            </svg>
                            <span><?= htmlspecialchars($flashError) ?></span>
                        </div>
                    <?php endif; ?>

                <?php if (!$isOwner && $activeWorkspaceId): ?>
                    <!-- Non-owner message -->
                    <section class="dashboard-card">
                        <div class="p-6 text-center">
                            <div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-300">
                                <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                                </svg>
                            </div>
                            <h2 class="section-title">Billing not available</h2>
                            <p class="mt-2 text-xs text-neutral-400 max-w-md mx-auto">
                                You are a member of <strong class="text-neutral-50"><?= htmlspecialchars($activeWorkspaceName) ?></strong>, but billing is managed by the workspace owner.
                            </p>
                            <p class="mt-4 text-[11px] text-neutral-500">Contact the workspace owner if you need to make subscription changes.</p>
                            <a href="/index.php?workspace=<?= urlencode($activeWorkspace['username'] ?? $activeWorkspaceId) ?>" 
                               class="mt-6 inline-flex items-center justify-center rounded-md border border-neutral-800 bg-neutral-900 px-4 py-2 text-xs font-medium text-neutral-100 hover:border-neutral-600 hover:bg-neutral-800 transition">
                                Back to Dashboard
                            </a>
                        </div>
                    </section>
                <?php elseif (!empty($userWorkspaces)): ?>
                    <section class="dashboard-card">
                        <div class="p-6 space-y-4">
                            <div>
                                <h2 class="section-title">Workspaces</h2>
                                <p class="section-subtitle">Select a workspace to manage its subscription.</p>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <?php foreach ($userWorkspaces as $workspace): ?>
                                    <?php 
                                        $wsSub = SubscriptionManager::getCompanySubscription((int) $workspace['id']); 
                                        $isActive = $activeWorkspaceId && (int) $workspace['id'] === (int) $activeWorkspaceId;
                                        $wsCurrency = $workspace['preferred_currency'] ?? 'USD';
                                        $wsCurrencySymbol = $wsCurrency === 'INR' ? '₹' : '$';
                                        $wsCycle = $wsSub['billing_cycle'] ?? 'monthly';
                                        
                                        // Get plan price in workspace currency
                                        $wsPlan = SubscriptionManager::getPlan((int)($wsSub['plan_id'] ?? 0));
                                        if ($wsCurrency === 'INR') {
                                            $wsPrice = $wsCycle === 'yearly' 
                                                ? (float)($wsPlan['price_yearly_inr'] ?? ($wsPlan['price_yearly'] ?? 0) * 83)
                                                : (float)($wsPlan['price_monthly_inr'] ?? ($wsPlan['price_monthly'] ?? 0) * 83);
                                        } else {
                                            $wsPrice = $wsCycle === 'yearly' 
                                                ? (float)($wsPlan['price_yearly'] ?? 0)
                                                : (float)($wsPlan['price_monthly'] ?? 0);
                                        }
                                    ?>
                                    <div class="workspace-card <?= $isActive ? 'active' : '' ?>">
                                        <div class="flex flex-col h-full">
                                            <div class="flex-1">
                                                <div class="flex items-start justify-between gap-3">
                                                    <div>
                                                        <p class="text-sm font-semibold text-neutral-50"><?= htmlspecialchars($workspace['name']) ?></p>
                                                        <?php if (!empty($workspace['username'])): ?>
                                                            <p class="text-[11px] text-neutral-500">@<?= htmlspecialchars($workspace['username']) ?></p>
                                                        <?php endif; ?>
                                                        <div class="mt-2 space-y-0.5">
                                                            <p class="text-[12px] text-neutral-400">
                                                                <span class="font-medium text-neutral-50"><?= htmlspecialchars($wsSub['plan_name'] ?? 'No plan') ?></span>
                                                                <span class="text-neutral-600"></span>
                                                                <span class="font-semibold text-neutral-100"><?= $wsCurrencySymbol ?><?= number_format($wsPrice, 0) ?>/<?= $wsCycle === 'yearly' ? 'yr' : 'mo' ?></span>
                                                            </p>
                                                            <p class="text-[11px] text-neutral-500">
                                                                <?= $wsCurrency === 'INR' ? '' : '' ?>
                                                                Renews <?= !empty($wsSub['subscription_expires_at']) ? date('M j, Y', strtotime($wsSub['subscription_expires_at'])) : 'N/A' ?>
                                                            </p>
                                                        </div>
                                                    </div>
                                                    <div class="flex flex-col items-end gap-2">
                                                        <?php $status = resolveSubscriptionStatus($wsSub); ?>
                                                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-medium
                                                            <?= $status === 'active' ? 'bg-emerald-500/15 text-emerald-300' : ($status === 'trial' ? 'bg-sky-500/15 text-sky-300' : 'bg-neutral-800 text-neutral-300') ?>">
                                                            <?= ucfirst($status) ?>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="mt-4 pt-3 border-t border-neutral-800/50">
                                                <?php if ($isActive): ?>
                                                    <div class="text-center">
                                                        <span class="inline-flex items-center px-3 py-1.5 rounded-full bg-emerald-500/10 border border-emerald-500/30 text-[11px] font-medium text-emerald-300">
                                                            <svg class="w-3 h-3 mr-1.5" fill="currentColor" viewBox="0 0 20 20">
                                                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                                                            </svg>
                                                            Managing
                                                        </span>
                                                    </div>
                                                <?php else: ?>
                                                    <a href="/billing.php?workspace=<?= urlencode(getWorkspaceSlug($workspace)) ?>"
                                                       class="w-full inline-flex items-center justify-center rounded-md border border-neutral-800 bg-neutral-900 px-3 py-2 text-[11px] font-medium text-neutral-100 hover:border-neutral-600 hover:bg-neutral-800 transition">
                                                        Manage
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </section>
                <?php else: ?>
                    <div class="dashboard-card p-4 text-xs text-neutral-400">No workspaces found for your account.</div>
                <?php endif; ?>

                <?php if ($activeWorkspaceId && $isOwner): ?>
                    <!-- Usage & Limits Section -->
                    <?php if (!empty($usageSummary)): ?>
                    <section class="dashboard-card">
                        <div class="p-6 space-y-4">
                            <div>
                                <h2 class="section-title">Usage & limits</h2>
                                <p class="section-subtitle">Current usage for <?= htmlspecialchars($activeWorkspaceName) ?></p>
                            </div>
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                                <?php 
                                $limitLabels = [
                                    'users' => ['label' => 'Team Members', 'icon' => 'users'],
                                    'clients' => ['label' => 'Clients', 'icon' => 'building'],
                                    'templates' => ['label' => 'Templates', 'icon' => 'file-text'],
                                    'proposals_per_month' => ['label' => 'Proposals/Mo', 'icon' => 'file'],
                                    'contracts_per_month' => ['label' => 'Contracts/Mo', 'icon' => 'file-signature'],
                                    'invoices_per_month' => ['label' => 'Invoices/Mo', 'icon' => 'receipt'],
                                ];
                                foreach ($usageSummary as $key => $data): 
                                    if (!isset($limitLabels[$key])) continue;
                                    $info = $limitLabels[$key];
                                    $percentage = $data['limit'] > 0 ? min(100, ($data['current'] / $data['limit']) * 100) : 0;
                                    $isUnlimited = $data['limit'] === -1;
                                    $isAtLimit = $data['is_at_limit'] ?? false;
                                ?>
                                <div class="rounded-lg border <?= $isAtLimit ? 'border-amber-500/60 bg-amber-500/10' : 'border-neutral-800 bg-neutral-900' ?> p-3">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-xs font-medium <?= $isAtLimit ? 'text-amber-200' : 'text-neutral-300' ?>"><?= $info['label'] ?></span>
                                        <?php if ($isAtLimit): ?>
                                            <span class="text-[10px] px-1.5 py-0.5 bg-amber-500/80 text-neutral-900 rounded">Limit</span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="flex items-baseline gap-1">
                                        <span class="text-xl font-bold <?= $isAtLimit ? 'text-amber-200' : 'text-neutral-50' ?>"><?= $data['current'] ?></span>
                                        <span class="text-xs text-neutral-500">
                                            / <?= $isUnlimited ? '' : $data['limit'] ?>
                                        </span>
                                    </div>
                                    <?php if (!$isUnlimited): ?>
                                    <div class="mt-2 h-1.5 bg-neutral-800 rounded-full overflow-hidden">
                                        <div class="h-full <?= $isAtLimit ? 'bg-amber-500' : 'bg-emerald-500' ?> rounded-full" style="width: <?= $percentage ?>%"></div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php 
                            $hasLimitReached = false;
                            foreach ($usageSummary as $data) {
                                if ($data['is_at_limit'] ?? false) {
                                    $hasLimitReached = true;
                                    break;
                                }
                            }
                            if ($hasLimitReached): 
                            ?>
                            <div class="mt-4 rounded-lg bg-amber-500/10 border border-amber-500/40 px-4 py-3">
                                <p class="text-xs text-amber-100">
                                    <strong>You've reached some limits.</strong> Upgrade your plan to unlock more capacity.
                                </p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </section>
                    <?php endif; ?>

                    <?php
                        // Calculate current price for display
                        $currentPlan = SubscriptionManager::getPlan((int)($activeSubscription['plan_id'] ?? 0));
                        if ($isIndia) {
                            $currentPrice = $currentCycle === 'yearly' 
                                ? (float)($currentPlan['price_yearly_inr'] ?? ($currentPlan['price_yearly'] ?? 0) * 83)
                                : (float)($currentPlan['price_monthly_inr'] ?? ($currentPlan['price_monthly'] ?? 0) * 83);
                        } else {
                            $currentPrice = $currentCycle === 'yearly' 
                                ? (float)($currentPlan['price_yearly'] ?? 0)
                                : (float)($currentPlan['price_monthly'] ?? 0);
                        }
                    ?>
                    <section class="dashboard-card" style="overflow: hidden; padding: 0;">
                        <!-- Current Plan Header -->
                        <div class="px-6 py-4 plan-header">
                            <div class="flex items-center justify-between">
                                <div>
                                    <p class="text-[11px] font-medium text-emerald-300 uppercase tracking-wide">Current plan</p>
                                    <h2 class="text-base font-semibold text-neutral-50"><?= htmlspecialchars($currentPlanName) ?></h2>
                                </div>
                                <div class="text-right">
                                    <p class="text-xl font-bold text-neutral-50"><?= $currencySymbol ?><?= number_format($currentPrice, 0) ?></p>
                                    <p class="text-[11px] text-neutral-400">/<?= $currentCycle === 'yearly' ? 'year' : 'month' ?> <?= $workspaceCurrency ?></p>
                                </div>
                            </div>
                            <div class="mt-3 flex items-center gap-4 text-[11px] text-neutral-300">
                                <span class="flex items-center gap-1">
                                    <?= $isIndia ? '' : '' ?>
                                    <strong class="font-semibold"><?= $isIndia ? 'Razorpay' : 'Stripe' ?></strong>
                                </span>
                                <span></span>
                                <span>Renews <strong class="font-semibold text-neutral-50"><?= $nextBillingDate ?></strong></span>
                                <span></span>
                                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium bg-emerald-500/15 text-emerald-300">Active</span>
                            </div>
                        </div>

                        <div class="p-6 space-y-6">
                            <form method="POST" class="space-y-5" id="billingForm">
                                <input type="hidden" name="workspace_id" value="<?= $activeWorkspaceId ?>">
                                
                                <!-- Plan Selection -->
                                <div>
                                    <label class="block text-sm font-semibold text-neutral-200 mb-2">Change plan</label>
                                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-3" id="planCards">
                                        <?php foreach ($plans as $plan): 
                                            $planMonthlyUSD = (float)$plan['price_monthly'];
                                            $planYearlyUSD = (float)$plan['price_yearly'];
                                            $planMonthlyINR = (float)($plan['price_monthly_inr'] ?? $plan['price_monthly'] * 83);
                                            $planYearlyINR = (float)($plan['price_yearly_inr'] ?? $plan['price_yearly'] * 83);
                                            $isCurrentPlan = ($activeSubscription['plan_id'] ?? null) == $plan['id'];
                                        ?>
                                            <label class="relative cursor-pointer">
                                                <input type="radio" name="plan_id" value="<?= $plan['id'] ?>" class="sr-only peer" <?= $isCurrentPlan ? 'checked' : '' ?>
                                                    data-monthly-usd="<?= $planMonthlyUSD ?>"
                                                    data-yearly-usd="<?= $planYearlyUSD ?>"
                                                    data-monthly-inr="<?= $planMonthlyINR ?>"
                                                    data-yearly-inr="<?= $planYearlyINR ?>">
                                                <div class="stat-card cursor-pointer transition-all hover:border-emerald-500/50 peer-checked:border-emerald-500 peer-checked:bg-emerald-500/5">
                                                    <div class="flex items-center justify-between">
                                                        <span class="font-semibold text-neutral-50"><?= htmlspecialchars($plan['name']) ?></span>
                                                        <?php if ($isCurrentPlan): ?>
                                                            <span class="text-[10px] bg-emerald-500 text-white px-1.5 py-0.5 rounded">Current</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <p class="text-lg font-bold text-neutral-50 mt-1" data-price>
                                                        <?= $currencySymbol ?><?= number_format($isIndia ? $planMonthlyINR : $planMonthlyUSD, 0) ?>
                                                        <span class="text-xs font-normal text-neutral-400">/mo</span>
                                                    </p>
                                                </div>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <!-- Billing Cycle & Currency -->
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-semibold text-neutral-200 mb-2">Billing cycle</label>
                                        <div class="inline-flex rounded-lg border border-neutral-800 p-1 bg-neutral-900 w-full">
                                            <label class="flex-1 text-center cursor-pointer">
                                                <input type="radio" name="billing_cycle" value="monthly" class="sr-only peer" <?= $currentCycle === 'monthly' ? 'checked' : '' ?>>
                                                <span class="block py-2 px-3 rounded-md text-sm font-medium border border-transparent transition-all peer-checked:border-emerald-400 peer-checked:bg-emerald-500/10 peer-checked:text-emerald-300 text-neutral-400">Monthly</span>
                                            </label>
                                            <label class="flex-1 text-center cursor-pointer">
                                                <input type="radio" name="billing_cycle" value="yearly" class="sr-only peer" <?= $currentCycle === 'yearly' ? 'checked' : '' ?>>
                                                <span class="block py-2 px-3 rounded-md text-sm font-medium border border-transparent transition-all peer-checked:border-emerald-400 peer-checked:bg-emerald-500/10 peer-checked:text-emerald-300 text-neutral-400">
                                                    Yearly
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-semibold text-neutral-200 mb-2">Currency & gateway</label>
                                        <div class="inline-flex rounded-lg border border-neutral-800 p-1 bg-neutral-900 w-full">
                                            <label class="flex-1 text-center cursor-pointer">
                                                <input type="radio" name="currency" value="USD" class="sr-only peer" <?= $workspaceCurrency === 'USD' ? 'checked' : '' ?>>
                                                <span class="block py-2 px-3 rounded-md text-sm font-medium border border-transparent transition-all peer-checked:border-emerald-400 peer-checked:bg-emerald-500/10 peer-checked:text-emerald-300 text-neutral-400">
                                                    USD <span class="text-[10px] text-neutral-500">Stripe</span>
                                                </span>
                                            </label>
                                            <label class="flex-1 text-center cursor-pointer">
                                                <input type="radio" name="currency" value="INR" class="sr-only peer" <?= $workspaceCurrency === 'INR' ? 'checked' : '' ?>>
                                                <span class="block py-2 px-3 rounded-md text-sm font-medium border border-transparent transition-all peer-checked:border-emerald-400 peer-checked:bg-emerald-500/10 peer-checked:text-emerald-300 text-neutral-400">
                                                    INR <span class="text-[10px] text-neutral-500">Razorpay</span>
                                                </span>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="flex flex-col sm:flex-row gap-3 pt-2 sm:justify-end">
                                    <button type="submit" name="manage_action" value="upgrade_plan" class="w-full sm:w-auto inline-flex items-center justify-center rounded-md bg-emerald-500 px-4 py-2 text-sm font-semibold text-emerald-950 shadow-lg shadow-emerald-500/30 hover:bg-emerald-400 transition">
                                        Save changes
                                    </button>
                                    <button type="submit" name="manage_action" value="renew_plan" class="w-full sm:w-auto inline-flex items-center justify-center rounded-md border border-neutral-800 bg-neutral-900 px-4 py-2 text-sm font-medium text-neutral-100 hover:border-neutral-600 hover:bg-neutral-800 transition">
                                        Renew now
                                    </button>
                                </div>
                            </form>

                            <!-- Cancel Subscription -->
                            <div class="pt-4 border-t border-neutral-800">
                                <form method="POST" class="flex items-center justify-between">
                                    <input type="hidden" name="manage_action" value="cancel_plan">
                                    <input type="hidden" name="workspace_id" value="<?= $activeWorkspaceId ?>">
                                    <div>
                                        <p class="text-xs font-medium text-neutral-200">Cancel subscription</p>
                                        <p class="text-[11px] text-neutral-500">Stops service immediately</p>
                                    </div>
                                    <button type="submit" class="inline-flex items-center justify-center rounded-md border border-rose-500/40 bg-rose-500/10 px-3 py-1.5 text-[11px] font-medium text-rose-100 hover:bg-rose-500/20">
                                        Cancel
                                    </button>
                                </form>
                            </div>
                        </div>
                    </section>

                    <section class="dashboard-card">
                        <div class="p-6 space-y-4">
                            <div>
                                <h2 class="section-title">Billing history</h2>
                                <p class="section-subtitle">Invoices for <?= htmlspecialchars($activeWorkspaceName) ?>.</p>
                            </div>

                            <?php if (empty($billingHistory)): ?>
                                <p class="text-xs text-neutral-400">No invoices yet.</p>
                            <?php else: ?>
                                <div class="table-shell">
                                    <table class="min-w-full divide-y divide-neutral-800 text-xs">
                                        <thead class="bg-neutral-900 text-[11px] font-semibold text-neutral-400">
                                            <tr>
                                                <th class="px-4 py-2 text-left">Invoice</th>
                                                <th class="px-4 py-2 text-left">Date</th>
                                                <th class="px-4 py-2 text-left">Amount</th>
                                                <th class="px-4 py-2 text-left">Status</th>
                                                <th class="px-4 py-2 text-left">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-neutral-900 bg-neutral-950 text-[11px]">
                                            <?php foreach ($billingHistory as $invoice): ?>
                                                <tr>
                                                    <td class="px-4 py-2 font-medium text-neutral-50"><?= htmlspecialchars($invoice['invoice_number'] ?? '') ?></td>
                                                    <td class="px-4 py-2 text-neutral-400"><?= date('M j, Y', strtotime($invoice['created_at'])) ?></td>
                                                    <td class="px-4 py-2 text-neutral-50"><?= $currencySymbol ?><?= number_format($invoice['amount'], 2) ?></td>
                                                    <td class="px-4 py-2">
                                                        <span class="inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-medium
                                                            <?= ($invoice['status'] ?? '') === 'paid' ? 'bg-emerald-500/10 text-emerald-300' : 'bg-neutral-800 text-neutral-300' ?>">
                                                            <?= ucfirst($invoice['status'] ?? 'pending') ?>
                                                        </span>
                                                    </td>
                                                    <td class="px-4 py-2 text-neutral-300">
                                                        <a href="#" class="text-[11px] font-medium hover:underline hover:text-neutral-50">View</a>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                <?php else: ?>
                    <div class="dashboard-card p-4 text-xs text-neutral-400">Select a workspace to manage its billing.</div>
                <?php endif; ?>
            </div>
            </div>
        </main>

    </div>

    <script>
        (function syncTheme() {
            const saved = localStorage.getItem('theme') || 'dark';
            document.documentElement.dataset.theme = saved;
            document.body.dataset.theme = saved;
        })();

        document.addEventListener('DOMContentLoaded', () => {
            // Wire mobile menu button to open app sidebar
            const mobileMenuBtn = document.getElementById('mobile-menu-btn');
            if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
                mobileMenuBtn.addEventListener('click', function () {
                    window.openAppSidebar();
                });
            }
        });
    </script>
</body>
</html>
