<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/../../src/SuperAdmin/WorkspaceManager.php';
require_once __DIR__ . '/../../src/SuperAdmin/PlatformSettings.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requirePermission('billing_view');

$admin = SuperAdminAuth::getCurrentAdmin();
$pdo = getPDO();

// Get billing summary
$billingSummary = WorkspaceManager::getBillingSummary();
$workspaceStats = WorkspaceManager::getStats();
$usdToInrRate = (float)PlatformSettings::get('usd_to_inr_rate', 83.0);
if ($usdToInrRate <= 0) {
    $usdToInrRate = 83.0;
}

$combinedMrrUsd = (float)($billingSummary['monthly_revenue_usd'] ?? 0);
$combinedMrrInr = (float)($billingSummary['monthly_revenue_inr'] ?? 0);
$usdMonthlyNative = (float)($billingSummary['usd_monthly_revenue_native'] ?? 0);
$usdYearlyNative = (float)($billingSummary['usd_yearly_revenue_native'] ?? 0);
$inrMonthlyNative = (float)($billingSummary['inr_monthly_revenue_native'] ?? 0);
$inrYearlyNative = (float)($billingSummary['inr_yearly_revenue_native'] ?? 0);
$usdRevenueTotal = max($usdMonthlyNative + $usdYearlyNative, 0.0);
$inrRevenueTotal = max($inrMonthlyNative + $inrYearlyNative, 0.0);
$usdMonthlyShare = $usdRevenueTotal > 0 ? (int)round(($usdMonthlyNative / $usdRevenueTotal) * 100) : 0;
$usdYearlyShare = max(0, 100 - $usdMonthlyShare);
$inrMonthlyShare = $inrRevenueTotal > 0 ? (int)round(($inrMonthlyNative / $inrRevenueTotal) * 100) : 0;
$inrYearlyShare = max(0, 100 - $inrMonthlyShare);
$usdWorkspaces = (int)($billingSummary['usd_workspaces'] ?? 0);
$inrWorkspaces = (int)($billingSummary['inr_workspaces'] ?? 0);
$paidWorkspaces = (int)($billingSummary['paid_workspaces'] ?? 0);
$trialWorkspaces = (int)($billingSummary['trial_workspaces'] ?? 0);
$renewalsThisWeek = (int)($billingSummary['renewals_this_week'] ?? 0);
$renewalsThisMonth = (int)($billingSummary['renewals_this_month'] ?? 0);
$expiringSoon = (int)($workspaceStats['expiring_soon'] ?? 0);
$statusBreakdown = $workspaceStats['by_status'] ?? [];

// Get upcoming renewals
$stmt = $pdo->query("
    SELECT c.*, sp.name as plan_name, u.name as owner_name, u.email as owner_email
    FROM companies c
    LEFT JOIN subscription_plans sp ON c.plan_id = sp.id
    LEFT JOIN users u ON c.owner_id = u.id
    WHERE c.subscription_expires_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
    AND c.subscription_status = 'active'
    ORDER BY c.subscription_expires_at ASC
    LIMIT 20
");
$upcomingRenewals = $stmt->fetchAll();

// Get recent payments (from billing_invoices if exists)
$recentPayments = [];
try {
    $stmt = $pdo->query("
        SELECT bi.*, c.name as company_name, sp.name as plan_name
        FROM billing_invoices bi
        JOIN companies c ON bi.company_id = c.id
        LEFT JOIN subscription_plans sp ON c.plan_id = sp.id
        WHERE bi.status = 'paid'
        ORDER BY bi.paid_at DESC
        LIMIT 10
    ");
    $recentPayments = $stmt->fetchAll();
} catch (Exception $e) {
    // Table may not exist
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Billing · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen text-slate-900">
<?php renderAdminNavigation(); ?>

<main class="flex-1">
    <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
                <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Billing Overview</h1>
                <p class="text-slate-500 mt-1 text-sm">Revenue, subscriptions, and payment analytics across all workspaces.</p>
            </div>
            <div class="flex items-center gap-2 text-xs text-slate-500">
                <span class="inline-flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2.5 py-1 shadow-sm">
                    <span class="h-1.5 w-1.5 rounded-full bg-amber-500"></span>
                    <span class="font-medium text-slate-700">Billing & revenue</span>
                </span>
            </div>
        </div>

        <!-- Summary -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="rounded-2xl border border-slate-200 bg-gradient-to-br from-white to-slate-50 p-4 shadow-sm hover:shadow-md transition-shadow duration-200">
                <p class="text-sm font-semibold text-slate-900">Combined MRR</p>
                <p class="text-3xl font-semibold text-slate-900 mt-2">$<?= number_format($combinedMrrUsd, 0) ?></p>
                <p class="text-sm text-slate-500">≈ ₹<?= number_format($combinedMrrInr, 0) ?></p>
                <p class="text-[11px] text-slate-400 mt-3">1 USD = ₹<?= number_format($usdToInrRate, 2) ?> (admin rate)</p>
            </div>
            <div class="rounded-2xl border border-slate-200 bg-gradient-to-br from-white to-amber-50 p-4 shadow-sm hover:shadow-md transition-shadow duration-200">
                <p class="text-sm font-semibold text-slate-900">USD Workspaces</p>
                <p class="text-3xl font-semibold text-slate-900 mt-2"><?= number_format($usdWorkspaces) ?></p>
                <p class="text-xs text-slate-500">Monthly: <?= number_format((int)($billingSummary['usd_monthly_workspaces'] ?? 0)) ?> · Yearly: <?= number_format((int)($billingSummary['usd_yearly_workspaces'] ?? 0)) ?></p>
            </div>
            <div class="rounded-2xl border border-slate-200 bg-gradient-to-br from-white to-indigo-50 p-4 shadow-sm hover:shadow-md transition-shadow duration-200">
                <p class="text-sm font-semibold text-slate-900">INR Workspaces</p>
                <p class="text-3xl font-semibold text-slate-900 mt-2"><?= number_format($inrWorkspaces) ?></p>
                <p class="text-xs text-slate-500">Monthly: <?= number_format((int)($billingSummary['inr_monthly_workspaces'] ?? 0)) ?> · Yearly: <?= number_format((int)($billingSummary['inr_yearly_workspaces'] ?? 0)) ?></p>
            </div>
            <div class="rounded-2xl border border-slate-200 bg-gradient-to-br from-white to-emerald-50 p-4 shadow-sm hover:shadow-md transition-shadow duration-200">
                <p class="text-sm font-semibold text-slate-900">Subscription Mix</p>
                <p class="text-3xl font-semibold text-slate-900 mt-2"><?= number_format($paidWorkspaces) ?></p>
                <p class="text-xs text-slate-500">Active · <?= number_format($trialWorkspaces) ?> on trial</p>
                <p class="text-[11px] text-slate-400 mt-2">Expiring soon: <?= number_format($expiringSoon) ?></p>
            </div>
        </div>

        <!-- Currency Detail -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 p-6 space-y-4">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-slate-900">USD Native Revenue</p>
                        <p class="text-2xl font-semibold text-slate-900 mt-1">$<?= number_format($usdMonthlyNative, 0) ?><span class="text-sm text-slate-500"> /mo</span></p>
                    </div>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-slate-50 border border-slate-200 text-slate-600">
                        <?= number_format($usdWorkspaces) ?> workspaces
                    </span>
                </div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <p class="text-slate-500">Monthly Plans</p>
                        <p class="text-xl font-semibold text-slate-900 mt-1">$<?= number_format($usdMonthlyNative, 0) ?></p>
                        <div class="mt-2 h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full bg-amber-500" style="width: <?= $usdMonthlyShare ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-1"><?= number_format((int)($billingSummary['usd_monthly_workspaces'] ?? 0)) ?> workspaces</p>
                    </div>
                    <div>
                        <p class="text-slate-500">Yearly Plans</p>
                        <p class="text-xl font-semibold text-slate-900 mt-1">$<?= number_format($usdYearlyNative, 0) ?></p>
                        <div class="mt-2 h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full bg-amber-700" style="width: <?= $usdYearlyShare ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-1"><?= number_format((int)($billingSummary['usd_yearly_workspaces'] ?? 0)) ?> workspaces</p>
                    </div>
                </div>
                <div class="flex flex-wrap gap-3 text-xs text-slate-600">
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-50 border border-slate-200">Conversion to INR: ₹<?= number_format($usdMonthlyNative * $usdToInrRate, 0) ?>/mo</span>
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-50 border border-slate-200">Share: <?= $usdMonthlyShare ?>% monthly · <?= $usdYearlyShare ?>% yearly</span>
                </div>
            </div>

            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 space-y-4">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-slate-900">INR Native Revenue</p>
                        <p class="text-2xl font-semibold text-slate-900 mt-1">₹<?= number_format($inrMonthlyNative, 0) ?><span class="text-sm text-slate-500"> /mo</span></p>
                    </div>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-slate-50 border border-slate-200 text-slate-600">
                        <?= number_format($inrWorkspaces) ?> workspaces
                    </span>
                </div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div>
                        <p class="text-slate-500">Monthly Plans</p>
                        <p class="text-xl font-semibold text-slate-900 mt-1">₹<?= number_format($inrMonthlyNative, 0) ?></p>
                        <div class="mt-2 h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full bg-indigo-500" style="width: <?= $inrMonthlyShare ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-1"><?= number_format((int)($billingSummary['inr_monthly_workspaces'] ?? 0)) ?> workspaces</p>
                    </div>
                    <div>
                        <p class="text-slate-500">Yearly Plans</p>
                        <p class="text-xl font-semibold text-slate-900 mt-1">₹<?= number_format($inrYearlyNative, 0) ?></p>
                        <div class="mt-2 h-2 bg-slate-100 rounded-full overflow-hidden">
                            <div class="h-full bg-indigo-700" style="width: <?= $inrYearlyShare ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-1"><?= number_format((int)($billingSummary['inr_yearly_workspaces'] ?? 0)) ?> workspaces</p>
                    </div>
                </div>
                <div class="flex flex-wrap gap-3 text-xs text-slate-600">
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-50 border border-slate-200">Conversion to USD: $<?= number_format($inrMonthlyNative / $usdToInrRate, 0) ?>/mo</span>
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-50 border border-slate-200">Share: <?= $inrMonthlyShare ?>% monthly · <?= $inrYearlyShare ?>% yearly</span>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 gap-6">
            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 p-6 space-y-4">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-slate-900">Renewal Watch</p>
                        <p class="text-sm text-slate-500">Billing milestones for the next 30 days</p>
                    </div>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-amber-50 border border-amber-100 text-amber-700">
                        <?= number_format($renewalsThisMonth) ?> renewals this month
                    </span>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                    <div class="rounded-xl border border-slate-100 bg-slate-50/70 p-4">
                        <p class="text-slate-500">Renewals this week</p>
                        <p class="text-2xl font-semibold text-slate-900 mt-2"><?= number_format($renewalsThisWeek) ?></p>
                        <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                            <?php $weekRatio = $renewalsThisMonth > 0 ? min(100, (int)round(($renewalsThisWeek / $renewalsThisMonth) * 100)) : 0; ?>
                            <div class="h-full bg-amber-500" style="width: <?= $weekRatio ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-2"><?= $weekRatio ?>% of this month's renewals</p>
                    </div>
                    <div class="rounded-xl border border-slate-100 bg-slate-50/70 p-4">
                        <p class="text-slate-500">Renewals in 30 days</p>
                        <p class="text-2xl font-semibold text-slate-900 mt-2"><?= number_format($renewalsThisMonth) ?></p>
                        <p class="text-[11px] text-slate-500 mt-2">Keep collection queue staffed</p>
                    </div>
                    <div class="rounded-xl border border-slate-100 bg-slate-50/70 p-4">
                        <p class="text-slate-500">Expiring in 7 days</p>
                        <p class="text-2xl font-semibold text-rose-600 mt-2"><?= number_format($expiringSoon) ?></p>
                        <p class="text-[11px] text-slate-500 mt-2">Trigger escalations immediately</p>
                    </div>
                </div>
                <?php if (empty($upcomingRenewals)): ?>
                    <p class="text-slate-400 text-center py-6">No upcoming renewals</p>
                <?php else: ?>
                    <div class="divide-y divide-slate-100 rounded-xl border border-slate-100 bg-slate-50/50">
                        <?php foreach ($upcomingRenewals as $renewal): ?>
                            <div class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
                                <div>
                                    <p class="font-semibold text-slate-900 text-sm"><?= htmlspecialchars($renewal['name']) ?></p>
                                    <p class="text-xs text-slate-500 flex items-center gap-2">
                                        <span><?= htmlspecialchars($renewal['plan_name'] ?? 'No plan') ?></span>
                                        <span>•</span>
                                        <span><?= strtoupper((string)($renewal['preferred_currency'] ?? 'USD')) ?> · <?= ucfirst((string)($renewal['billing_cycle'] ?? 'monthly')) ?></span>
                                    </p>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm font-semibold text-amber-600"><?= date('jS M, y', strtotime($renewal['subscription_expires_at'])) ?></p>
                                    <p class="text-[11px] text-slate-500">in <?= max(1, ceil((strtotime($renewal['subscription_expires_at']) - time()) / 86400)) ?> days</p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 h-full flex flex-col p-6">
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-slate-900 font-semibold">Subscription Status</p>
                        <p class="text-xs text-slate-400">Workspace mix by billing state</p>
                    </div>
                    <span class="inline-flex items-center gap-1 text-xs font-medium text-slate-600 bg-slate-50 border border-slate-200 px-3 py-1 rounded-full">
                        <?= number_format($workspaceStats['total_workspaces'] ?? 0) ?> workspaces
                    </span>
                </div>
                <div class="space-y-3 flex-1">
                    <?php 
                    $statusMeta = [
                        'active' => ['label' => 'Active', 'desc' => 'Paid & current', 'chip' => 'bg-emerald-50 text-emerald-700 border border-emerald-200', 'panel' => 'border border-emerald-100 bg-emerald-50/40', 'bar' => 'bg-emerald-500'],
                        'trial' => ['label' => 'Trial', 'desc' => 'Onboarding window', 'chip' => 'bg-blue-50 text-blue-700 border border-blue-200', 'panel' => 'border border-blue-100 bg-blue-50/40', 'bar' => 'bg-blue-500'],
                        'past_due' => ['label' => 'Past Due', 'desc' => 'Needs follow-up', 'chip' => 'bg-amber-50 text-amber-700 border border-amber-200', 'panel' => 'border border-amber-100 bg-amber-50/40', 'bar' => 'bg-amber-500'],
                        'canceled' => ['label' => 'Canceled', 'desc' => 'Closed accounts', 'chip' => 'bg-rose-50 text-rose-700 border border-rose-200', 'panel' => 'border border-rose-100 bg-rose-50/40', 'bar' => 'bg-rose-500'],
                        'none' => ['label' => 'No Plan', 'desc' => 'Free/legacy', 'chip' => 'bg-slate-50 text-slate-600 border border-slate-200', 'panel' => 'border border-slate-100 bg-slate-50/60', 'bar' => 'bg-slate-400'],
                    ];
                    foreach ($statusBreakdown as $status => $count): 
                        $totalWorkspaces = max(1, (int)($workspaceStats['total_workspaces'] ?? 1));
                        $percentage = $totalWorkspaces > 0 
                            ? round(($count / $totalWorkspaces) * 100) 
                            : 0;
                        $meta = $statusMeta[$status] ?? $statusMeta['none'];
                    ?>
                    <div class="rounded-xl p-4 <?= $meta['panel'] ?>">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-semibold text-slate-900"><?= htmlspecialchars($meta['label']) ?></p>
                                <p class="text-xs text-slate-500"><?= htmlspecialchars($meta['desc']) ?></p>
                            </div>
                            <span class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold <?= $meta['chip'] ?>">
                                <?= number_format($count) ?>
                            </span>
                        </div>
                        <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                            <div class="h-full <?= $meta['bar'] ?>" style="width: <?= $percentage ?>%"></div>
                        </div>
                        <p class="text-[11px] text-slate-500 mt-2"><?= $percentage ?>% of total workspaces</p>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="bg-white rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 p-6 space-y-4">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-semibold text-slate-900">Recent Payments</p>
                        <p class="text-sm text-slate-500">Latest 10 settled invoices</p>
                    </div>
                </div>
                <?php if (empty($recentPayments)): ?>
                    <p class="text-slate-500 text-center py-8">No payment records found</p>
                <?php else: ?>
                    <div class="space-y-2 max-h-72 overflow-y-auto">
                        <?php foreach ($recentPayments as $payment): ?>
                            <?php
                                $currency = strtoupper((string)($payment['currency'] ?? 'USD'));
                                $symbol = $currency === 'INR' ? '₹' : '$';
                            ?>
                            <div class="flex items-center justify-between p-3 bg-slate-50/60 rounded-lg">
                                <div>
                                    <p class="font-medium text-sm text-slate-900"><?= htmlspecialchars($payment['company_name']) ?></p>
                                    <p class="text-xs text-slate-500">
                                        <?= htmlspecialchars($payment['plan_name'] ?? 'Manual charge') ?> · <?= date('jS M, y', strtotime($payment['paid_at'])) ?>
                                    </p>
                                </div>
                                <p class="text-emerald-500 font-semibold">
                                    <?= $symbol ?><?= number_format((float)($payment['amount'] ?? 0), 2) ?>
                                </p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>
</body>
</html>
