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

function reports_money(float $amount, string $currency = 'INR'): string
{
    $symbol = strtoupper(trim($currency)) === 'INR' ? html_entity_decode('&#8377;') : $currency . ' ';
    return $symbol . number_format($amount, 2);
}

function reports_format_date(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return '-';
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('d M Y', $timestamp) : $value;
}

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

$userContext = current_user_context();
$reportOwner = trim((string) ($userContext['display_name'] ?? ''));
if ($reportOwner === '') {
    $reportOwner = 'You';
}

$summary = [
    'total_reports' => 0,
    'draft_reports' => 0,
    'unsubmitted_reports' => 0,
    'awaiting_approval_reports' => 0,
    'awaiting_reimbursement_reports' => 0,
];

$overview = fetch_one(
    'SELECT
        COUNT(*) AS total_reports,
        SUM(CASE WHEN report_status = "draft" THEN 1 ELSE 0 END) AS draft_reports,
        SUM(CASE WHEN report_status = "unsubmitted" THEN 1 ELSE 0 END) AS unsubmitted_reports,
        SUM(CASE WHEN report_status = "awaiting_approval" THEN 1 ELSE 0 END) AS awaiting_approval_reports,
        SUM(CASE WHEN report_status = "awaiting_reimbursement" THEN 1 ELSE 0 END) AS awaiting_reimbursement_reports
     FROM expense_reports
     WHERE user_id = ?
       AND is_deleted = 0
       AND deleted_at IS NULL',
    'i',
    [$userId]
);

if ($overview) {
    $summary['total_reports'] = (int) ($overview['total_reports'] ?? 0);
    $summary['draft_reports'] = (int) ($overview['draft_reports'] ?? 0);
    $summary['unsubmitted_reports'] = (int) ($overview['unsubmitted_reports'] ?? 0);
    $summary['awaiting_approval_reports'] = (int) ($overview['awaiting_approval_reports'] ?? 0);
    $summary['awaiting_reimbursement_reports'] = (int) ($overview['awaiting_reimbursement_reports'] ?? 0);
}

$recentReports = fetch_all(
    'SELECT
        r.id,
        r.report_title,
        r.report_status,
        r.total_amount,
        r.currency_code,
        r.start_date,
        r.end_date,
        r.submitted_at,
        r.created_at,
        COALESCE(t.trip_name, "") AS trip_name
     FROM expense_reports r
     LEFT JOIN expense_trips t
       ON t.id = r.trip_id
      AND t.user_id = r.user_id
     WHERE r.user_id = ?
       AND r.is_deleted = 0
       AND r.deleted_at IS NULL
     ORDER BY COALESCE(r.submitted_at, r.created_at) DESC, r.id DESC
     LIMIT 8',
    'i',
    [$userId]
);

$featuredReport = $recentReports[0] ?? null;
$reportTabs = [
    ['key' => 'recent', 'label' => 'Recent', 'value' => (string) count($recentReports), 'active' => true],
    ['key' => 'drafts', 'label' => 'Drafts', 'value' => (string) $summary['draft_reports'], 'active' => false],
    ['key' => 'approval', 'label' => 'Approval', 'value' => (string) $summary['awaiting_approval_reports'], 'active' => false],
    ['key' => 'reimbursement', 'label' => 'Reimbursement', 'value' => (string) $summary['awaiting_reimbursement_reports'], 'active' => false],
];

render_expense_shell_start('Reports | Expense', 'dashboard-page reports-page', 'reports');
?>
<div class="page-surface page-surface--white">
    <section class="reports-start panel">
        <div class="reports-start-copy">
            <p class="reports-start-kicker">Reports</p>
            <h1>Get started with Reports</h1>
            <p class="reports-start-text">
                Create a report, group related expenses, and move them through approval and reimbursement.
            </p>
            <div class="reports-start-actions">
                <a class="trip-primary" href="<?= e(route_url('reports/new/')) ?>">+ New Report</a>
                <a class="trip-secondary" href="<?= e(route_url('reports/import/')) ?>">Import Reports</a>
            </div>
            <p class="reports-start-note">
                You currently have <?= (int) $summary['total_reports'] ?> report<?= $summary['total_reports'] === 1 ? '' : 's' ?> in the workspace.
            </p>
        </div>

        <div class="reports-start-preview">
            <div class="reports-start-preview-card panel">
                <div class="reports-start-preview-header">
                    <strong>Monthly Report (<?= e($reportOwner) ?>)</strong>
                    <span>Duration: <?= e(reports_format_date((string) ($featuredReport['start_date'] ?? '01/02/2025'))) ?> - <?= e(reports_format_date((string) ($featuredReport['end_date'] ?? '27/02/2025'))) ?></span>
                </div>

                <div class="reports-tabs" data-report-tabs>
                    <?php foreach ($reportTabs as $tab): ?>
                        <button
                            type="button"
                            class="report-tab<?= $tab['active'] ? ' is-active' : '' ?>"
                            data-report-tab="<?= e($tab['key']) ?>"
                        >
                            <span class="report-tab-label"><?= e($tab['label']) ?></span>
                            <span class="report-tab-value"><?= e($tab['value']) ?></span>
                        </button>
                    <?php endforeach; ?>
                </div>

                <div class="reports-body reports-start-panels" data-report-panels>
                    <div class="report-panel is-active" data-report-panel="recent">
                        <?php if ($featuredReport): ?>
                            <div class="reports-start-preview-entry">
                                <div class="reports-start-preview-thumb">
                                    <i class="fa-regular fa-file-lines" aria-hidden="true"></i>
                                </div>
                                <div class="reports-start-preview-details">
                                    <strong><?= e(trim((string) ($featuredReport['report_title'] ?? ''))) ?: 'Report' ?></strong>
                                    <span><?= e(reports_format_date((string) ($featuredReport['created_at'] ?? ''))) ?></span>
                                    <small><?= e(trim((string) ($featuredReport['trip_name'] ?? ''))) ?: 'No trip linked yet' ?></small>
                                </div>
                                <div class="reports-start-preview-amount">
                                    <?= e(reports_money((float) ($featuredReport['total_amount'] ?? 0), (string) ($featuredReport['currency_code'] ?? 'INR'))) ?>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="reports-start-empty">
                                <p>No reports yet. Create your first report to get started.</p>
                                <a class="empty-action" href="<?= e(route_url('reports/new/')) ?>">+ New Report</a>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="report-panel" data-report-panel="drafts">
                        <div class="reports-start-empty">
                            <p><?= (int) $summary['draft_reports'] ?> draft report<?= $summary['draft_reports'] === 1 ? '' : 's' ?> waiting to be completed.</p>
                            <a class="empty-action" href="<?= e(route_url('reports/new/')) ?>">Finish a draft</a>
                        </div>
                    </div>

                    <div class="report-panel" data-report-panel="approval">
                        <div class="reports-start-empty">
                            <p><?= (int) $summary['awaiting_approval_reports'] ?> report<?= $summary['awaiting_approval_reports'] === 1 ? '' : 's' ?> waiting for approval.</p>
                            <a class="empty-action" href="<?= e(page_url('approvals')) ?>">Open approvals</a>
                        </div>
                    </div>

                    <div class="report-panel" data-report-panel="reimbursement">
                        <div class="reports-start-empty">
                            <p><?= (int) $summary['awaiting_reimbursement_reports'] ?> report<?= $summary['awaiting_reimbursement_reports'] === 1 ? '' : 's' ?> waiting for reimbursement.</p>
                            <a class="empty-action" href="<?= e(page_url('reports')) ?>">View reports</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="reports-workflow panel">
        <header class="reports-section-header">
            <h2>How It Works</h2>
        </header>
        <div class="reports-workflow-grid">
            <article class="reports-workflow-card">
                <div class="reports-workflow-icon"><i class="fa-regular fa-folder-open" aria-hidden="true"></i></div>
                <strong>Create report</strong>
            </article>
            <div class="reports-workflow-arrow">&rarr;</div>
            <article class="reports-workflow-card">
                <div class="reports-workflow-icon"><i class="fa-regular fa-credit-card" aria-hidden="true"></i></div>
                <strong>Add expenses</strong>
            </article>
            <div class="reports-workflow-arrow">&rarr;</div>
            <article class="reports-workflow-card">
                <div class="reports-workflow-icon"><i class="fa-regular fa-paper-plane" aria-hidden="true"></i></div>
                <strong>Submit for approval</strong>
            </article>
            <div class="reports-workflow-arrow">&rarr;</div>
            <article class="reports-workflow-card">
                <div class="reports-workflow-icon reports-workflow-icon--green"><i class="fa-solid fa-circle-check" aria-hidden="true"></i></div>
                <strong>Approve and reimburse</strong>
            </article>
        </div>
    </section>

    <section class="reports-more panel">
        <header class="reports-section-header reports-section-header--more">
            <h2>See what's more</h2>
        </header>
        <div class="reports-more-list">
            <article class="reports-more-item">
                <div class="reports-more-icon"><i class="fa-regular fa-folder-open" aria-hidden="true"></i></div>
                <div class="reports-more-copy">
                    <strong>View report history</strong>
                    <p>Keep track of report changes, submissions, and reimbursements from one place.</p>
                </div>
                <a href="<?= e(page_url('reports')) ?>">Open reports</a>
            </article>
            <article class="reports-more-item">
                <div class="reports-more-icon"><i class="fa-regular fa-comment-dots" aria-hidden="true"></i></div>
                <div class="reports-more-copy">
                    <strong>Recall submitted reports</strong>
                    <p>Update missing details after submission and send the report again when you are ready.</p>
                </div>
                <a href="<?= e(route_url('reports/new/')) ?>">Create report</a>
            </article>
            <article class="reports-more-item">
                <div class="reports-more-icon"><i class="fa-regular fa-pen-to-square" aria-hidden="true"></i></div>
                <div class="reports-more-copy">
                    <strong>Apply advances</strong>
                    <p>Attach advances to a report so reimbursement and settlement stay in sync.</p>
                </div>
                <a href="<?= e(route_url('advancepayments/gettingstarted/')) ?>">Open advances</a>
            </article>
            <article class="reports-more-item">
                <div class="reports-more-icon"><i class="fa-solid fa-wand-magic-sparkles" aria-hidden="true"></i></div>
                <div class="reports-more-copy">
                    <strong>Automated expense reports</strong>
                    <p>Create reports faster by letting expenses flow in automatically from receipts and cards.</p>
                </div>
                <a href="<?= e(route_url('expenses/new/')) ?>">Add expenses</a>
            </article>
        </div>
    </section>

    <section class="summary-grid reports-summary-grid">
        <article class="panel pending-panel">
            <h3>Report Summary</h3>
            <div class="pending-list">
                <div class="pending-item">
                    <div class="pending-label">
                        <i class="fa-regular fa-folder-open" aria-hidden="true"></i>
                        <span>Total Reports</span>
                    </div>
                    <strong><?= (int) $summary['total_reports'] ?></strong>
                </div>
                <div class="pending-item">
                    <div class="pending-label">
                        <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                        <span>Draft Reports</span>
                    </div>
                    <strong><?= (int) $summary['draft_reports'] ?></strong>
                </div>
                <div class="pending-item">
                    <div class="pending-label">
                        <i class="fa-regular fa-paper-plane" aria-hidden="true"></i>
                        <span>Unsubmitted</span>
                    </div>
                    <strong><?= (int) $summary['unsubmitted_reports'] ?></strong>
                </div>
            </div>
        </article>

        <article class="panel pending-panel">
            <h3>Workflow</h3>
            <div class="pending-list">
                <div class="pending-item">
                    <div class="pending-label">
                        <i class="fa-solid fa-circle-check" aria-hidden="true"></i>
                        <span>Awaiting Approval</span>
                    </div>
                    <strong><?= (int) $summary['awaiting_approval_reports'] ?></strong>
                </div>
                <div class="pending-item">
                    <div class="pending-label">
                        <i class="fa-solid fa-rotate" aria-hidden="true"></i>
                        <span>Awaiting Reimbursement</span>
                    </div>
                    <strong><?= (int) $summary['awaiting_reimbursement_reports'] ?></strong>
                </div>
                <a class="pending-item pending-item--link" href="<?= e(route_url('reports/new/')) ?>">
                    <div class="pending-label">
                        <i class="fa-solid fa-plus" aria-hidden="true"></i>
                        <span>Create a report</span>
                    </div>
                    <strong>Open</strong>
                </a>
            </div>
        </article>
    </section>

    <section class="reports-panel panel">
        <header class="panel-header">
            <h3>RECENT REPORTS</h3>
        </header>

        <div class="approvals-table-wrap">
            <table class="approvals-table approvals-table--reports">
                <thead>
                    <tr>
                        <th>Report</th>
                        <th>Trip</th>
                        <th>Dates</th>
                        <th>Status</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($recentReports)): ?>
                        <?php foreach ($recentReports as $report): ?>
                            <tr>
                                <td>
                                    <strong><?= e(trim((string) ($report['report_title'] ?? ''))) ?: 'Report' ?></strong>
                                    <span><?= e(reports_format_date((string) ($report['created_at'] ?? ''))) ?></span>
                                </td>
                                <td><?= e(trim((string) ($report['trip_name'] ?? ''))) ?: '-' ?></td>
                                <td>
                                    <strong><?= e(reports_format_date((string) ($report['start_date'] ?? ''))) ?> - <?= e(reports_format_date((string) ($report['end_date'] ?? ''))) ?></strong>
                                    <span><?= e(reports_format_date((string) ($report['submitted_at'] ?? ''))) ?></span>
                                </td>
                                <td><?= e(ucfirst(str_replace('_', ' ', (string) ($report['report_status'] ?? 'draft')))) ?></td>
                                <td><?= e(reports_money((float) ($report['total_amount'] ?? 0), (string) ($report['currency_code'] ?? 'INR'))) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5">
                                <div class="approvals-empty-table">No reports yet. Create your first report to get started.</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>
<?php render_expense_shell_end(); ?>
