<?php
session_start();
require_once dirname(__DIR__) . '/includes/functions.php';

billing_require_auth();

$user = billing_current_user();
$organization = billing_current_organization();

if (!$user) {
    billing_redirect('signin.php');
}

if (!$organization || empty($organization['onboarding_completed_at'])) {
    billing_redirect('onboarding.php?step=1');
}

if (isset($_GET['dismiss_tour'])) {
    $_SESSION['billing_dashboard_tour_dismissed'] = 1;
    http_response_code(204);
    exit;
}

$userId = (int) ($user['id'] ?? 0);
$organizationId = (int) ($organization['id'] ?? 0);
$stats = billing_dashboard_stats($userId);
$customers = billing_get_customers($userId);
$allInvoices = billing_get_invoices($userId, $organizationId);
$expenses = billing_get_expenses($userId, $organizationId);
$projects = billing_get_projects($userId, $organizationId);
$subscriptions = billing_get_subscriptions($userId, $organizationId);

$billingActiveNav = 'home';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');

$customerCount = (int) ($stats['customers'] ?? 0);
$itemCount = (int) ($stats['items'] ?? 0);
$invoiceCount = (int) ($stats['invoices'] ?? 0);
$receivableAmount = (float) ($stats['receivable'] ?? 0);
$revenueAmount = (float) ($stats['revenue'] ?? 0);
$activeSubscriptions = 0;
$draftInvoices = 0;
$paidInvoices = 0;
$recentInvoices = array_slice($allInvoices, 0, 5);
$recentCustomers = array_slice($customers, 0, 5);
$recentProjects = array_slice($projects, 0, 3);
$today = new DateTimeImmutable('today');
$rangeStart = $today->modify('first day of this month')->modify('-11 months');
$monthKeys = [];
$netRevenueSeries = [];
$incomeSeries = [];
$expenseSeries = [];

for ($cursor = $rangeStart; $cursor <= $today; $cursor = $cursor->modify('+1 month')) {
    $key = $cursor->format('Y-m');
    $monthKeys[] = $key;
    $netRevenueSeries[$key] = 0.0;
    $incomeSeries[$key] = 0.0;
    $expenseSeries[$key] = 0.0;
}

$receivableBuckets = [
    'Current' => 0.0,
    '1-15' => 0.0,
    '16-30' => 0.0,
    '31-45' => 0.0,
    '>45' => 0.0,
];

foreach ($subscriptions as $subscription) {
    $status = strtolower((string) ($subscription['status_label'] ?? ''));
    if (in_array($status, ['live', 'active'], true)) {
        $activeSubscriptions++;
    }
}

foreach ($allInvoices as $invoice) {
    $statusLabel = (string) ($invoice['status_label'] ?? '');
    $status = strtolower($statusLabel);
    $totalAmount = (float) ($invoice['total_amount'] ?? 0);
    $invoiceDateRaw = (string) ($invoice['invoice_date'] ?? $invoice['created_at'] ?? '');
    $dueDateRaw = (string) ($invoice['due_date'] ?? '');

    if ($status === 'draft') {
        $draftInvoices++;
    }
    if (in_array($status, ['paid', 'live'], true)) {
        $paidInvoices++;
    }

    if ($invoiceDateRaw !== '') {
        try {
            $invoiceDate = new DateTimeImmutable($invoiceDateRaw);
            $monthKey = $invoiceDate->format('Y-m');
            if (isset($netRevenueSeries[$monthKey]) && in_array($status, ['paid', 'live'], true)) {
                $netRevenueSeries[$monthKey] += $totalAmount;
                $incomeSeries[$monthKey] += $totalAmount;
            }
        } catch (Throwable $exception) {
        }
    }

    if (in_array($status, ['sent', 'overdue'], true)) {
        $bucketKey = 'Current';
        if ($dueDateRaw !== '') {
            try {
                $dueDate = new DateTimeImmutable($dueDateRaw);
                $daysOverdue = (int) $dueDate->diff($today)->format('%r%a');
                if ($daysOverdue <= 0) {
                    $bucketKey = 'Current';
                } elseif ($daysOverdue <= 15) {
                    $bucketKey = '1-15';
                } elseif ($daysOverdue <= 30) {
                    $bucketKey = '16-30';
                } elseif ($daysOverdue <= 45) {
                    $bucketKey = '31-45';
                } else {
                    $bucketKey = '>45';
                }
            } catch (Throwable $exception) {
            }
        }
        $receivableBuckets[$bucketKey] += $totalAmount;
    }
}

$expenseCategoryTotals = [];
foreach ($expenses as $expense) {
    $amount = (float) ($expense['total_amount'] ?? 0);
    $category = trim((string) ($expense['category_name'] ?? 'Others'));
    if ($category === '') {
        $category = 'Others';
    }
    if (!isset($expenseCategoryTotals[$category])) {
        $expenseCategoryTotals[$category] = 0.0;
    }
    $expenseCategoryTotals[$category] += $amount;

    $expenseDateRaw = (string) ($expense['expense_date'] ?? $expense['created_at'] ?? '');
    if ($expenseDateRaw !== '') {
        try {
            $expenseDate = new DateTimeImmutable($expenseDateRaw);
            $monthKey = $expenseDate->format('Y-m');
            if (isset($expenseSeries[$monthKey])) {
                $expenseSeries[$monthKey] += $amount;
            }
        } catch (Throwable $exception) {
        }
    }
}

arsort($expenseCategoryTotals);
$topExpenses = array_slice($expenseCategoryTotals, 0, 6, true);
$topExpenseTotal = array_sum($topExpenses);

$maxRevenue = max($netRevenueSeries ?: [0]);
$maxReceivableBucket = max($receivableBuckets ?: [0]);
$maxIncomeExpense = max(array_merge(array_values($incomeSeries), array_values($expenseSeries), [0]));
$totalExpenseAmount = array_sum($expenseCategoryTotals);
$projectCount = count($projects);
$unbilledHoursTotal = 0.0;
$unbilledExpenseTotal = 0.0;
$projectStatusSummary = [
    'Active' => 0,
    'Completed' => 0,
    'On Hold' => 0,
];

foreach ($projects as $project) {
    $unbilledHoursTotal += ((int) ($project['unbilled_seconds'] ?? 0)) / 3600;
    $unbilledExpenseTotal += max(0, (float) ($project['cost_budget'] ?? 0) - (float) ($project['revenue_budget'] ?? 0));

    $statusLabel = trim((string) ($project['status_label'] ?? 'Active'));
    if (!isset($projectStatusSummary[$statusLabel])) {
        $projectStatusSummary[$statusLabel] = 0;
    }
    $projectStatusSummary[$statusLabel]++;
}

$projectSummaryTotal = max(1, array_sum($projectStatusSummary));
$tab = (string) ($_GET['tab'] ?? 'dashboard');
$tourEnabled = $tab === 'getting-started' && empty($_SESSION['billing_dashboard_tour_dismissed']);
$showDashboardTab = !in_array($tab, ['getting-started', 'recent-updates'], true);

$starterSections = [
    [
        'title' => 'Complete your business profile',
        'open' => true,
        'tasks' => [
            ['label' => 'Review organization details', 'href' => 'settings.php', 'done' => true, 'action' => 'Open Settings'],
            ['label' => 'Create your first customer', 'href' => 'customer_new.php', 'done' => $customerCount > 0, 'action' => 'Add Customer'],
            ['label' => 'Create your first invoice', 'href' => 'invoice_new.php', 'done' => $invoiceCount > 0, 'action' => 'Create Invoice'],
        ],
    ],
    [
        'title' => 'Set up your catalog and workflows',
        'open' => false,
        'tasks' => [
            ['label' => 'Add catalog items', 'href' => 'items.php', 'done' => $itemCount > 0, 'action' => 'Open Items'],
            ['label' => 'Review billing settings', 'href' => 'settings.php', 'done' => false, 'action' => 'Open Settings'],
        ],
    ],
    [
        'title' => 'Track collections and reporting',
        'open' => false,
        'tasks' => [
            ['label' => 'Review receivables', 'href' => 'reports.php', 'done' => $receivableAmount <= 0, 'action' => 'View Reports'],
            ['label' => 'Open dashboard insights', 'href' => 'dashboard.php?tab=dashboard', 'done' => true, 'action' => 'View Dashboard'],
        ],
    ],
];

$recentUpdatesItems = [
    [
        'date' => 'May 2026',
        'badge' => 'Product Update',
        'title' => 'Dashboard tabs were restored and wired back into the billing workspace.',
        'body' => 'You can now switch between Dashboard, Getting Started, and Recent Updates again from the same route without losing the sidebar and topbar experience.',
    ],
    [
        'date' => 'May 2026',
        'badge' => 'Billing',
        'title' => 'Receivables, invoices, expenses, subscriptions, and projects are now summarized in one place.',
        'body' => 'The dashboard uses your live billing data so the overview panels reflect the state of your customers, invoices, expenses, and projects.',
    ],
    [
        'date' => 'May 2026',
        'badge' => 'Workspace',
        'title' => 'Getting Started guidance and support cards are available again for onboarding flow.',
        'body' => 'That brings back the guided setup feel from your earlier restore, including quick actions to configure the workspace and create first records.',
    ],
];

if (!function_exists('billing_dashboard_currency')) {
    function billing_dashboard_currency(float $amount): string
    {
        return 'INR ' . number_format($amount, 2);
    }
}

if (!function_exists('billing_dashboard_month_label')) {
    function billing_dashboard_month_label(string $monthKey): string
    {
        $date = DateTimeImmutable::createFromFormat('Y-m', $monthKey);
        return $date ? $date->format('M Y') : $monthKey;
    }
}

if (!function_exists('billing_dashboard_hours_label')) {
    function billing_dashboard_hours_label(float $hours): string
    {
        $wholeHours = (int) floor($hours);
        $minutes = (int) round(($hours - $wholeHours) * 60);
        if ($minutes === 60) {
            $wholeHours++;
            $minutes = 0;
        }
        return sprintf('%02d:%02d', max(0, $wholeHours), max(0, $minutes));
    }
}

if (!function_exists('billing_dashboard_initials')) {
    function billing_dashboard_initials(string $label): string
    {
        $clean = trim($label);
        if ($clean === '') {
            return 'NA';
        }
        $parts = preg_split('/\s+/', $clean) ?: [];
        $initials = '';
        foreach (array_slice($parts, 0, 2) as $part) {
            $initials .= strtoupper(substr($part, 0, 1));
        }
        return $initials !== '' ? $initials : strtoupper(substr($clean, 0, 2));
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
<title>Billing Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;700;800&display=swap">
<link rel="stylesheet" href="Payslip_Project/assets/fontawesome/css/all.min.css">
<link rel="stylesheet" href="assets/billing.css?v=20260507-zoho-dashboard">
</head>
<body class="billing-dashboard-page">
<div class="dashboard-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content">
            <section class="zoho-dashboard">
                <header class="zoho-dashboard-hero">
                    <div class="zoho-dashboard-hero-main">
                        <div class="zoho-dashboard-greeting">
                            <span class="zoho-dashboard-avatar"><i class="fa-regular fa-id-badge"></i></span>
                            <div>
                                <h1>Hello, <?php echo billing_escape((string) ($user['business_name'] ?? $user['email'] ?? 'User')); ?></h1>
                                <p><?php echo billing_escape((string) ($organization['organization_name'] ?? 'Your organization')); ?></p>
                            </div>
                        </div>

                        <nav class="zoho-dashboard-tabs" aria-label="Dashboard Sections">
                            <a class="<?php echo $tab === 'dashboard' ? 'is-active' : ''; ?>" href="dashboard.php?tab=dashboard">Dashboard</a>
                            <a class="<?php echo $tab === 'getting-started' ? 'is-active' : ''; ?>" href="dashboard.php?tab=getting-started">Getting Started</a>
                            <a class="<?php echo $tab === 'recent-updates' ? 'is-active' : ''; ?>" href="dashboard.php?tab=recent-updates">Recent Updates</a>
                        </nav>
                    </div>

                    <div class="zoho-dashboard-support">
                        <strong>b2lmobitech Billing India Helpline</strong>
                        <span>18005692881</span>
                        <small>Mon - Fri | 9:00 AM - 7:00 PM | Toll Free</small>
                    </div>
                </header>

                <section class="zoho-dashboard-banner">
                    <div class="zoho-dashboard-banner-visual">
                        <div class="zoho-dashboard-banner-badge">2026</div>
                    </div>
                    <div class="zoho-dashboard-banner-copy">
                        <h2>Finance and operations are ready to scale</h2>
                        <p>Your workspace now brings invoices, expenses, projects, receivables, and customer activity into one overview similar to the Zoho billing experience you shared.</p>
                        <div class="zoho-dashboard-banner-tags">
                            <span><i class="fa-solid fa-location-dot"></i> Customers</span>
                            <span><i class="fa-solid fa-location-dot"></i> Invoices</span>
                            <span><i class="fa-solid fa-location-dot"></i> Expenses</span>
                            <span><i class="fa-solid fa-location-dot"></i> Projects</span>
                        </div>
                    </div>
                    <div class="zoho-dashboard-banner-action">
                        <a href="invoice_new.php">Create Invoice</a>
                    </div>
                </section>

                <div class="zoho-dashboard-filterbar">
                    <span>Date Range</span>
                    <button type="button">Last 12 months <i class="fa-solid fa-angle-down"></i></button>
                </div>
                <?php if ($showDashboardTab): ?>
                <section class="zoho-dashboard-top-grid">
                    <article class="zoho-panel zoho-panel--chart">
                        <div class="zoho-panel-head">
                            <h2>Net Revenue</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-big-number"><?php echo billing_escape(billing_dashboard_currency($revenueAmount)); ?></div>
                        <div class="zoho-muted-meta"><span class="zoho-chip">0%</span><span>Year On Year</span></div>
                        <div class="zoho-chart-bars">
                            <?php foreach ($netRevenueSeries as $monthKey => $amount): ?>
                                <?php $height = $maxRevenue > 0 ? max(6, (int) round(($amount / $maxRevenue) * 100)) : 6; ?>
                                <div class="zoho-bar-group">
                                    <div class="zoho-bar-track">
                                        <span class="zoho-bar zoho-bar--green" style="height: <?php echo $height; ?>%;" title="<?php echo billing_escape(billing_dashboard_month_label($monthKey) . ': ' . billing_dashboard_currency($amount)); ?>"></span>
                                    </div>
                                    <small><?php echo billing_escape(date('M', strtotime($monthKey . '-01'))); ?><br><?php echo billing_escape(date('Y', strtotime($monthKey . '-01'))); ?></small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </article>

                    <article class="zoho-panel zoho-panel--chart">
                        <div class="zoho-panel-head">
                            <h2>Receivable Summary</h2>
                            <span><?php echo billing_escape(billing_dashboard_currency($receivableAmount)); ?></span>
                        </div>
                        <div class="zoho-receivable-meta">
                            <div>
                                <span>Total Receivables</span>
                                <strong><?php echo billing_escape(billing_dashboard_currency($receivableAmount)); ?></strong>
                            </div>
                            <div class="zoho-receivable-legend">
                                <?php foreach ($receivableBuckets as $bucket => $amount): ?>
                                    <div><i></i><span><?php echo billing_escape($bucket); ?></span><strong><?php echo billing_escape(billing_dashboard_currency($amount)); ?></strong></div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="zoho-chart-bars zoho-chart-bars--receivable">
                            <?php foreach ($receivableBuckets as $bucket => $amount): ?>
                                <?php $height = $maxReceivableBucket > 0 ? max(6, (int) round(($amount / $maxReceivableBucket) * 100)) : 6; ?>
                                <div class="zoho-bar-group">
                                    <div class="zoho-bar-track">
                                        <span class="zoho-bar zoho-bar--amber" style="height: <?php echo $height; ?>%;" title="<?php echo billing_escape($bucket . ': ' . billing_dashboard_currency($amount)); ?>"></span>
                                    </div>
                                    <small><?php echo billing_escape($bucket); ?></small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </article>
                </section>

                <section class="zoho-dashboard-mini-grid">
                    <article class="zoho-panel zoho-panel--mini">
                        <div class="zoho-panel-head">
                            <h2>MRR</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-big-number"><?php echo billing_escape(billing_dashboard_currency($activeSubscriptions > 0 ? $revenueAmount / max(1, $activeSubscriptions) : 0)); ?></div>
                        <div class="zoho-muted-meta"><span class="zoho-chip">0%</span><span>Year On Year</span></div>
                    </article>

                    <article class="zoho-panel zoho-panel--mini">
                        <div class="zoho-panel-head">
                            <h2>Active Subscriptions</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-big-number"><?php echo $activeSubscriptions; ?></div>
                        <div class="zoho-muted-meta"><span class="zoho-chip">0%</span><span>Year On Year</span></div>
                    </article>

                    <article class="zoho-panel zoho-panel--mini">
                        <div class="zoho-panel-head">
                            <h2>ARPU</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-big-number"><?php echo billing_escape(billing_dashboard_currency($customerCount > 0 ? $revenueAmount / $customerCount : 0)); ?></div>
                        <div class="zoho-muted-meta"><span class="zoho-chip">0%</span><span>Year On Year</span></div>
                    </article>

                    <article class="zoho-panel zoho-panel--mini">
                        <div class="zoho-panel-head">
                            <h2>Churn Rate</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-big-number">0.00%</div>
                        <div class="zoho-muted-meta"><span class="zoho-chip">0%</span><span>On <?php echo billing_escape($today->format('M Y')); ?></span></div>
                    </article>
                </section>

                <section class="zoho-panel">
                    <div class="zoho-panel-head">
                        <h2>Business Summary</h2>
                        <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                    </div>
                    <div class="zoho-summary-stats">
                        <div><i class="fa-solid fa-user-plus"></i><span>Customers</span><strong><?php echo $customerCount; ?></strong></div>
                        <div><i class="fa-solid fa-file-invoice"></i><span>Invoices</span><strong><?php echo $invoiceCount; ?></strong></div>
                        <div><i class="fa-solid fa-circle-check"></i><span>Paid</span><strong><?php echo $paidInvoices; ?></strong></div>
                        <div><i class="fa-solid fa-file-pen"></i><span>Draft</span><strong><?php echo $draftInvoices; ?></strong></div>
                    </div>
                    <div class="zoho-summary-line">
                        <?php foreach ($monthKeys as $monthKey): ?>
                            <span title="<?php echo billing_escape(billing_dashboard_month_label($monthKey)); ?>"></span>
                        <?php endforeach; ?>
                    </div>
                </section>

                <section class="zoho-dashboard-middle-grid">
                    <article class="zoho-panel zoho-panel--chart">
                        <div class="zoho-panel-head">
                            <h2>Income and Expense</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-income-legend">
                            <div><i class="is-income"></i><span>Total Income</span><strong><?php echo billing_escape(billing_dashboard_currency(array_sum($incomeSeries))); ?></strong></div>
                            <div><i class="is-receipts"></i><span>Total Receipts</span><strong><?php echo billing_escape(billing_dashboard_currency($revenueAmount)); ?></strong></div>
                            <div><i class="is-expense"></i><span>Total Expenses</span><strong><?php echo billing_escape(billing_dashboard_currency($totalExpenseAmount)); ?></strong></div>
                        </div>
                        <div class="zoho-mixed-chart">
                            <?php foreach ($monthKeys as $monthKey): ?>
                                <?php
                                $incomeHeight = $maxIncomeExpense > 0 ? max(4, (int) round((($incomeSeries[$monthKey] ?? 0) / $maxIncomeExpense) * 100)) : 4;
                                $expenseHeight = $maxIncomeExpense > 0 ? max(4, (int) round((($expenseSeries[$monthKey] ?? 0) / $maxIncomeExpense) * 100)) : 4;
                                ?>
                                <div class="zoho-mixed-group">
                                    <div class="zoho-bar-track">
                                        <span class="zoho-bar zoho-bar--green" style="height: <?php echo $incomeHeight; ?>%;"></span>
                                        <span class="zoho-bar zoho-bar--amber" style="height: <?php echo $expenseHeight; ?>%;"></span>
                                    </div>
                                    <small><?php echo billing_escape(date('M', strtotime($monthKey . '-01'))); ?><br><?php echo billing_escape(date('Y', strtotime($monthKey . '-01'))); ?></small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </article>

                    <article class="zoho-panel">
                        <div class="zoho-panel-head">
                            <h2>Top Expenses</h2>
                            <span>Last 12 months <i class="fa-solid fa-angle-down"></i></span>
                        </div>
                        <div class="zoho-expense-donut-wrap">
                            <div class="zoho-expense-donut">
                                <div>
                                    <span>All Expenses</span>
                                    <strong><?php echo billing_escape(billing_dashboard_currency($topExpenseTotal)); ?></strong>
                                </div>
                            </div>
                            <div class="zoho-expense-list">
                                <?php if ($topExpenses === []): ?>
                                    <div class="zoho-empty-state">No expense records found.</div>
                                <?php else: ?>
                                    <?php $expenseIndex = 0; ?>
                                    <?php foreach ($topExpenses as $label => $amount): ?>
                                        <div>
                                            <span class="zoho-expense-dot zoho-expense-dot--<?php echo $expenseIndex % 6; ?>"></span>
                                            <b><?php echo billing_escape($label); ?></b>
                                            <strong><?php echo billing_escape(billing_dashboard_currency($amount)); ?></strong>
                                        </div>
                                        <?php $expenseIndex++; ?>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </article>
                </section>

                <section class="zoho-dashboard-project-grid">
                    <article class="zoho-panel">
                        <div class="zoho-panel-head">
                            <h2>Projects</h2>
                            <a href="projects.php">Show All Projects <i class="fa-solid fa-angle-right"></i></a>
                        </div>
                        <div class="zoho-project-stats">
                            <div>
                                <span>Unbilled Hours</span>
                                <strong><?php echo billing_escape(billing_dashboard_hours_label($unbilledHoursTotal)); ?></strong>
                            </div>
                            <div>
                                <span>Unbilled Expenses</span>
                                <strong><?php echo billing_escape(billing_dashboard_currency(max(0, $unbilledExpenseTotal))); ?></strong>
                            </div>
                        </div>
                        <div class="zoho-project-list">
                            <?php if ($recentProjects === []): ?>
                                <div class="zoho-empty-state">No projects yet. <a href="projects.php">Open projects</a>.</div>
                            <?php else: ?>
                                <?php foreach ($recentProjects as $project): ?>
                                    <?php
                                    $projectName = (string) ($project['project_name'] ?? 'Project');
                                    $customerName = (string) ($project['customer_name'] ?? 'No customer');
                                    $loggedSeconds = (int) ($project['logged_seconds'] ?? 0);
                                    $unbilledSeconds = (int) ($project['unbilled_seconds'] ?? 0);
                                    $completion = $loggedSeconds > 0 ? min(100, (int) round(($unbilledSeconds / $loggedSeconds) * 100)) : 0;
                                    ?>
                                    <div class="zoho-project-item">
                                        <div class="zoho-project-ring"><?php echo $completion; ?>%</div>
                                        <div class="zoho-project-copy">
                                            <strong><?php echo billing_escape($projectName); ?></strong>
                                            <span><?php echo billing_escape($customerName); ?></span>
                                        </div>
                                        <div class="zoho-project-budget"><?php echo billing_escape(billing_dashboard_hours_label($unbilledSeconds / 3600)); ?></div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </article>

                    <article class="zoho-panel">
                        <div class="zoho-panel-head">
                            <h2>Workspace Snapshot</h2>
                            <span>Live view</span>
                        </div>
                        <div class="zoho-snapshot-grid">
                            <div><span>Customers</span><strong><?php echo $customerCount; ?></strong></div>
                            <div><span>Items</span><strong><?php echo $itemCount; ?></strong></div>
                            <div><span>Invoices</span><strong><?php echo $invoiceCount; ?></strong></div>
                            <div><span>Projects</span><strong><?php echo $projectCount; ?></strong></div>
                        </div>
                        <div class="zoho-status-breakdown">
                            <?php foreach ($projectStatusSummary as $label => $count): ?>
                                <div>
                                    <span><?php echo billing_escape($label); ?></span>
                                    <strong><?php echo $count; ?></strong>
                                    <small><?php echo (int) round(($count / $projectSummaryTotal) * 100); ?>% of projects</small>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </article>
                </section>

                <section class="zoho-dashboard-bottom-grid">
                    <article class="zoho-panel">
                        <div class="zoho-panel-head">
                            <h2>Recent Customers</h2>
                            <a href="customers.php">View all</a>
                        </div>
                        <div class="zoho-list">
                            <?php if ($recentCustomers === []): ?>
                                <div class="zoho-empty-state">No customers yet. <a href="customer_new.php">Create your first customer</a>.</div>
                            <?php else: ?>
                                <?php foreach ($recentCustomers as $customer): ?>
                                    <div class="zoho-list-row">
                                        <div class="zoho-list-avatar"><?php echo billing_escape(billing_dashboard_initials((string) ($customer['customer_name'] ?? ''))); ?></div>
                                        <div class="zoho-list-copy">
                                            <strong><?php echo billing_escape((string) ($customer['customer_name'] ?? '')); ?></strong>
                                            <span><?php echo billing_escape((string) ($customer['email'] ?? 'No email')); ?></span>
                                        </div>
                                        <div class="zoho-list-metric">
                                            <span><?php echo billing_escape((string) ($customer['status_label'] ?? 'Active')); ?></span>
                                            <strong><?php echo billing_escape(billing_dashboard_currency((float) ($customer['outstanding_amount'] ?? 0))); ?></strong>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </article>

                    <article class="zoho-panel">
                        <div class="zoho-panel-head">
                            <h2>Recent Invoices</h2>
                            <a href="invoices.php">View all</a>
                        </div>
                        <div class="zoho-list">
                            <?php if ($recentInvoices === []): ?>
                                <div class="zoho-empty-state">No invoices yet. <a href="invoice_new.php">Create invoice</a>.</div>
                            <?php else: ?>
                                <?php foreach ($recentInvoices as $invoice): ?>
                                    <div class="zoho-list-row">
                                        <div class="zoho-list-avatar"><i class="fa-solid fa-file-invoice"></i></div>
                                        <div class="zoho-list-copy">
                                            <strong><?php echo billing_escape((string) ($invoice['invoice_number'] ?? '')); ?></strong>
                                            <span><?php echo billing_escape((string) ($invoice['customer_name'] ?? '')); ?></span>
                                        </div>
                                        <div class="zoho-list-metric">
                                            <span><?php echo billing_escape((string) ($invoice['status_label'] ?? 'Draft')); ?></span>
                                            <strong><?php echo billing_escape(billing_dashboard_currency((float) ($invoice['total_amount'] ?? 0))); ?></strong>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </article>
                </section>

                <footer class="zoho-dashboard-footer">
                    <div class="zoho-footer-card zoho-footer-card--promo">
                        <h3>Manage billing on the move</h3>
                        <p>Create sales transactions, view key metrics, and receive important business notifications from anywhere.</p>
                        <div class="zoho-mobile-visual">
                            <div class="zoho-mobile-phone"></div>
                            <div class="zoho-mobile-qr">
                                <span>Scan to Download</span>
                                <i class="fa-solid fa-qrcode"></i>
                            </div>
                        </div>
                    </div>

                    <div class="zoho-footer-card">
                        <h4>Other b2lmobitech Apps</h4>
                        <a href="#">Accounting Software</a>
                        <a href="#">Ecommerce Software</a>
                        <a href="#">Expense Reporting</a>
                        <a href="#">Inventory Management</a>
                        <a href="#">CRM &amp; Other Apps</a>
                    </div>

                    <div class="zoho-footer-card">
                        <h4>Help &amp; Support</h4>
                        <a href="#">Contact Support</a>
                        <a href="#">FAQ</a>
                        <a href="#">Help Documentation</a>
                    </div>

                    <div class="zoho-footer-card">
                        <h4>Quick Links</h4>
                        <a href="#">Integrations</a>
                        <a href="#">Developers API</a>
                        <a href="#">Blog</a>
                        <a href="#">Forum</a>
                    </div>
                </footer>
                <?php elseif ($tab === 'getting-started'): ?>
                <section class="starter-shell" data-tour-root data-tour-enabled="<?php echo $tourEnabled ? '1' : '0'; ?>">
                    <div class="starter-head">
                        <div>
                            <h2>Getting started with your billing workspace</h2>
                            <p>Set up customers, items, invoices, and collections using the same guided experience you had in the morning restore.</p>
                        </div>
                        <a class="billing-dashboard-primary" href="dashboard.php?tab=dashboard">Go to Dashboard</a>
                    </div>

                    <div class="starter-list">
                        <?php foreach ($starterSections as $index => $section): ?>
                            <details class="starter-item <?php echo $section['open'] ? 'starter-item--open' : ''; ?>" <?php echo $section['open'] ? 'open' : ''; ?>>
                                <summary>
                                    <span class="starter-index"><?php echo $index + 1; ?></span>
                                    <span><?php echo billing_escape($section['title']); ?></span>
                                    <i class="fa-solid fa-angle-down"></i>
                                </summary>
                                <div class="starter-tasks">
                                    <?php foreach ($section['tasks'] as $task): ?>
                                        <div class="starter-task">
                                            <span>
                                                <i class="fa-solid <?php echo $task['done'] ? 'fa-circle-check done' : 'fa-circle-dot pending'; ?>"></i>
                                                <?php echo billing_escape($task['label']); ?>
                                            </span>
                                            <a href="<?php echo billing_escape($task['href']); ?>"><?php echo billing_escape($task['action']); ?></a>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </details>
                        <?php endforeach; ?>
                    </div>
                </section>

                <section class="starter-feature-panel">
                    <div class="starter-feature-copy">
                        <h3>Key areas to finish first</h3>
                        <p>Use these shortcuts to complete setup and start billing quickly.</p>
                    </div>
                    <div class="starter-feature-grid">
                        <a class="starter-feature-card" href="customer_new.php"><i class="fa-regular fa-user"></i><span>Create customer</span></a>
                        <a class="starter-feature-card" href="invoice_new.php"><i class="fa-solid fa-file-invoice"></i><span>Send invoice</span></a>
                        <a class="starter-feature-card" href="items.php"><i class="fa-solid fa-box-open"></i><span>Build catalog</span></a>
                    </div>

                    <h3 class="starter-resources-title">Helpful resources</h3>
                    <div class="starter-resources-grid">
                        <article class="resource-box resource-box--video">
                            <div class="resource-video-copy">
                                <h3>Start billing in a few minutes</h3>
                                <p>Open the key modules, add your first customer, and create your first invoice from the current workspace.</p>
                                <a href="dashboard.php?tab=dashboard"><i class="fa-solid fa-circle-play"></i> View dashboard</a>
                            </div>
                            <div class="resource-video-art">
                                <div class="resource-video-blob"></div>
                                <div class="resource-video-figure">
                                    <span class="resource-figure-head"></span>
                                    <span class="resource-figure-body"></span>
                                    <span class="resource-figure-laptop"></span>
                                </div>
                            </div>
                        </article>

                        <article class="resource-box resource-box--help">
                            <h3>Need help?</h3>
                            <p>Jump to the most important sections and finish the setup flow without leaving the app.</p>
                            <div class="resource-links">
                                <a href="settings.php"><i class="fa-solid fa-gear"></i><span>Organization settings</span><i class="fa-solid fa-angle-right"></i></a>
                                <a href="reports.php"><i class="fa-solid fa-chart-column"></i><span>Billing reports</span><i class="fa-solid fa-angle-right"></i></a>
                                <a href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span><i class="fa-solid fa-angle-right"></i></a>
                            </div>
                        </article>
                    </div>
                </section>

                <div class="tour-overlay" data-tour-overlay></div>
                <div class="tour-card" data-tour-card>
                    <div class="tour-step" data-tour-step>1 / 7</div>
                    <div class="tour-illustration"></div>
                    <h3 data-tour-title>Keep tabs on everything</h3>
                    <p data-tour-body>View key metrics from the dashboard, set up your organization from Getting Started, or catch up on recent updates.</p>
                    <div class="tour-actions">
                        <button class="tour-btn skip" type="button" data-tour-skip>Skip</button>
                        <div class="tour-actions-right">
                            <button class="tour-btn secondary" type="button" data-tour-prev>Previous</button>
                            <button class="tour-btn" type="button" data-tour-next>Next</button>
                        </div>
                    </div>
                </div>
                <?php elseif ($tab === 'recent-updates'): ?>
                <section class="updates-layout">
                    <div class="panel">
                        <div class="panel-header">
                            <h2>Recent Updates</h2>
                            <p class="panel-subtitle">Latest billing workspace improvements and restored dashboard updates.</p>
                        </div>
                        <div class="checklist-wrap">
                            <div class="updates-timeline">
                                <?php foreach ($recentUpdatesItems as $item): ?>
                                    <article class="update-item">
                                        <span class="update-marker"></span>
                                        <div class="update-copy">
                                            <div class="update-date"><?php echo billing_escape($item['date']); ?> <span class="update-badge"><?php echo billing_escape($item['badge']); ?></span></div>
                                            <h2><?php echo billing_escape($item['title']); ?></h2>
                                            <p><?php echo billing_escape($item['body']); ?></p>
                                        </div>
                                    </article>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <aside class="updates-sidebar">
                        <article class="updates-side-card">
                            <div class="updates-side-hero"></div>
                            <span class="updates-side-label">WHAT'S NEW</span>
                            <h3>Dashboard sections are visible again from the restored route.</h3>
                            <p>Use Dashboard for metrics, Getting Started for setup guidance, and Recent Updates for the latest changes.</p>
                            <div class="updates-side-actions">
                                <a href="dashboard.php?tab=dashboard">Open Dashboard</a>
                                <a href="dashboard.php?tab=getting-started">Getting Started</a>
                            </div>
                        </article>

                        <article class="updates-side-card updates-side-card--soft">
                            <span class="updates-side-label updates-side-label--red">NEXT STEPS</span>
                            <h3>Continue configuring your billing workspace</h3>
                            <p>Create customers, catalog items, invoices, and reports using the quick links already available in the sidebar and topbar.</p>
                        </article>
                    </aside>
                </section>
                <?php endif; ?>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js?v=20260507-zoho-dashboard"></script>
</body>
</html>
