<?php
session_start();

require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/layout.php';
require_once __DIR__ . '/../includes/expense_shell.php';

if (!isset($_SESSION['authenticated'])) {
    redirect(page_url('signin'));
}

$userId = current_user_id();
if ($userId <= 0) {
    redirect(page_url('signin'));
}

$summary = [
    'pending_approval' => 0,
    'unreported_expenses' => 0,
    'unreported_advances_count' => 0,
    'unreported_advances_amount' => 0.00,
    'unsubmitted_reports' => 0,
    'awaiting_approval_reports' => 0,
    'awaiting_reimbursement_reports' => 0,
    'awaiting_reimbursement_amount' => 0.00,
    'total_trips' => 0,
];

$overview = fetch_one(
    'SELECT total_expense_count, total_expense_amount, total_category_count, total_report_count, total_trip_count, active_trip_count, pending_approval_count, awaiting_approval_reports_count, awaiting_reimbursement_reports_count, awaiting_reimbursement_amount
     FROM vw_analytics_overview
     WHERE user_id = ?',
    'i',
    [$userId]
);

if ($overview) {
    $summary['pending_approval'] = (int) ($overview['pending_approval_count'] ?? 0);
    $summary['unreported_expenses'] = (int) ($overview['total_expense_count'] ?? 0);
    $summary['unreported_advances_count'] = (int) ($overview['total_category_count'] ?? 0);
    $summary['unreported_advances_amount'] = (float) ($overview['total_expense_amount'] ?? 0);
    $summary['unsubmitted_reports'] = (int) ($overview['total_report_count'] ?? 0);
    $summary['awaiting_approval_reports'] = (int) ($overview['awaiting_approval_reports_count'] ?? 0);
    $summary['awaiting_reimbursement_reports'] = (int) ($overview['awaiting_reimbursement_reports_count'] ?? 0);
    $summary['awaiting_reimbursement_amount'] = (float) ($overview['awaiting_reimbursement_amount'] ?? 0);
    $summary['total_trips'] = (int) ($overview['total_trip_count'] ?? 0);
}

$topCategories = fetch_all(
    'SELECT category_name, expense_count, total_amount
     FROM vw_analytics_category_summary
     WHERE user_id = ?
     ORDER BY total_amount DESC, expense_count DESC, category_name ASC
     LIMIT 6',
    'i',
    [$userId]
);

$topMerchants = fetch_all(
    'SELECT merchant_name, expense_count, total_amount
     FROM vw_analytics_merchant_summary
     WHERE user_id = ?
     ORDER BY total_amount DESC, expense_count DESC, merchant_name ASC
     LIMIT 6',
    'i',
    [$userId]
);

$activityFeed = fetch_all(
    'SELECT activity_type, activity_label, activity_status, activity_amount, activity_date
     FROM vw_analytics_activity_feed
     WHERE user_id = ?
     ORDER BY COALESCE(activity_date, DATE(created_at)) DESC, source_id DESC
     LIMIT 8',
    'i',
    [$userId]
);

$expenseReports = [
    ['label' => 'Expense Details', 'desc' => 'Run a detailed expense report with receipt-level drilldowns.', 'href' => '#', 'icon' => 'fa-regular fa-file-lines'],
    ['label' => 'Expenses by Category', 'desc' => 'Compare spend across categories for the selected period.', 'href' => '#', 'icon' => 'fa-solid fa-layer-group'],
    ['label' => 'Expenses by Attendee', 'desc' => 'Review shared and attendee-based spending quickly.', 'href' => '#', 'icon' => 'fa-regular fa-user'],
    ['label' => 'Expenses by Customer', 'desc' => 'Track customer-billable expense totals.', 'href' => '#', 'icon' => 'fa-regular fa-address-card'],
    ['label' => 'Expenses by Project', 'desc' => 'See spend linked to projects and internal workstreams.', 'href' => '#', 'icon' => 'fa-solid fa-diagram-project'],
    ['label' => 'Expenses by Merchant', 'desc' => 'Group spend by merchant to spot recurring vendors.', 'href' => '#', 'icon' => 'fa-solid fa-store'],
    ['label' => 'Expenses by Currency', 'desc' => 'Break down spend by currency across your workspace.', 'href' => '#', 'icon' => 'fa-solid fa-coins'],
];

$reportCards = [
    ['label' => 'Expense Reports Details', 'desc' => 'View submitted reports, totals, and approval state.', 'href' => '#', 'icon' => 'fa-regular fa-folder-open'],
    ['label' => 'Policy Violations', 'desc' => 'Highlight reports that violate policy rules.', 'href' => '#', 'icon' => 'fa-solid fa-triangle-exclamation'],
];

$tripCards = [
    ['label' => 'Trip Details', 'desc' => 'Review all created trips with travel status.', 'href' => '#', 'icon' => 'fa-solid fa-suitcase'],
    ['label' => 'Trip Stage Summary', 'desc' => 'Summarize trips by lifecycle stage.', 'href' => '#', 'icon' => 'fa-solid fa-route'],
    ['label' => 'Trip Expense Summary', 'desc' => 'See expense totals connected to each trip.', 'href' => '#', 'icon' => 'fa-solid fa-receipt'],
    ['label' => 'Trip Summary by Report Status', 'desc' => 'Track trips against linked report progress.', 'href' => '#', 'icon' => 'fa-solid fa-chart-pie'],
];

$activityCards = [
    ['label' => 'Activity Logs', 'desc' => 'Audit recent workspace activity and updates.', 'href' => '#', 'icon' => 'fa-regular fa-clock'],
];

render_expense_shell_start('Analytics | Expense', 'dashboard-page analytics-page', 'analytics');
?>
<div class="page-surface analytics-surface">
    <header class="analytics-header">
        <div>
            <h1>Analytics</h1>
            <p>Know how much you’ve spent on business expenses by running analytics based on various parameters.</p>
        </div>
        <label class="analytics-search">
            <span>Search reports</span>
            <div class="analytics-search-box">
                <input type="search" placeholder="Search reports" aria-label="Search reports">
                <i class="fa-solid fa-chevron-down" aria-hidden="true"></i>
            </div>
        </label>
    </header>

    <section class="analytics-summary-strip">
        <article class="analytics-summary-pill">
            <strong><?= (int) $summary['pending_approval'] ?></strong>
            <span>Pending approvals</span>
        </article>
        <article class="analytics-summary-pill">
            <strong><?= e(html_entity_decode('&#8377;') . number_format((float) $summary['unreported_advances_amount'], 2)) ?></strong>
            <span>Total spend</span>
        </article>
        <article class="analytics-summary-pill">
            <strong><?= (int) $summary['total_trips'] ?></strong>
            <span>Total trips</span>
        </article>
        <article class="analytics-summary-pill">
            <strong><?= (int) $summary['awaiting_approval_reports'] ?></strong>
            <span>Reports awaiting approval</span>
        </article>
    </section>

    <section class="analytics-grid">
        <article class="analytics-card analytics-card--wide">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-regular fa-folder-open" aria-hidden="true"></i>
                    <h2>Expenses</h2>
                </div>
                <p>Know how much you’ve spent on business expenses by running analytics based on various parameters.</p>
            </header>
            <div class="analytics-link-grid">
                <?php foreach ($expenseReports as $item): ?>
                    <a class="analytics-link-item" href="<?= e($item['href']) ?>">
                        <i class="<?= e($item['icon']) ?>" aria-hidden="true"></i>
                        <span>
                            <strong><?= e($item['label']) ?></strong>
                            <small><?= e($item['desc']) ?></small>
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="analytics-card">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-regular fa-file-lines" aria-hidden="true"></i>
                    <h2>Reports</h2>
                </div>
                <p>View statistics of the expense reports you’ve created and resolve policy violations in your reports.</p>
            </header>
            <div class="analytics-link-list">
                <?php foreach ($reportCards as $item): ?>
                    <a class="analytics-link-item" href="<?= e($item['href']) ?>">
                        <i class="<?= e($item['icon']) ?>" aria-hidden="true"></i>
                        <span>
                            <strong><?= e($item['label']) ?></strong>
                            <small><?= e($item['desc']) ?></small>
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="analytics-card">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-regular fa-folder-open" aria-hidden="true"></i>
                    <h2>Trips</h2>
                </div>
                <p>Get a summary of the business trips you’ve undertaken and the statuses of your trips and trip reports.</p>
            </header>
            <div class="analytics-link-list">
                <?php foreach ($tripCards as $item): ?>
                    <a class="analytics-link-item" href="<?= e($item['href']) ?>">
                        <i class="<?= e($item['icon']) ?>" aria-hidden="true"></i>
                        <span>
                            <strong><?= e($item['label']) ?></strong>
                            <small><?= e($item['desc']) ?></small>
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="analytics-card analytics-card--activity">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-regular fa-clock" aria-hidden="true"></i>
                    <h2>Activity</h2>
                </div>
                <p>View all the activities you’ve performed in Zoho Expense for a particular period.</p>
            </header>
            <div class="analytics-link-list">
                <?php foreach ($activityCards as $item): ?>
                    <a class="analytics-link-item" href="<?= e($item['href']) ?>">
                        <i class="<?= e($item['icon']) ?>" aria-hidden="true"></i>
                        <span>
                            <strong><?= e($item['label']) ?></strong>
                            <small><?= e($item['desc']) ?></small>
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>
    </section>

    <section class="analytics-insights">
        <article class="analytics-card analytics-insight-card">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-solid fa-layer-group" aria-hidden="true"></i>
                    <h2>Top Categories</h2>
                </div>
            </header>
            <div class="analytics-insight-list">
                <?php if (!empty($topCategories)): ?>
                    <?php foreach ($topCategories as $category): ?>
                        <div class="analytics-insight-row">
                            <div>
                                <strong><?= e((string) ($category['category_name'] ?? 'Uncategorized')) ?></strong>
                                <small><?= (int) ($category['expense_count'] ?? 0) ?> expenses</small>
                            </div>
                            <span><?= e(html_entity_decode('&#8377;') . number_format((float) ($category['total_amount'] ?? 0), 2)) ?></span>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="analytics-insight-empty">No expense categories yet</div>
                <?php endif; ?>
            </div>
        </article>

        <article class="analytics-card analytics-insight-card">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-solid fa-clock-rotate-left" aria-hidden="true"></i>
                    <h2>Recent Activity</h2>
                </div>
            </header>
            <div class="analytics-insight-list">
                <?php if (!empty($activityFeed)): ?>
                    <?php foreach ($activityFeed as $activity): ?>
                        <div class="analytics-insight-row">
                            <div>
                                <strong><?= e((string) ($activity['activity_label'] ?? 'Activity')) ?></strong>
                                <small><?= e(ucfirst(str_replace('_', ' ', (string) ($activity['activity_type'] ?? 'item')))) ?> - <?= e((string) ($activity['activity_status'] ?? '')) ?></small>
                            </div>
                            <span>
                                <?php
                                $amount = (float) ($activity['activity_amount'] ?? 0);
                                echo $amount > 0 ? e(html_entity_decode('&#8377;') . number_format($amount, 2)) : e((string) ($activity['activity_date'] ?? '-'));
                                ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="analytics-insight-empty">No recent activity</div>
                <?php endif; ?>
            </div>
        </article>

        <article class="analytics-card analytics-insight-card">
            <header class="analytics-card-header">
                <div>
                    <i class="fa-solid fa-store" aria-hidden="true"></i>
                    <h2>Top Merchants</h2>
                </div>
            </header>
            <div class="analytics-insight-list">
                <?php if (!empty($topMerchants)): ?>
                    <?php foreach ($topMerchants as $merchant): ?>
                        <div class="analytics-insight-row">
                            <div>
                                <strong><?= e((string) ($merchant['merchant_name'] ?? 'Unknown Merchant')) ?></strong>
                                <small><?= (int) ($merchant['expense_count'] ?? 0) ?> expenses</small>
                            </div>
                            <span><?= e(html_entity_decode('&#8377;') . number_format((float) ($merchant['total_amount'] ?? 0), 2)) ?></span>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="analytics-insight-empty">No merchants found yet</div>
                <?php endif; ?>
            </div>
        </article>
    </section>
</div>
<?php render_expense_shell_end(); ?>
