<?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'] ?? (AuthManager::isAuthenticated() ? ($_SESSION['theme_preference'] ?? 'dark') : 'dark');
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

// Workspace query string for URLs
$workspaceQuery = '';
if (!empty($activeWorkspace['username'])) {
    $workspaceQuery = '?workspace=' . urlencode($activeWorkspace['username']);
} elseif (!empty($activeWorkspaceId)) {
    $workspaceQuery = '?workspace=' . $activeWorkspaceId;
}
?>
<!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>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <style>
        .billing-card {
            width: 100%;
            max-width: 100%;
        }

        .billing-card.billing-card--wide {
            width: 100%;
            max-width: 100%;
        }

        .billing-plan-grid {
            width: 100%;
        }

        /* Override billing-stats-grid to use responsive layout like billing-plan-grid */
        .billing-stats-grid {
            display: grid;
            gap: 8px;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        }

        /* Remove page-width constraint to make sections edge-to-edge like index.php */
        .page-width {
            max-width: none !important;
            width: 100% !important;
        }
    </style>
</head>
<body>
    <?php require_once __DIR__ . '/components/navigation.php'; renderNavigationNew('Billing', $currentTheme); ?>

    <div class="main-container">
        <?php
        require_once __DIR__ . '/components/headers/page-header.php';
        
        $actions = [
            ['label' => 'Settings', 'url' => '/settings.php' . $workspaceQuery, 'type' => 'secondary', 'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z'],
            ['label' => 'New Workspace', 'url' => '/workspace-plans.php' . $workspaceQuery, 'type' => 'primary', 'icon' => 'M12 4v16m8-8H4']
        ];
        
        renderPageHeader(
            breadcrumbs: [
                ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6']
            ],
            currentPage: 'Billing',
            actions: $actions,
            workspaceQuery: $workspaceQuery
        );
        ?>

        <!-- Billing Content -->
        <div class="dash-container">
            <div class="page-width">
            <?php if ($flashSuccess): ?>
                <div class="status-banner success" style="margin-bottom: 16px;">
                    <?= htmlspecialchars($flashSuccess) ?>
                </div>
            <?php endif; ?>

            <?php if ($flashError): ?>
                <div class="status-banner error" style="margin-bottom: 16px;">
                    <?= htmlspecialchars($flashError) ?>
                </div>
            <?php endif; ?>

            <div class="dash-section">
                <?php if (!$isOwner && $activeWorkspaceId): ?>
                    <!-- Non-owner message -->
                    <div class="card">
                        <div style="text-align: center;">
                            <div style="margin: 0 auto 16px; width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.6);">
                                <svg width="24" height="24" 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>
                            <h3 class="billing-title">Billing not available</h3>
                            <p class="billing-subtitle" style="max-width: 400px; margin: 8px auto 0;">
                                You are a member of <strong><?= htmlspecialchars($activeWorkspaceName) ?></strong>, but billing is managed by the workspace owner.
                            </p>
                            <p class="billing-subtitle" style="margin-top: 12px;">Contact the workspace owner if you need to make subscription changes.</p>
                            <a href="/index.php?workspace=<?= urlencode($activeWorkspace['username'] ?? $activeWorkspaceId) ?>" 
                               class="billing-btn billing-btn-secondary" style="margin-top: 20px; display: inline-block;">
                                Back to Dashboard
                            </a>
                        </div>
                    </div>
                <?php elseif (!empty($userWorkspaces)): ?>
                <div class="dash-section">
                    <section class="billing-card billing-card--wide">
                        <div style="margin-bottom: 16px;">
                            <div style="margin-top: 4px;">
                                <h2 class="section-title">Workspaces</h2>
                                <p class="billing-subtitle">Select a workspace to manage its subscription.</p>
                            </div>
                            <div class="billing-stats-grid">
                                <?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="billing-plan-card">
                                        <div>
                                            <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 8px;">
                                                <div>
                                                    <p class="billing-plan-name"><?= htmlspecialchars($workspace['name']) ?></p>
                                                    <?php if (!empty($workspace['username'])) : ?>
                                                        <p style="font-size: 11px; color: var(--text-tertiary); margin: 0;">@<?= htmlspecialchars($workspace['username']) ?></p>
                                                    <?php endif; ?>
                                                </div>
                                                <?php $status = resolveSubscriptionStatus($wsSub); ?>
                                                <span class="billing-status <?= $status === 'active' ? 'billing-status-active' : 'billing-status-inactive' ?>"><?= ucfirst($status) ?></span>
                                            </div>
                                            <div style="margin-top: 12px;">
                                                <p style="font-size: 12px; color: var(--text-secondary); margin: 0;">
                                                    <span style="font-weight: 500; color: var(--text-primary);"><?= htmlspecialchars($wsSub['plan_name'] ?? 'No plan') ?></span>
                                                    <span style="color: var(--text-tertiary);"> &middot; </span>
                                                    <span style="font-weight: 600; color: var(--text-primary);"><?= $wsCurrencySymbol ?><?= number_format($wsPrice, 0) ?>/<?= $wsCycle === 'yearly' ? 'yr' : 'mo' ?></span>
                                                </p>
                                                <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">
                                                    Renews <?= !empty($wsSub['subscription_expires_at']) ? date('M j, Y', strtotime($wsSub['subscription_expires_at'])) : 'N/A' ?>
                                                </p>
                                            </div>
                                        </div>
                                        <div style="margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--border-subtle);">
                                            <?php if ($isActive) : ?>
                                                <button class="billing-btn billing-btn-primary" disabled style="width: 100%; opacity: 0.7; cursor: default;">Managing</button>
                                            <?php else : ?>
                                                <a href="/billing.php?workspace=<?= urlencode(getWorkspaceSlug($workspace)) ?>" class="billing-btn billing-btn-secondary" style="width: 100%; text-align: center;">Manage</a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </section>
                </div>
                <?php else: ?>
                    <div class="dashboard-card p-4 text-xs text-neutral-400">No workspaces found for your account.</div>
                <?php endif; ?>
            </div>

            <?php if ($activeWorkspaceId && $isOwner): ?>
                <!-- Usage & Limits Section -->
                <?php if (!empty($usageSummary)): ?>
                <div class="dash-section">
                    <section class="billing-card billing-card--wide">
                        <div style="margin-bottom: 16px;">
                            <div style="margin-top: 4px;">
                                <h2 class="section-title">Usage & limits</h2>
                                <p class="billing-subtitle">Current usage for <?= htmlspecialchars($activeWorkspaceName) ?></p>
                            </div>
                            <div class="billing-stats-grid">
                                <?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="billing-stat-item">
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                                        <span style="font-size: 12px; font-weight: 500; color: var(--text-secondary);"><?= $info['label'] ?></span>
                                        <?php if ($isAtLimit): ?>
                                            <span class="billing-status billing-status-inactive" style="font-size: 9px;">Limit</span>
                                        <?php endif; ?>
                                    </div>
                                    <div style="display: flex; align-items: baseline; gap: 4px;">
                                        <span style="font-size: 20px; font-weight: 600; color: var(--text-primary);"><?= $data['current'] ?></span>
                                        <span style="font-size: 12px; color: var(--text-tertiary);">
                                            / <?= $isUnlimited ? 'Unlimited' : $data['limit'] ?>
                                        </span>
                                    </div>
                                    <?php if (!$isUnlimited): ?>
                                    <div style="margin-top: 8px; height: 6px; background: var(--surface-muted); border-radius: 99px; overflow: hidden;">
                                        <div style="height: 100%; background-color: <?= $isAtLimit ? 'var(--danger)' : 'var(--text-primary)' ?>; border-radius: 99px; 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="status-banner error" style="margin-top: 16px;">
                                <p style="font-size: 12px;">
                                    <strong>You've reached some limits.</strong> Upgrade your plan to unlock more capacity.
                                </p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </section>
                </div>
                <?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);
                    }
                ?>
                <div class="dash-section">
                    <section class="billing-card">
                        <!-- Current Plan Overview -->
                        <div style="padding: 20px; border-bottom: 1px solid var(--border-subtle);">
                            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
                                <div>
                                    <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                                        <span class="section-title" style="margin-bottom: 0;">Current plan</span>
                                        <span class="billing-status billing-status-active">Active</span>
                                    </div>
                                    <h3 style="font-size: 16px; font-weight: 600; color: var(--text-primary); margin-bottom: 4px;"><?= htmlspecialchars($currentPlanName) ?></h3>
                                    <p style="font-size: 12px; color: var(--text-secondary);">Renews <strong style="color: var(--text-primary);"><?= $nextBillingDate ?></strong></p>
                                </div>
                                <div style="text-align: right;">
                                    <div style="font-size: 24px; font-weight: 700; color: var(--text-primary); margin-bottom: 2px;"><?= $currencySymbol ?><?= number_format($currentPrice, 0) ?></div>
                                    <div style="font-size: 12px; color: var(--text-secondary);">/<?= $currentCycle === 'yearly' ? 'year' : 'month' ?> <?= $workspaceCurrency ?></div>
                                </div>
                            </div>
                        </div>

                        <!-- Plan Management -->
                        <div style="padding: 20px;">
                            <form method="POST" class="billing-form" id="billingForm">
                                <input type="hidden" name="workspace_id" value="<?= $activeWorkspaceId ?>">
                                
                                <!-- Available Plans -->
                                <div style="margin-bottom: 24px;">
                                    <h4 class="section-title" style="margin-bottom: 12px;">Available plans</h4>
                                    <div class="billing-plan-grid" 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'];
                                        ?>
                                            <div class="billing-plan-item">
                                                <input type="radio" name="plan_id" value="<?= $plan['id'] ?>" id="plan-<?= $plan['id'] ?>" class="sr-only" <?= $isCurrentPlan ? 'checked' : '' ?>
                                                    data-monthly-usd="<?= $planMonthlyUSD ?>"
                                                    data-yearly-usd="<?= $planYearlyUSD ?>"
                                                    data-monthly-inr="<?= $planMonthlyINR ?>"
                                                    data-yearly-inr="<?= $planYearlyINR ?>">
                                                <div class="billing-plan-card" onclick="document.getElementById('plan-<?= $plan['id'] ?>').checked = true">
                                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                                                        <div class="billing-plan-name"><?= htmlspecialchars($plan['name']) ?></div>
                                                        <?php if ($isCurrentPlan): ?>
                                                            <div class="billing-status billing-status-active">Current</div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="billing-plan-price" data-price>
                                                        <?= $currencySymbol ?><?= number_format($isIndia ? $planMonthlyINR : $planMonthlyUSD, 0) ?>
                                                        <span style="font-size: 11px; font-weight: normal; color: var(--text-tertiary);">/mo</span>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>

                                <!-- Billing Settings -->
                                <div style="margin-bottom: 24px;">
                                    <h4 class="section-title" style="margin-bottom: 12px;">Billing settings</h4>
                                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                                        <div>
                                            <label class="billing-form-label" style="margin-bottom: 6px; display: block;">Billing cycle</label>
                                            <div class="billing-toggle-group">
                                                <input type="radio" name="billing_cycle" value="monthly" id="cycle-monthly" class="sr-only" <?= $currentCycle === 'monthly' ? 'checked' : '' ?>>
                                                <label for="cycle-monthly" class="billing-toggle-btn">Monthly</label>
                                                
                                                <input type="radio" name="billing_cycle" value="yearly" id="cycle-yearly" class="sr-only" <?= $currentCycle === 'yearly' ? 'checked' : '' ?>>
                                                <label for="cycle-yearly" class="billing-toggle-btn">Yearly</label>
                                            </div>
                                        </div>
                                        
                                        <div>
                                            <label class="billing-form-label" style="margin-bottom: 6px; display: block;">Currency</label>
                                            <div class="billing-toggle-group">
                                                <input type="radio" name="currency" value="USD" id="currency-usd" class="sr-only" <?= $workspaceCurrency === 'USD' ? 'checked' : '' ?>>
                                                <label for="currency-usd" class="billing-toggle-btn">USD</label>
                                                
                                                <input type="radio" name="currency" value="INR" id="currency-inr" class="sr-only" <?= $workspaceCurrency === 'INR' ? 'checked' : '' ?>>
                                                <label for="currency-inr" class="billing-toggle-btn">INR</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 16px; border-top: 1px solid var(--border-subtle);">
                                    <div>
                                        <button type="submit" name="manage_action" value="upgrade_plan" class="billing-btn billing-btn-primary">
                                            Save changes
                                        </button>
                                        <button type="submit" name="manage_action" value="renew_plan" class="billing-btn billing-btn-secondary" style="margin-left: 8px;">
                                            Renew now
                                        </button>
                                    </div>
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="manage_action" value="cancel_plan">
                                        <input type="hidden" name="workspace_id" value="<?= $activeWorkspaceId ?>">
                                        <button type="submit" class="billing-btn billing-btn-danger">
                                            Cancel subscription
                                        </button>
                                    </form>
                                </div>
                            </form>
                        </div>
                    </section>
                </div>

                <div class="dash-section">
                    <section class="billing-card">
                        <div style="margin-bottom: 16px;">
                            <div style="margin-top: 4px;">
                                <h2 class="section-title">Billing history</h2>
                                <p class="billing-subtitle">Invoices for <?= htmlspecialchars($activeWorkspaceName) ?>.</p>
                            </div>

                            <?php if (empty($billingHistory)): ?>
                                <p style="font-size: 12px; color: var(--text-secondary);">No invoices yet.</p>
                            <?php else: ?>
                                <div class="table-shell">
                                    <table class="billing-table">
                                        <thead>
                                            <tr>
                                                <th>Invoice</th>
                                                <th>Date</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($billingHistory as $invoice): ?>
                                                <tr>
                                                    <td><?= htmlspecialchars($invoice['invoice_number'] ?? 'N/A') ?></td>
                                                    <td><?= date('M j, Y', strtotime($invoice['created_at'])) ?></td>
                                                    <td><?= $currencySymbol ?><?= number_format((float) $invoice['amount'], 2) ?></td>
                                                    <td>
                                                        <span class="billing-status <?= strtolower($invoice['status']) === 'paid' ? 'billing-status-active' : 'billing-status-inactive' ?>"><?= htmlspecialchars(ucfirst($invoice['status'])) ?></span>
                                                    </td>
                                                    <td>
                                                        <a href="<?= htmlspecialchars($invoice['invoice_url'] ?? '#') ?>" target="_blank" class="billing-btn billing-btn-secondary" style="padding: 4px 8px;">View</a>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                </div>
            <?php else: ?>
                <div class="dash-section">
                    <div class="dashboard-card p-4 text-xs text-neutral-400">Select a workspace to manage its billing.</div>
                </div>
            <?php endif; ?>
            </div>
        </div>

    </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>
