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

$reportTemplates = [
    'sales_by_customer' => [
        'name' => 'Sales by Customer',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '06/05/2026 09:44 AM',
        'entities_label' => 'All',
        'default_export_name' => 'Sales by Customer',
        'columns' => [
            'Name',
            'Invoice Count',
            'Sales',
            'Sales With Tax',
        ],
        'available_columns' => [
            'CN Count',
            'Journal Count',
            'Sales Deposit Count',
            'Sales Without Discount',
            'Sales(FCY)',
            'Sales With Tax(FCY)',
            'Sales Without Discount (FCY)',
            'Invoice Amount',
            'Invoice Amount (FCY)',
            'Credit Note Amount',
            'Credit Note Amount (FCY)',
            'Currency',
        ],
    ],
    'sales_by_item' => [
        'name' => 'Sales by Item',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '06/05/2026 09:44 AM',
    ],
    'sales_by_plan' => [
        'name' => 'Sales by Plan',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '-',
    ],
    'sales_by_addon' => [
        'name' => 'Sales by Addon',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '-',
    ],
    'sales_by_coupon' => [
        'name' => 'Sales by Coupon',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '-',
    ],
    'sales_by_sales_person' => [
        'name' => 'Sales by Sales Person',
        'category' => 'Sales',
        'created_by' => 'System Generated',
        'visited' => '-',
    ],
];

if (!isset($_SESSION['billing_custom_reports']) || !is_array($_SESSION['billing_custom_reports'])) {
    $_SESSION['billing_custom_reports'] = [
        [
            'id' => 1,
            'template' => 'sales_by_customer',
            'name' => 'gr',
            'export_name' => 'Sales by Customer',
            'description' => '',
            'category' => 'Sales',
            'created_by' => 'balachandar k',
            'created_meta' => 'On 06/05/2026 09:41 AM',
            'visited' => '06/05/2026 09:42 AM',
            'shared_with' => 'Only Me',
            'date_range' => 'Today',
            'compare_with' => 'None',
            'entities' => 'All',
            'selected_columns' => ['Name', 'Invoice Count', 'Sales', 'Sales With Tax'],
            'available_columns' => $reportTemplates['sales_by_customer']['available_columns'],
            'layout' => [
                'show_organization_name' => 1,
                'show_organization_details' => 0,
                'show_page_number' => 0,
                'show_generated_by' => 0,
                'show_generated_date' => 0,
                'show_generated_time' => 0,
                'table_density' => 'Classic',
                'table_design' => 'Default',
                'auto_resize' => 1,
                'paper_size' => 'A4',
                'orientation' => 'Portrait',
                'font_family' => 'Ubuntu',
                'margin_top' => '0.7',
                'margin_bottom' => '0.7',
                'margin_left' => '0.55',
                'margin_right' => '0.2',
            ],
            'activity' => [
                ['actor' => 'balachandar k', 'time' => '09/05/2026 06:14 PM', 'message' => 'Custom Report created.'],
            ],
        ],
    ];
}

if (!isset($_SESSION['billing_report_draft']) || !is_array($_SESSION['billing_report_draft'])) {
    $_SESSION['billing_report_draft'] = [];
}

$reportCategories = [
    ['slug' => 'sales', 'label' => 'Sales'],
    ['slug' => 'receivables', 'label' => 'Receivables'],
    ['slug' => 'acquisition_insights', 'label' => 'Acquisition Insights'],
    ['slug' => 'signups_activations', 'label' => 'Signups & Activations'],
    ['slug' => 'subscriptions', 'label' => 'Subscriptions'],
    ['slug' => 'revenue', 'label' => 'Revenue'],
    ['slug' => 'retention', 'label' => 'Retention'],
    ['slug' => 'mrr_arr', 'label' => 'MRR & ARR'],
];

$systemCategoryReports = [
    'sales' => ['sales_by_customer', 'sales_by_item', 'sales_by_plan', 'sales_by_addon', 'sales_by_coupon', 'sales_by_sales_person'],
    'receivables' => ['AR Aging Summary', 'AR Aging Details', 'Invoice Details'],
    'acquisition_insights' => ['Active Trials', 'Inactive Trials', 'Trial to Live Conversions'],
    'signups_activations' => ['Signups', 'Activations', 'Activations By Country'],
    'subscriptions' => ['Active Subscriptions', 'Net Customers', 'Subscription Details'],
    'revenue' => ['Net Revenue', 'Revenue By Country'],
    'retention' => ['Revenue Retention Cohort', 'Revenue Retention Rate', 'Renewal Summary'],
    'mrr_arr' => ['MRR', 'ARR', 'MRR Quick Ratio'],
];

$buildTemplateRow = static function (string $templateKey) use ($reportTemplates): array {
    $template = $reportTemplates[$templateKey];
    return [
        'report_key' => $templateKey,
        'name' => $template['name'],
        'category' => $template['category'],
        'created_by' => $template['created_by'],
        'created_meta' => '',
        'visited' => $template['visited'],
        'is_custom' => false,
    ];
};

$allReportRows = [];
foreach ($systemCategoryReports as $categorySlug => $reports) {
    foreach ($reports as $report) {
        if (isset($reportTemplates[$report])) {
            $allReportRows[] = $buildTemplateRow($report);
        } else {
            $allReportRows[] = [
                'report_key' => '',
                'name' => $report,
                'category' => ucwords(str_replace('_', ' ', $categorySlug)),
                'created_by' => 'System Generated',
                'created_meta' => '',
                'visited' => '-',
                'is_custom' => false,
            ];
        }
    }
}

foreach ($_SESSION['billing_custom_reports'] as $customReport) {
    $allReportRows[] = [
        'report_key' => 'custom_' . (int) $customReport['id'],
        'name' => (string) $customReport['name'],
        'category' => (string) $customReport['category'],
        'created_by' => (string) $customReport['created_by'],
        'created_meta' => (string) ($customReport['created_meta'] ?? ''),
        'visited' => (string) $customReport['visited'],
        'is_custom' => true,
        'custom_id' => (int) $customReport['id'],
        'shared_with' => (string) ($customReport['shared_with'] ?? 'Only Me'),
    ];
}

$homeLinks = [
    ['slug' => 'home', 'label' => 'Home', 'icon' => 'fa-house'],
    ['slug' => 'favorites', 'label' => 'Favorites', 'icon' => 'fa-star'],
    ['slug' => 'shared', 'label' => 'Shared Reports', 'icon' => 'fa-share-nodes'],
    ['slug' => 'mine', 'label' => 'My Reports', 'icon' => 'fa-id-badge'],
    ['slug' => 'scheduled', 'label' => 'Scheduled Reports', 'icon' => 'fa-clock'],
];

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

$view = isset($_GET['view']) ? strtolower(trim((string) $_GET['view'])) : 'home';
if (!in_array($view, ['home', 'favorites', 'shared', 'mine', 'scheduled'], true)) {
    $view = 'home';
}

$reportGroup = strtolower(trim((string) ($_GET['report_group'] ?? 'home')));
$reportMode = strtolower(trim((string) ($_GET['mode'] ?? 'center')));
$builderStep = max(1, min(4, (int) ($_GET['step'] ?? 1)));
$templateKey = strtolower(trim((string) ($_GET['template'] ?? 'sales_by_customer')));
if (!isset($reportTemplates[$templateKey])) {
    $templateKey = 'sales_by_customer';
}
$selectedReportId = (int) ($_GET['report_id'] ?? 0);
$openPanel = strtolower(trim((string) ($_GET['panel'] ?? '')));

$findCustomReport = static function (int $reportId): ?array {
    foreach ($_SESSION['billing_custom_reports'] as $report) {
        if ((int) ($report['id'] ?? 0) === $reportId) {
            return $report;
        }
    }
    return null;
};

$buildReportsUrl = static function (array $params = []) : string {
    $query = array_merge($_GET, $params);
    foreach ($query as $key => $value) {
        if ($value === null || $value === '') {
            unset($query[$key]);
        }
    }
    return 'reports.php' . ($query !== [] ? '?' . http_build_query($query) : '');
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reportAction = (string) ($_POST['report_action'] ?? '');

    if ($reportAction === 'start_custom_report') {
        $selectedTemplate = strtolower(trim((string) ($_POST['template'] ?? 'sales_by_customer')));
        if (!isset($reportTemplates[$selectedTemplate])) {
            $selectedTemplate = 'sales_by_customer';
        }

        $_SESSION['billing_report_draft'] = [
            'template' => $selectedTemplate,
            'date_range' => 'Today',
            'compare_with' => 'None',
            'entities' => 'All',
            'selected_columns' => $reportTemplates[$selectedTemplate]['columns'],
            'available_columns' => $reportTemplates[$selectedTemplate]['available_columns'],
            'layout' => [
                'show_organization_name' => 1,
                'show_organization_details' => 0,
                'show_page_number' => 0,
                'show_generated_by' => 0,
                'show_generated_date' => 0,
                'show_generated_time' => 0,
                'table_density' => 'Classic',
                'table_design' => 'Default',
                'auto_resize' => 1,
                'paper_size' => 'A4',
                'orientation' => 'Portrait',
                'font_family' => 'Ubuntu',
                'margin_top' => '0.7',
                'margin_bottom' => '0.7',
                'margin_left' => '0.55',
                'margin_right' => '0.2',
            ],
            'name' => '',
            'export_name' => $reportTemplates[$selectedTemplate]['default_export_name'],
            'description' => '',
            'shared_with' => 'Only Me',
        ];

        billing_redirect('reports.php?mode=builder&template=' . urlencode($selectedTemplate) . '&step=1');
    }

    if ($reportAction === 'builder_step_1') {
        $_SESSION['billing_report_draft']['date_range'] = (string) ($_POST['date_range'] ?? 'Today');
        $_SESSION['billing_report_draft']['compare_with'] = (string) ($_POST['compare_with'] ?? 'None');
        $_SESSION['billing_report_draft']['entities'] = (string) ($_POST['entities'] ?? 'All');
        billing_redirect('reports.php?mode=builder&template=' . urlencode($templateKey) . '&step=2');
    }

    if ($reportAction === 'builder_step_2') {
        $selectedColumns = $_POST['selected_columns'] ?? $reportTemplates[$templateKey]['columns'];
        if (!is_array($selectedColumns) || $selectedColumns === []) {
            $selectedColumns = $reportTemplates[$templateKey]['columns'];
        }
        $_SESSION['billing_report_draft']['selected_columns'] = array_values($selectedColumns);
        billing_redirect('reports.php?mode=builder&template=' . urlencode($templateKey) . '&step=3');
    }

    if ($reportAction === 'builder_step_3') {
        $_SESSION['billing_report_draft']['layout'] = [
            'show_organization_name' => !empty($_POST['show_organization_name']) ? 1 : 0,
            'show_organization_details' => !empty($_POST['show_organization_details']) ? 1 : 0,
            'show_page_number' => !empty($_POST['show_page_number']) ? 1 : 0,
            'show_generated_by' => !empty($_POST['show_generated_by']) ? 1 : 0,
            'show_generated_date' => !empty($_POST['show_generated_date']) ? 1 : 0,
            'show_generated_time' => !empty($_POST['show_generated_time']) ? 1 : 0,
            'auto_resize' => !empty($_POST['auto_resize']) ? 1 : 0,
            'table_density' => (string) ($_POST['table_density'] ?? 'Classic'),
            'table_design' => (string) ($_POST['table_design'] ?? 'Default'),
            'paper_size' => (string) ($_POST['paper_size'] ?? 'A4'),
            'orientation' => (string) ($_POST['orientation'] ?? 'Portrait'),
            'font_family' => (string) ($_POST['font_family'] ?? 'Ubuntu'),
            'margin_top' => (string) ($_POST['margin_top'] ?? '0.7'),
            'margin_bottom' => (string) ($_POST['margin_bottom'] ?? '0.7'),
            'margin_left' => (string) ($_POST['margin_left'] ?? '0.55'),
            'margin_right' => (string) ($_POST['margin_right'] ?? '0.2'),
        ];
        billing_redirect('reports.php?mode=builder&template=' . urlencode($templateKey) . '&step=4');
    }

    if ($reportAction === 'save_custom_report') {
        $reportName = trim((string) ($_POST['report_name'] ?? ''));
        if ($reportName === '') {
            $reportName = 'Custom Report';
        }

        $customReports = $_SESSION['billing_custom_reports'];
        $nextId = 1;
        foreach ($customReports as $report) {
            $nextId = max($nextId, ((int) ($report['id'] ?? 0)) + 1);
        }

        $draft = $_SESSION['billing_report_draft'];
        $customReports[] = [
            'id' => $nextId,
            'template' => (string) ($draft['template'] ?? $templateKey),
            'name' => $reportName,
            'export_name' => trim((string) ($_POST['export_name'] ?? $reportTemplates[$templateKey]['default_export_name'])),
            'description' => trim((string) ($_POST['description'] ?? '')),
            'category' => $reportTemplates[$templateKey]['category'],
            'created_by' => 'balachandar k',
            'created_meta' => 'On ' . date('d/m/Y h:i A'),
            'visited' => date('d/m/Y h:i A'),
            'shared_with' => (string) ($_POST['shared_with'] ?? 'Only Me'),
            'date_range' => (string) ($draft['date_range'] ?? 'Today'),
            'compare_with' => (string) ($draft['compare_with'] ?? 'None'),
            'entities' => (string) ($draft['entities'] ?? 'All'),
            'selected_columns' => $draft['selected_columns'] ?? $reportTemplates[$templateKey]['columns'],
            'available_columns' => $draft['available_columns'] ?? $reportTemplates[$templateKey]['available_columns'],
            'layout' => $draft['layout'] ?? [],
            'activity' => [
                ['actor' => 'balachandar k', 'time' => date('d/m/Y h:i A'), 'message' => 'Custom Report created.'],
            ],
        ];
        $_SESSION['billing_custom_reports'] = $customReports;
        $_SESSION['billing_report_draft'] = [];

        billing_redirect('reports.php?mode=view_report&report_id=' . $nextId);
    }

    if ($reportAction === 'share_report' && $selectedReportId > 0) {
        $customReports = $_SESSION['billing_custom_reports'];
        foreach ($customReports as &$report) {
            if ((int) ($report['id'] ?? 0) !== $selectedReportId) {
                continue;
            }

            $report['shared_with'] = (string) ($_POST['shared_with'] ?? 'Only Me');
            $report['activity'][] = [
                'actor' => 'balachandar k',
                'time' => date('d/m/Y h:i A'),
                'message' => 'Report sharing updated.',
            ];
        }
        unset($report);
        $_SESSION['billing_custom_reports'] = $customReports;

        billing_redirect('reports.php?mode=view_report&report_id=' . $selectedReportId);
    }
}

$customReports = $_SESSION['billing_custom_reports'];
$myReports = array_map(static function (array $report): array {
    return [
        'name' => (string) $report['name'],
        'category' => (string) $report['category'],
        'created_by' => (string) $report['created_by'],
        'created_meta' => (string) ($report['created_meta'] ?? ''),
        'visited' => (string) $report['visited'],
        'shared_with' => (string) ($report['shared_with'] ?? 'Only Me'),
        'custom_id' => (int) $report['id'],
    ];
}, $customReports);

$scheduledReports = [[
    'name' => 'gr',
    'frequency' => 'Weekly',
    'scheduled_by' => 'balachandar k',
    'next_scheduled_on' => '06/05/2026 10:00 AM',
    'recipient_name' => 'balachandar k',
    'recipient_email' => 'balachandarkat...',
    'status' => 'Active',
    'file_format' => 'PDF',
]];

$draft = $_SESSION['billing_report_draft'];
$selectedCustomReport = $selectedReportId > 0 ? $findCustomReport($selectedReportId) : null;

if ($reportMode === 'view_report' && !$selectedCustomReport) {
    $reportMode = 'center';
}
?>
<!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-reports-modes-restore">
<style>
.reports-modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(17, 24, 39, 0.55);
    z-index: 80;
}

.reports-modal {
    position: fixed;
    top: 110px;
    left: 50%;
    transform: translateX(-50%);
    width: min(750px, calc(100vw - 32px));
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 24px 50px rgba(15, 23, 42, 0.28);
    z-index: 81;
    overflow: hidden;
}

.reports-modal-head,
.reports-builder-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding: 22px 24px;
    border-bottom: 1px solid #e6edf5;
}

.reports-modal-head h2,
.reports-builder-head h1,
.reports-view-title {
    margin: 0;
}

.reports-modal-body {
    padding: 24px;
}

.reports-modal-select,
.reports-builder-field input,
.reports-builder-field select,
.reports-builder-field textarea {
    width: 100%;
    min-height: 44px;
    border: 1px solid #d6deea;
    border-radius: 10px;
    padding: 0 14px;
    background: #fff;
    color: #111b2d;
    font: inherit;
}

.reports-builder-field textarea {
    min-height: 144px;
    padding-top: 12px;
    padding-bottom: 12px;
    resize: vertical;
}

.reports-modal-list {
    margin-top: 12px;
    max-height: 300px;
    overflow: auto;
    border: 1px solid #e7edf4;
    border-radius: 12px;
}

.reports-modal-list-group {
    padding: 10px 12px 4px;
    color: #56657a;
    font-weight: 700;
}

.reports-modal-option {
    width: 100%;
    padding: 12px 24px;
    border: 0;
    background: #fff;
    text-align: left;
    font: inherit;
    cursor: pointer;
}

.reports-modal-option.is-active,
.reports-modal-option:hover {
    background: #4285f4;
    color: #fff;
}

.reports-modal-actions,
.reports-builder-footer {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 18px 24px 24px;
    border-top: 1px solid #e6edf5;
}

.reports-builder-page {
    background: #fff;
    min-height: calc(100vh - 120px);
}

.reports-builder-steps {
    display: flex;
    align-items: center;
    gap: 18px;
    padding: 0 24px;
    border-bottom: 1px solid #e6edf5;
}

.reports-builder-step {
    min-height: 56px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: #2363f0;
    text-decoration: none;
    font-size: 18px;
}

.reports-builder-step strong {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 1px solid #cfd8e6;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #111b2d;
    font-size: 16px;
}

.reports-builder-step.is-active {
    color: #111b2d;
    box-shadow: inset 0 -3px 0 #4d87ef;
    font-weight: 700;
}

.reports-builder-content {
    padding: 26px 24px 0;
}

.reports-builder-section {
    padding: 18px 0 24px;
    border-bottom: 1px solid #e7edf4;
}

.reports-builder-grid {
    display: grid;
    grid-template-columns: minmax(300px, 420px) minmax(300px, 420px);
    gap: 34px;
}

.reports-builder-field label,
.reports-layout-group h3,
.reports-share-box h3 {
    display: block;
    margin-bottom: 12px;
    color: #111b2d;
    font-size: 16px;
    font-weight: 600;
}

.reports-filter-add {
    color: #2563eb;
    text-decoration: none;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.reports-columns-grid {
    display: grid;
    grid-template-columns: minmax(280px, 420px) 80px minmax(280px, 420px);
    gap: 24px;
    align-items: center;
    padding: 18px 0 28px;
}

.reports-columns-box {
    border: 1px solid #dfe7f2;
    border-radius: 12px;
    overflow: hidden;
    min-height: 560px;
    background: #fff;
}

.reports-columns-head {
    padding: 18px 18px 14px;
    color: #6b7690;
    font-weight: 700;
}

.reports-columns-search {
    padding: 0 14px 10px;
}

.reports-columns-search input {
    width: 100%;
    min-height: 42px;
    border: 1px solid #d6deea;
    border-radius: 10px;
    padding: 0 12px;
    font: inherit;
}

.reports-columns-list {
    max-height: 470px;
    overflow: auto;
    padding: 0 14px 14px;
}

.reports-columns-group {
    padding: 10px 6px;
    color: #8a96aa;
}

.reports-columns-item {
    padding: 8px 18px;
}

.reports-columns-arrow {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    border: 2px solid #7988a4;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #7988a4;
    font-size: 24px;
    margin: 0 auto;
}

.reports-layout-screen {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 400px;
    gap: 36px;
    align-items: start;
}

.reports-layout-options {
    display: grid;
    gap: 28px;
}

.reports-layout-inline {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 16px 26px;
}

.reports-layout-checks,
.reports-share-options {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
}

.reports-layout-checks label,
.reports-layout-radios label,
.reports-share-options label {
    display: inline-flex;
    align-items: center;
    gap: 10px;
}

.reports-layout-radios {
    display: flex;
    gap: 18px;
    flex-wrap: wrap;
}

.reports-layout-margin-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
}

.reports-preview-panel {
    background: #f6f8fd;
    border-radius: 18px;
    padding: 20px 20px 26px;
}

.reports-preview-panel h3 {
    margin: 0 0 18px;
    text-align: center;
    font-size: 16px;
    font-weight: 500;
}

.reports-preview-sheet {
    width: 340px;
    max-width: 100%;
    margin: 0 auto;
    background: #fff;
    padding: 24px 18px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.12);
}

.reports-preview-sheet strong,
.reports-preview-sheet span {
    display: block;
    text-align: center;
}

.reports-preview-bar {
    height: 32px;
    margin: 22px 0 30px;
    background: #f0f0f0;
}

.reports-preview-line {
    height: 1px;
    background: #e3e6eb;
    margin: 0 0 26px;
}

.reports-builder-note {
    margin-top: 10px;
    color: #4f5f74;
}

.reports-builder-tip {
    margin-top: 20px;
    padding: 18px 20px;
    border-radius: 16px;
    background: #f7f9fc;
}

.reports-share-box {
    margin: 24px;
    padding: 24px;
    border: 1px solid #e7edf4;
    border-radius: 18px;
    background: #fbfcff;
}

.reports-view-page {
    background: #f5f7fc;
    min-height: calc(100vh - 120px);
}

.reports-view-head,
.reports-view-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
    padding: 18px 22px;
    background: #fff;
    border-bottom: 1px solid #e6edf5;
}

.reports-view-head-left,
.reports-view-toolbar-left,
.reports-view-head-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.reports-view-hamburger,
.reports-view-icon,
.reports-view-close {
    width: 42px;
    height: 42px;
    border: 1px solid #d6deea;
    border-radius: 10px;
    background: #fff;
    color: #2b3953;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
}

.reports-view-subtitle {
    margin-top: 4px;
    color: #4f5f74;
}

.reports-filter-chip {
    min-height: 42px;
    padding: 0 14px;
    border: 1px solid #d6deea;
    border-radius: 10px;
    background: #fff;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.reports-run-btn {
    min-height: 42px;
    padding: 0 18px;
    border-radius: 8px;
    background: #69d3a6;
    color: #fff;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
}

.reports-view-card {
    margin: 20px 20px 24px;
    background: #fff;
    border: 1px solid #e1e7f0;
    border-radius: 18px;
    overflow: hidden;
}

.reports-view-summary {
    padding: 34px 20px 30px;
    text-align: center;
    border-bottom: 1px solid #e8edf5;
}

.reports-view-table {
    width: 100%;
    border-collapse: collapse;
}

.reports-view-table th,
.reports-view-table td {
    padding: 14px 18px;
    border-bottom: 1px solid #eef2f7;
    text-align: left;
}

.reports-view-table th {
    color: #62708b;
    font-size: 13px;
    font-weight: 800;
}

.reports-view-empty {
    padding: 120px 24px;
    text-align: center;
    color: #65748b;
    font-size: 18px;
}

.reports-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    min-width: 390px;
    background: #fff;
    border: 1px solid #e1e8f2;
    border-radius: 14px;
    box-shadow: 0 14px 30px rgba(30, 44, 74, 0.14);
    padding: 12px 0;
    z-index: 30;
}

.reports-dropdown h4 {
    margin: 8px 16px 10px;
    color: #7b8496;
    font-size: 12px;
    font-weight: 800;
}

.reports-dropdown a {
    display: block;
    padding: 10px 18px;
    color: #2c3851;
    text-decoration: none;
}

.reports-dropdown a:hover {
    background: #4285f4;
    color: #fff;
}

.reports-activity-panel {
    position: fixed;
    top: 169px;
    right: 0;
    width: min(490px, 100vw);
    height: calc(100vh - 169px);
    background: #fff;
    border-left: 1px solid #e6edf5;
    box-shadow: -8px 0 24px rgba(15, 23, 42, 0.12);
    z-index: 82;
    display: flex;
    flex-direction: column;
}

.reports-activity-list {
    padding: 22px 24px;
    overflow: auto;
}

.reports-activity-item {
    display: grid;
    grid-template-columns: 34px 1fr;
    gap: 14px;
}

.reports-activity-icon {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    border: 1px solid #33b36b;
    color: #33b36b;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.reports-activity-box {
    margin-top: 10px;
    padding: 18px;
    background: #f7f9fc;
    border-radius: 12px;
}

@media (max-width: 1180px) {
    .reports-builder-grid,
    .reports-layout-screen,
    .reports-columns-grid {
        grid-template-columns: 1fr;
    }
}
</style>
</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'; ?>

        <?php if ($reportMode === 'builder'): ?>
            <main class="reports-builder-page">
                <div class="reports-builder-head">
                    <h1>Create Custom Report</h1>
                    <a class="reports-view-close" href="reports.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                </div>

                <div class="reports-builder-steps">
                    <a class="reports-builder-step<?php echo $builderStep === 1 ? ' is-active' : ''; ?>" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=1"><strong>1</strong><span>General</span></a>
                    <a class="reports-builder-step<?php echo $builderStep === 2 ? ' is-active' : ''; ?>" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=2"><strong>2</strong><span>Show / Hide Columns</span></a>
                    <a class="reports-builder-step<?php echo $builderStep === 3 ? ' is-active' : ''; ?>" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=3"><strong>3</strong><span>Report Layout</span></a>
                    <a class="reports-builder-step<?php echo $builderStep === 4 ? ' is-active' : ''; ?>" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=4"><strong>4</strong><span>Report Preferences</span></a>
                </div>

                <?php if ($builderStep === 1): ?>
                    <form method="post">
                        <input type="hidden" name="report_action" value="builder_step_1">
                        <div class="reports-builder-content">
                            <div class="reports-builder-section">
                                <div class="reports-builder-grid">
                                    <div class="reports-builder-field">
                                        <label>Date Range</label>
                                        <select name="date_range">
                                            <option value="Today" <?php echo (($draft['date_range'] ?? 'Today') === 'Today') ? 'selected' : ''; ?>>Today</option>
                                            <option value="This Month" <?php echo (($draft['date_range'] ?? '') === 'This Month') ? 'selected' : ''; ?>>This Month</option>
                                            <option value="This Quarter" <?php echo (($draft['date_range'] ?? '') === 'This Quarter') ? 'selected' : ''; ?>>This Quarter</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="reports-builder-section">
                                <div class="reports-builder-grid">
                                    <div class="reports-builder-field">
                                        <label>Compare With</label>
                                        <select name="compare_with">
                                            <option value="None" <?php echo (($draft['compare_with'] ?? 'None') === 'None') ? 'selected' : ''; ?>>None</option>
                                            <option value="Previous Period" <?php echo (($draft['compare_with'] ?? '') === 'Previous Period') ? 'selected' : ''; ?>>Previous Period</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="reports-builder-section">
                                <div class="reports-builder-grid">
                                    <div class="reports-builder-field">
                                        <label>Entities :</label>
                                        <select name="entities">
                                            <option value="All" <?php echo (($draft['entities'] ?? 'All') === 'All') ? 'selected' : ''; ?>>All</option>
                                            <option value="Invoice, Credit Note" <?php echo (($draft['entities'] ?? '') === 'Invoice, Credit Note') ? 'selected' : ''; ?>>Invoice, Credit Note</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="reports-builder-section">
                                <h2>Advanced Filters</h2>
                                <p class="reports-builder-note">Use advanced filters to filter the report based on the fields of Reports.</p>
                                <a class="reports-filter-add" href="#"><i class="fa-solid fa-circle-plus"></i><span>Add Filters</span></a>
                            </div>
                        </div>
                        <div class="reports-builder-footer">
                            <button class="customer-btn customer-btn--green" type="submit">Next</button>
                            <a class="customer-btn" href="reports.php">Cancel</a>
                        </div>
                    </form>
                <?php elseif ($builderStep === 2): ?>
                    <form method="post">
                        <input type="hidden" name="report_action" value="builder_step_2">
                        <div class="reports-builder-content">
                            <div class="reports-columns-grid">
                                <div class="reports-columns-box">
                                    <div class="reports-columns-head">AVAILABLE COLUMNS</div>
                                    <div class="reports-columns-search"><input type="search" placeholder="Search"></div>
                                    <div class="reports-columns-list">
                                        <div class="reports-columns-group">Reports</div>
                                        <?php foreach ($reportTemplates[$templateKey]['available_columns'] as $column): ?>
                                            <div class="reports-columns-item"><?php echo billing_escape($column); ?></div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <div class="reports-columns-arrow"><i class="fa-solid fa-arrow-right"></i></div>
                                <div class="reports-columns-box">
                                    <div class="reports-columns-head">SELECTED COLUMNS</div>
                                    <div class="reports-columns-list" style="padding-top:16px;">
                                        <?php foreach (($draft['selected_columns'] ?? $reportTemplates[$templateKey]['columns']) as $column): ?>
                                            <label class="reports-columns-item" style="display:block;">
                                                <input type="checkbox" name="selected_columns[]" value="<?php echo billing_escape($column); ?>" checked>
                                                <span style="margin-left:10px;"><?php echo billing_escape($column); ?> <span style="color:#7c89a0;">(Reports)</span></span>
                                            </label>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="reports-builder-footer">
                            <a class="customer-btn customer-icon-btn" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=1"><i class="fa-solid fa-angle-left"></i></a>
                            <button class="customer-btn customer-btn--green" type="submit">Next</button>
                            <a class="customer-btn" href="reports.php">Cancel</a>
                        </div>
                    </form>
                <?php elseif ($builderStep === 3): ?>
                    <?php $layout = $draft['layout'] ?? []; ?>
                    <form method="post">
                        <input type="hidden" name="report_action" value="builder_step_3">
                        <div class="reports-builder-content">
                            <div class="reports-layout-screen">
                                <div class="reports-layout-options">
                                    <div class="reports-layout-group">
                                        <h3>Choose Details to Display</h3>
                                        <div class="reports-layout-checks">
                                            <label><input type="checkbox" name="show_organization_name" value="1" <?php echo !empty($layout['show_organization_name']) ? 'checked' : ''; ?>> Organization Name</label>
                                            <label><input type="checkbox" name="show_organization_details" value="1" <?php echo !empty($layout['show_organization_details']) ? 'checked' : ''; ?>> Organization Details</label>
                                            <label><input type="checkbox" name="show_page_number" value="1" <?php echo !empty($layout['show_page_number']) ? 'checked' : ''; ?>> Page Number</label>
                                            <label><input type="checkbox" name="show_generated_by" value="1" <?php echo !empty($layout['show_generated_by']) ? 'checked' : ''; ?>> Generated By</label>
                                            <label><input type="checkbox" name="show_generated_date" value="1" <?php echo !empty($layout['show_generated_date']) ? 'checked' : ''; ?>> Generated Date</label>
                                            <label><input type="checkbox" name="show_generated_time" value="1" <?php echo !empty($layout['show_generated_time']) ? 'checked' : ''; ?>> Generated Time</label>
                                        </div>
                                    </div>
                                    <div class="reports-builder-section">
                                        <h2>Report Layout</h2>
                                        <div class="reports-layout-inline">
                                            <div class="reports-builder-field">
                                                <label>Table Density</label>
                                                <select name="table_density"><option<?php echo (($layout['table_density'] ?? 'Classic') === 'Classic') ? ' selected' : ''; ?>>Classic</option></select>
                                            </div>
                                            <div class="reports-builder-field">
                                                <label>Table Design</label>
                                                <select name="table_design"><option<?php echo (($layout['table_design'] ?? 'Default') === 'Default') ? ' selected' : ''; ?>>Default</option></select>
                                            </div>
                                        </div>
                                        <div style="margin-top:22px;">
                                            <label><input type="checkbox" name="auto_resize" value="1" <?php echo !empty($layout['auto_resize']) ? 'checked' : ''; ?>> Re-size the table and its font automatically to fit the content within the table.</label>
                                        </div>
                                        <div class="reports-layout-inline" style="margin-top:26px;">
                                            <div class="reports-builder-field">
                                                <label>Paper Size</label>
                                                <div class="reports-layout-radios">
                                                    <label><input type="radio" name="paper_size" value="A4" <?php echo (($layout['paper_size'] ?? 'A4') === 'A4') ? 'checked' : ''; ?>> A4</label>
                                                    <label><input type="radio" name="paper_size" value="Letter" <?php echo (($layout['paper_size'] ?? '') === 'Letter') ? 'checked' : ''; ?>> Letter</label>
                                                </div>
                                            </div>
                                            <div class="reports-builder-field">
                                                <label>Orientation</label>
                                                <div class="reports-layout-radios">
                                                    <label><input type="radio" name="orientation" value="Portrait" <?php echo (($layout['orientation'] ?? 'Portrait') === 'Portrait') ? 'checked' : ''; ?>> Portrait</label>
                                                    <label><input type="radio" name="orientation" value="Landscape" <?php echo (($layout['orientation'] ?? '') === 'Landscape') ? 'checked' : ''; ?>> Landscape</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="reports-layout-inline" style="margin-top:26px;">
                                            <div class="reports-builder-field">
                                                <label>Font Family</label>
                                                <select name="font_family"><option<?php echo (($layout['font_family'] ?? 'Ubuntu') === 'Ubuntu') ? ' selected' : ''; ?>>Ubuntu</option></select>
                                                <div class="reports-builder-note">Supports English and European languages. This font can</div>
                                            </div>
                                            <div class="reports-builder-field">
                                                <label>Margins</label>
                                                <div class="reports-layout-margin-grid">
                                                    <input type="text" name="margin_top" value="<?php echo billing_escape((string) ($layout['margin_top'] ?? '0.7')); ?>">
                                                    <input type="text" name="margin_bottom" value="<?php echo billing_escape((string) ($layout['margin_bottom'] ?? '0.7')); ?>">
                                                    <input type="text" name="margin_left" value="<?php echo billing_escape((string) ($layout['margin_left'] ?? '0.55')); ?>">
                                                    <input type="text" name="margin_right" value="<?php echo billing_escape((string) ($layout['margin_right'] ?? '0.2')); ?>">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="reports-preview-panel">
                                    <h3>PREVIEW</h3>
                                    <div class="reports-preview-sheet">
                                        <strong><?php echo billing_escape((string) ($organization['organization_name'] ?? 'demo')); ?></strong>
                                        <div class="reports-preview-bar"></div>
                                        <?php for ($i = 0; $i < 7; $i++): ?>
                                            <div class="reports-preview-line"></div>
                                        <?php endfor; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="reports-builder-footer">
                            <a class="customer-btn customer-icon-btn" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=2"><i class="fa-solid fa-angle-left"></i></a>
                            <button class="customer-btn customer-btn--green" type="submit">Next</button>
                            <a class="customer-btn" href="reports.php">Cancel</a>
                        </div>
                    </form>
                <?php else: ?>
                    <form method="post">
                        <input type="hidden" name="report_action" value="save_custom_report">
                        <div class="reports-builder-content">
                            <div class="reports-builder-grid">
                                <div class="reports-builder-field">
                                    <label style="color:#ef4444;">Report Name*</label>
                                    <input type="text" name="report_name" maxlength="50" value="<?php echo billing_escape((string) ($draft['name'] ?? '')); ?>" required>
                                    <div class="reports-builder-note" style="text-align:right;">3 / 50</div>
                                </div>
                                <div></div>
                            </div>
                            <div class="reports-builder-grid" style="margin-top:22px;">
                                <div class="reports-builder-field">
                                    <label>Name in Export</label>
                                    <input type="text" name="export_name" value="<?php echo billing_escape((string) ($draft['export_name'] ?? $reportTemplates[$templateKey]['default_export_name'])); ?>">
                                </div>
                            </div>
                            <div class="reports-builder-field" style="max-width: 860px; margin-top:26px;">
                                <label>Report Description</label>
                                <textarea name="description" placeholder="Add a description to your report"><?php echo billing_escape((string) ($draft['description'] ?? '')); ?></textarea>
                            </div>
                            <div class="reports-builder-tip" style="max-width: 860px;">
                                <i class="fa-solid fa-lightbulb" style="color:#f4c430;"></i>
                                You can use report descriptions to help you identify the details of the reports for your reference.
                            </div>
                            <div class="reports-builder-section" style="margin-top:22px;">
                                <h2>Configure Permissions</h2>
                                <div class="reports-share-options">
                                    <label><input type="radio" name="shared_with" value="Only Me" checked> Only Me</label>
                                    <label><input type="radio" name="shared_with" value="Only Selected Users &amp; Roles"> Only Selected Users &amp; Roles</label>
                                    <label><input type="radio" name="shared_with" value="Everyone"> Everyone</label>
                                </div>
                            </div>
                        </div>
                        <div class="reports-builder-footer">
                            <a class="customer-btn customer-icon-btn" href="reports.php?mode=builder&amp;template=<?php echo billing_escape($templateKey); ?>&amp;step=3"><i class="fa-solid fa-angle-left"></i></a>
                            <button class="customer-btn customer-btn--green" type="submit">Save Custom Report</button>
                            <a class="customer-btn" href="reports.php">Cancel</a>
                        </div>
                    </form>
                <?php endif; ?>
            </main>

        <?php elseif ($reportMode === 'view_report' && $selectedCustomReport): ?>
            <main class="reports-view-page">
                <div class="reports-view-head">
                    <div class="reports-view-head-left">
                        <button class="reports-view-hamburger" type="button"><i class="fa-solid fa-bars"></i></button>
                        <div>
                            <h1 class="reports-view-title"><?php echo billing_escape((string) $selectedCustomReport['name']); ?> <a href="reports.php?mode=builder&amp;template=<?php echo billing_escape((string) $selectedCustomReport['template']); ?>&amp;step=4" style="font-size:20px; color:#2563eb; text-decoration:none;"><i class="fa-regular fa-pen-to-square"></i></a></h1>
                            <div class="reports-view-subtitle">From 09/05/2026 To 09/05/2026</div>
                        </div>
                    </div>
                    <div class="reports-view-head-actions">
                        <a class="reports-view-icon" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>&amp;panel=activity"><i class="fa-regular fa-clock"></i></a>
                        <a class="reports-view-icon" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>&amp;panel=share"><i class="fa-solid fa-share-nodes"></i></a>
                        <div class="customer-menu-wrap">
                            <button class="customer-btn" type="button" data-menu-toggle="reportExportMenu">Export <i class="fa-solid fa-angle-down"></i></button>
                            <?php if ($openPanel === 'export'): ?>
                                <div class="reports-dropdown" id="reportExportMenu" style="display:block;">
                                    <h4>EXPORT AS</h4>
                                    <a href="#">PDF</a>
                                    <a href="#">XLSX (Microsoft Excel)</a>
                                    <a href="#">XLS (Microsoft Excel 1997-2004 Compatible)</a>
                                    <a href="#">CSV (Comma Separated Value)</a>
                                    <a href="#">Export to Zoho Sheet</a>
                                    <h4>PRINT</h4>
                                    <a href="#">Print</a>
                                    <a href="#">Print Preference</a>
                                </div>
                            <?php endif; ?>
                        </div>
                        <a class="reports-view-icon" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>&amp;panel=export"><i class="fa-solid fa-arrow-rotate-right"></i></a>
                        <a class="reports-view-close" href="reports.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
                    </div>
                </div>

                <div class="reports-view-toolbar">
                    <div class="reports-view-toolbar-left">
                        <span><i class="fa-solid fa-filter"></i> Filters :</span>
                        <button class="reports-filter-chip" type="button">Date Range : <strong>Today</strong> <i class="fa-solid fa-angle-down"></i></button>
                        <a class="reports-run-btn" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>">Run Report</a>
                    </div>
                </div>

                <section class="reports-view-card">
                    <div class="reports-view-summary">
                        <div style="color:#6b7690;"><?php echo billing_escape((string) ($organization['organization_name'] ?? 'demo')); ?></div>
                        <h2 style="margin:8px 0 8px;"><?php echo billing_escape((string) $selectedCustomReport['name']); ?></h2>
                        <div style="color:#4f5f74;">From 09/05/2026 To 09/05/2026</div>
                    </div>
                    <table class="reports-view-table">
                        <thead>
                            <tr>
                                <?php foreach ((array) ($selectedCustomReport['selected_columns'] ?? []) as $column): ?>
                                    <th><?php echo billing_escape(strtoupper((string) $column)); ?></th>
                                <?php endforeach; ?>
                            </tr>
                        </thead>
                    </table>
                    <div class="reports-view-empty">There were no sales during the selected date range.</div>
                </section>
            </main>

            <?php if ($openPanel === 'share'): ?>
                <div class="reports-modal-overlay"></div>
                <div class="reports-modal" style="width:min(860px, calc(100vw - 32px));">
                    <div class="reports-modal-head">
                        <h2>Share Report</h2>
                        <a class="reports-view-close" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>"><i class="fa-solid fa-xmark"></i></a>
                    </div>
                    <form method="post">
                        <input type="hidden" name="report_action" value="share_report">
                        <div class="reports-share-box">
                            <h3>Share With</h3>
                            <div class="reports-share-options">
                                <label><input type="radio" name="shared_with" value="Only Me" <?php echo (($selectedCustomReport['shared_with'] ?? 'Only Me') === 'Only Me') ? 'checked' : ''; ?>> Only Me</label>
                                <label><input type="radio" name="shared_with" value="Only Selected Users &amp; Roles" <?php echo (($selectedCustomReport['shared_with'] ?? '') === 'Only Selected Users & Roles') ? 'checked' : ''; ?>> Only Selected Users &amp; Roles</label>
                                <label><input type="radio" name="shared_with" value="Everyone" <?php echo (($selectedCustomReport['shared_with'] ?? '') === 'Everyone') ? 'checked' : ''; ?>> Everyone</label>
                            </div>
                        </div>
                        <div class="reports-modal-actions">
                            <button class="customer-btn customer-btn--green" type="submit">Share</button>
                            <a class="customer-btn" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>">Close</a>
                        </div>
                    </form>
                </div>
            <?php endif; ?>

            <?php if ($openPanel === 'activity'): ?>
                <div class="reports-activity-panel">
                    <div class="reports-modal-head">
                        <h2>Report Activity</h2>
                        <a class="reports-view-close" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $selectedCustomReport['id']; ?>"><i class="fa-solid fa-xmark"></i></a>
                    </div>
                    <div class="reports-activity-list">
                        <?php foreach ((array) ($selectedCustomReport['activity'] ?? []) as $activity): ?>
                            <div class="reports-activity-item">
                                <span class="reports-activity-icon"><i class="fa-solid fa-plus"></i></span>
                                <div>
                                    <div><strong><?php echo billing_escape((string) $activity['actor']); ?></strong> <span style="color:#7c89a0;">• <?php echo billing_escape((string) $activity['time']); ?></span></div>
                                    <div class="reports-activity-box"><?php echo billing_escape((string) $activity['message']); ?></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

        <?php else: ?>
            <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="<?php echo billing_escape($buildReportsUrl(['mode' => null])); ?>">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="<?php echo billing_escape($buildReportsUrl(['mode' => 'choose_report'])); ?>">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 ($homeLinks as $link): ?>
                                    <a class="app-report-nav-item<?php echo $view === $link['slug'] ? ' is-active' : ''; ?>" href="reports.php<?php echo $link['slug'] === 'home' ? '' : '?view=' . billing_escape($link['slug']); ?>">
                                        <i class="fa-regular <?php echo billing_escape($link['icon']); ?>"></i>
                                        <span><?php echo billing_escape($link['label']); ?></span>
                                    </a>
                                <?php endforeach; ?>
                            </nav>

                            <div class="app-report-side-title">REPORT CATEGORY</div>
                            <div class="app-report-category-list">
                                <?php foreach ($reportCategories as $category): ?>
                                    <a class="app-report-category<?php echo $reportGroup === $category['slug'] ? ' is-active' : ''; ?>" href="reports.php?report_group=<?php echo billing_escape($category['slug']); ?>">
                                        <i class="fa-regular fa-folder"></i>
                                        <span><?php echo billing_escape($category['label']); ?></span>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </aside>

                        <section class="app-report-list-card">
                            <?php if ($view === 'favorites'): ?>
                                <div class="app-report-list-head"><h2>Favorites</h2></div>
                                <div class="billing-reports-empty-state">
                                    <div class="billing-reports-empty-icon"><i class="fa-regular fa-star"></i></div>
                                    <p>You haven’t marked any reports as a favorite.</p>
                                    <span>Click the Star icon next to a report to view it here.</span>
                                </div>
                            <?php elseif ($view === 'mine'): ?>
                                <div class="app-report-list-head billing-reports-tabs-head">
                                    <h2>My Reports</h2>
                                    <div class="billing-reports-inline-tabs">
                                        <a class="is-active" href="reports.php?view=mine">My Reports</a>
                                        <a href="reports.php?view=mine">Other User Reports</a>
                                    </div>
                                </div>
                                <div class="billing-reports-filter-bar">
                                    <span><i class="fa-solid fa-filter"></i> Filters :</span>
                                    <button type="button">Schedule Type : <strong>All</strong> <i class="fa-solid fa-angle-down"></i></button>
                                    <button type="button">Parent Report : <strong>All</strong> <i class="fa-solid fa-angle-down"></i></button>
                                </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>
                                                <th>SHARED WITH</th>
                                            </tr>
                                        </thead>
                                        <tbody data-report-list>
                                            <?php foreach ($myReports as $report): ?>
                                                <tr data-report-name="<?php echo billing_escape(strtolower($report['name'])); ?>">
                                                    <td>
                                                        <div class="billing-reports-row-name">
                                                            <i class="fa-regular fa-star"></i>
                                                            <a class="app-report-link" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $report['custom_id']; ?>"><?php echo billing_escape($report['name']); ?></a>
                                                        </div>
                                                    </td>
                                                    <td><?php echo billing_escape($report['category']); ?></td>
                                                    <td>
                                                        <div class="billing-reports-cell-main"><?php echo billing_escape($report['created_by']); ?></div>
                                                        <div class="billing-reports-cell-sub"><?php echo billing_escape($report['created_meta']); ?></div>
                                                    </td>
                                                    <td><?php echo billing_escape($report['visited']); ?></td>
                                                    <td><?php echo billing_escape($report['shared_with']); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php elseif ($view === 'scheduled'): ?>
                                <div class="app-report-list-head"><h2>Scheduled Reports</h2></div>
                                <div class="app-table-wrap">
                                    <table class="app-table app-table--reports">
                                        <thead>
                                            <tr>
                                                <th>REPORT NAME</th>
                                                <th>FREQUENCY</th>
                                                <th>SCHEDULED BY</th>
                                                <th>NEXT SCHEDULED ON</th>
                                                <th>EMAIL RECIPIENTS</th>
                                                <th>STATUS</th>
                                                <th>FILE FORMAT</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($scheduledReports as $report): ?>
                                                <tr>
                                                    <td><?php echo billing_escape($report['name']); ?></td>
                                                    <td><?php echo billing_escape($report['frequency']); ?></td>
                                                    <td><?php echo billing_escape($report['scheduled_by']); ?></td>
                                                    <td><?php echo billing_escape($report['next_scheduled_on']); ?></td>
                                                    <td><?php echo billing_escape($report['recipient_name'] . ' / ' . $report['recipient_email']); ?></td>
                                                    <td><span class="billing-reports-status-active"><?php echo billing_escape($report['status']); ?></span></td>
                                                    <td><?php echo billing_escape($report['file_format']); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php else: ?>
                                <div class="app-report-list-head">
                                    <h2>All Reports <span><?php echo count($allReportRows); ?></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 ($allReportRows as $report): ?>
                                                <tr data-report-name="<?php echo billing_escape(strtolower($report['name'])); ?>">
                                                    <td>
                                                        <div class="billing-reports-row-name">
                                                            <i class="fa-regular fa-star"></i>
                                                            <?php if (!empty($report['is_custom'])): ?>
                                                                <a class="app-report-link" href="reports.php?mode=view_report&amp;report_id=<?php echo (int) $report['custom_id']; ?>"><?php echo billing_escape($report['name']); ?></a>
                                                            <?php else: ?>
                                                                <a class="app-report-link" href="<?php echo billing_escape($buildReportsUrl(['mode' => 'choose_report'])); ?>"><?php echo billing_escape($report['name']); ?></a>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td><?php echo billing_escape($report['category']); ?></td>
                                                    <td>
                                                        <div class="billing-reports-cell-main"><?php echo billing_escape($report['created_by']); ?></div>
                                                        <?php if (!empty($report['created_meta'])): ?>
                                                            <div class="billing-reports-cell-sub"><?php echo billing_escape((string) $report['created_meta']); ?></div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo billing_escape($report['visited']); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </section>
                    </div>
                </section>
            </main>

            <?php if ($reportMode === 'choose_report'): ?>
                <div class="reports-modal-overlay"></div>
                <div class="reports-modal">
                    <div class="reports-modal-head">
                        <h2>New Custom Report</h2>
                        <a class="reports-view-close" href="reports.php"><i class="fa-solid fa-xmark"></i></a>
                    </div>
                    <form method="post">
                        <input type="hidden" name="report_action" value="start_custom_report">
                        <div class="reports-modal-body">
                            <p>Select the report that you want to customize and create a new custom report.</p>
                            <select class="reports-modal-select" name="template" id="reportTemplateSelect">
                                <?php foreach ($reportTemplates as $templateSlug => $template): ?>
                                    <option value="<?php echo billing_escape($templateSlug); ?>"><?php echo billing_escape($template['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="reports-modal-list">
                                <div class="reports-modal-list-group">Sales</div>
                                <?php foreach ($reportTemplates as $templateSlug => $template): ?>
                                    <button class="reports-modal-option<?php echo $templateSlug === 'sales_by_customer' ? ' is-active' : ''; ?>" type="button" data-template-option="<?php echo billing_escape($templateSlug); ?>"><?php echo billing_escape($template['name']); ?></button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="reports-modal-actions">
                            <button class="customer-btn customer-btn--green" type="submit">Proceed</button>
                            <a class="customer-btn" href="reports.php">Cancel</a>
                        </div>
                    </form>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</div>
<script src="assets/billing.js?v=20260507-reports-modes-restore"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    var search = document.querySelector('[data-report-search]');
    var rows = Array.from(document.querySelectorAll('[data-report-list] tr'));

    if (search) {
        search.addEventListener('input', function () {
            var query = search.value.trim().toLowerCase();
            rows.forEach(function (row) {
                var name = row.getAttribute('data-report-name') || '';
                row.hidden = !(query === '' || name.indexOf(query) !== -1);
            });
        });
    }

    var select = document.getElementById('reportTemplateSelect');
    document.querySelectorAll('[data-template-option]').forEach(function (button) {
        button.addEventListener('click', function () {
            var value = button.getAttribute('data-template-option');
            if (select) {
                select.value = value;
            }
            document.querySelectorAll('[data-template-option]').forEach(function (item) {
                item.classList.toggle('is-active', item === button);
            });
        });
    });
});
</script>
</body>
</html>
