<?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');
}

$stats = billing_dashboard_stats((int) $user['id']);
$expenses = billing_get_expenses((int) $user['id'], (int) $organization['id']);
$timeEntries = billing_get_project_time_entries((int) $user['id'], (int) $organization['id']);
$subscriptions = billing_fetch_all(
    'SELECT plan_name, status_label, total_amount, created_at, updated_at FROM subscriptions WHERE user_id = ? AND organization_id = ? AND COALESCE(is_deleted, 0) = 0 ORDER BY id DESC',
    'ii',
    [(int) $user['id'], (int) $organization['id']]
);

$expenseTotal = 0.0;
foreach ($expenses as $expense) {
    $expenseTotal += (float) ($expense['total_amount'] ?? 0);
}

$hoursTotal = 0;
foreach ($timeEntries as $entry) {
    $hoursTotal += (int) ($entry['duration_seconds'] ?? 0);
}

$activeSubscriptions = 0;
foreach ($subscriptions as $subscription) {
    if (in_array((string) ($subscription['status_label'] ?? ''), ['Live', 'Active'], true)) {
        $activeSubscriptions++;
    }
}

$reportGroups = [
    'Home',
    'Favorites',
    'Shared Reports',
    'My Reports',
    'Scheduled Reports',
];

$reportCategories = [
    'Sales',
    'Receivables',
    'Acquisition Insights',
    'Signups & Activations',
    'Subscriptions',
    'Revenue',
    'Retention',
    'MRR & ARR',
];

$reportRows = [
    ['name' => 'Sales by Customer', 'category' => 'Sales', 'created_by' => 'System Generated', 'visited' => '06/05/2026 09:44 AM'],
    ['name' => 'Sales by Item', 'category' => 'Sales', 'created_by' => 'System Generated', 'visited' => '06/05/2026 09:44 AM'],
    ['name' => 'Sales Summary', 'category' => 'Sales', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'Receivables Summary', 'category' => 'Receivables', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'AR Aging Summary', 'category' => 'Receivables', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'Expense Summary', 'category' => 'Revenue', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'Customer Growth', 'category' => 'Acquisition Insights', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'Subscription Growth', 'category' => 'Signups & Activations', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'Active Subscription Overview', 'category' => 'Subscriptions', 'created_by' => 'System Generated', 'visited' => '-'],
    ['name' => 'MRR Snapshot', 'category' => 'MRR & ARR', 'created_by' => 'System Generated', 'visited' => '-'],
];

$dynamicReports = [
    ['name' => 'Revenue Overview', 'category' => 'Revenue', 'created_by' => 'System Generated', 'visited' => number_format((float) ($stats['revenue'] ?? 0), 2)],
    ['name' => 'Receivable Overview', 'category' => 'Receivables', 'created_by' => 'System Generated', 'visited' => number_format((float) ($stats['receivable'] ?? 0), 2)],
    ['name' => 'Expense Overview', 'category' => 'Revenue', 'created_by' => 'System Generated', 'visited' => number_format($expenseTotal, 2)],
    ['name' => 'Tracked Hours Overview', 'category' => 'Revenue', 'created_by' => 'System Generated', 'visited' => number_format($hoursTotal / 3600, 2) . ' hrs'],
    ['name' => 'Active Subscription Overview', 'category' => 'Subscriptions', 'created_by' => 'System Generated', 'visited' => (string) $activeSubscriptions],
];

foreach ($dynamicReports as $row) {
    $reportRows[] = $row;
}

$billingActiveNav = 'reports';
$billingTopbarOrganizationName = (string) ($organization['organization_name'] ?? 'Billing');
$billingTopbarUserLabel = (string) ($user['email'] ?? '');
?>
<!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>Reports</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-layout-fix-2">
</head>
<body class="billing-reports-page">
<div class="dashboard-shell customer-shell">
    <?php include dirname(__DIR__) . '/includes/app_sidebar.php'; ?>
    <div class="dashboard-main customer-main">
        <?php include dirname(__DIR__) . '/includes/topbar.php'; ?>
        <main class="dashboard-content billing-app-page">
            <div class="billing-maintenance-strip">
                <span>Planned India Data Center Maintenance on 10th May 2026 and 17th May 2026, between 06.30AM to 09.30AM IST.</span>
                <a href="reports.php">Know more</a>
            </div>

            <section class="app-screen app-screen--reports">
                <div class="app-reports-hero">
                    <h1>Reports Center</h1>
                    <label class="app-report-search">
                        <i class="fa-solid fa-magnifying-glass"></i>
                        <input type="search" placeholder="Search reports" data-report-search>
                    </label>
                    <div class="app-report-actions">
                        <a class="app-primary-btn" href="#">Create Custom Report</a>
                        <button class="app-icon-btn" type="button" aria-label="More actions">
                            <i class="fa-solid fa-ellipsis-vertical"></i>
                        </button>
                    </div>
                </div>

                <div class="app-reports-surface">
                    <aside class="app-report-sidebar">
                        <nav class="app-report-home-nav">
                            <?php foreach ($reportGroups as $index => $group): ?>
                                <button class="app-report-nav-item<?php echo $index === 0 ? ' is-active' : ''; ?>" type="button">
                                    <i class="fa-regular <?php echo $index === 0 ? 'fa-house' : ($index === 1 ? 'fa-star' : ($index === 2 ? 'fa-share-nodes' : ($index === 3 ? 'fa-user' : 'fa-clock'))); ?>"></i>
                                    <span><?php echo billing_escape($group); ?></span>
                                </button>
                            <?php endforeach; ?>
                        </nav>

                        <div class="app-report-side-title">REPORT CATEGORY</div>
                        <div class="app-report-category-list">
                            <?php foreach ($reportCategories as $category): ?>
                                <button class="app-report-category" type="button" data-report-category="<?php echo billing_escape($category); ?>">
                                    <i class="fa-regular fa-folder"></i>
                                    <span><?php echo billing_escape($category); ?></span>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    </aside>

                    <section class="app-report-list-card">
                        <div class="app-report-list-head">
                            <h2>All Reports <span><?php echo count($reportRows); ?></span></h2>
                        </div>
                        <div class="app-table-wrap">
                            <table class="app-table app-table--reports">
                                <thead>
                                    <tr>
                                        <th>REPORT NAME</th>
                                        <th>REPORT CATEGORY</th>
                                        <th>CREATED BY</th>
                                        <th>LAST VISITED</th>
                                    </tr>
                                </thead>
                                <tbody data-report-list>
                                    <?php foreach ($reportRows as $report): ?>
                                        <tr data-report-name="<?php echo billing_escape(strtolower($report['name'])); ?>" data-report-category="<?php echo billing_escape($report['category']); ?>">
                                            <td><a class="app-report-link" href="#"><?php echo billing_escape($report['name']); ?></a></td>
                                            <td><?php echo billing_escape($report['category']); ?></td>
                                            <td><?php echo billing_escape($report['created_by']); ?></td>
                                            <td><?php echo billing_escape($report['visited']); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </section>
                </div>
            </section>
        </main>
    </div>
</div>
<script src="assets/billing.js?v=20260507-layout-fix-2"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var search = document.querySelector('[data-report-search]');
    var rows = Array.from(document.querySelectorAll('[data-report-list] tr'));
    var categories = Array.from(document.querySelectorAll('[data-report-category]'));
    var activeCategory = '';

    function applyFilter() {
        var query = search ? search.value.trim().toLowerCase() : '';
        rows.forEach(function (row) {
            var name = row.getAttribute('data-report-name') || '';
            var category = row.getAttribute('data-report-category') || '';
            var matchesQuery = query === '' || name.indexOf(query) !== -1;
            var matchesCategory = activeCategory === '' || category === activeCategory;
            row.hidden = !(matchesQuery && matchesCategory);
        });
    }

    if (search) {
        search.addEventListener('input', applyFilter);
    }

    categories.forEach(function (button) {
        button.addEventListener('click', function () {
            activeCategory = activeCategory === button.getAttribute('data-report-category') ? '' : (button.getAttribute('data-report-category') || '');
            categories.forEach(function (item) {
                item.classList.toggle('is-active', item === button && activeCategory !== '');
            });
            applyFilter();
        });
    });
});
</script>
</body>
</html>
