<?php
session_start();

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

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

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

expense_flow_ensure_schema();

function expenses_board_url(array $params = []): string
{
    $merged = array_merge($_GET, $params);
    foreach ($merged as $key => $value) {
        if ($value === null || $value === '') {
            unset($merged[$key]);
        }
    }

    $query = http_build_query($merged);
    return page_url('expenses', $query);
}

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

    $ts = strtotime($value);
    return $ts ? date('d/m/Y', $ts) : $value;
}

function expenses_board_avatar(string $path): string
{
    $path = trim($path);
    if ($path === '') {
        return asset_url('images/img1.jpg');
    }

    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }

    return asset_url(ltrim($path, '/'));
}

$view = strtolower(trim((string) ($_GET['view'] ?? 'pending')));
if (!in_array($view, ['pending', 'all'], true)) {
    $view = 'pending';
}

$sortColumn = trim((string) ($_GET['sort_column'] ?? 'date'));
$sortOrder = strtoupper(trim((string) ($_GET['sort_order'] ?? 'D')));
$sortMap = [
    'date' => 'COALESCE(i.expense_date, i.created_at)',
    'merchant' => 'i.merchant_name',
    'category' => 'i.category_name',
    'amount' => 'i.amount',
    'report' => 'r.report_title',
];

if (!isset($sortMap[$sortColumn])) {
    $sortColumn = 'date';
}
if ($sortOrder !== 'A' && $sortOrder !== 'D') {
    $sortOrder = 'D';
}

$sortSql = $sortMap[$sortColumn] . ' ' . ($sortOrder === 'A' ? 'ASC' : 'DESC') . ', i.id DESC';

$items = fetch_all(
    'SELECT
        i.id,
        i.report_id,
        i.trip_id,
        i.expense_title,
        i.merchant_name,
        i.category_name,
        i.amount,
        i.currency_code,
        i.expense_date,
        i.claim_reimbursement,
        i.description,
        i.reference_no,
        i.receipt_path,
        i.created_at,
        COALESCE(r.report_title, "") AS report_title,
        COALESCE(r.report_status, "") AS report_status,
        COALESCE(t.trip_name, "") AS trip_name
     FROM expense_report_items i
     LEFT JOIN expense_reports r
       ON r.id = i.report_id
      AND r.user_id = i.user_id
      AND r.is_deleted = 0
      AND r.deleted_at IS NULL
     LEFT JOIN expense_trips t
       ON t.id = i.trip_id
      AND COALESCE(t.is_deleted, 0) = 0
     WHERE i.user_id = ?
       AND i.is_deleted = 0
       AND i.deleted_at IS NULL
     ORDER BY ' . $sortSql,
    'i',
    [$userId]
);

$pendingItems = array_values(array_filter(
    $items,
    static fn(array $item): bool => (int) ($item['report_id'] ?? 0) <= 0
));
$visibleItems = $view === 'all' ? $items : $pendingItems;

$totalAmount = 0.0;
$reimbursableAmount = 0.0;
$reportedCount = 0;
foreach ($items as $item) {
    $amount = (float) ($item['amount'] ?? 0);
    $totalAmount += $amount;
    if ((int) ($item['claim_reimbursement'] ?? 1) === 1) {
        $reimbursableAmount += $amount;
    }
    if ((int) ($item['report_id'] ?? 0) > 0) {
        $reportedCount++;
    }
}

$message = flash('expense_success');
$error = flash('expense_error');

render_expense_shell_start('Expenses | Expense', 'dashboard-page expense-page expenses-board-page', 'expenses');
?>
<div class="page-surface page-surface--white expenses-board-shell">
    <?php if ($message !== null): ?>
        <div class="expense-banner expense-banner--success"><?= e($message) ?></div>
    <?php endif; ?>
    <?php if ($error !== null): ?>
        <div class="expense-banner expense-banner--error"><?= e($error) ?></div>
    <?php endif; ?>

    <header class="reports-table-toolbar expenses-board-toolbar">
        <div class="reports-table-heading">
            <h1><?= e($view === 'all' ? 'All Expenses' : 'Unreported Expenses') ?></h1>
            <div class="reports-table-tabs">
                <a class="reports-table-tab<?= $view === 'pending' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['view' => 'pending'])) ?>">Pending Expenses</a>
                <a class="reports-table-tab<?= $view === 'all' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['view' => 'all'])) ?>">All Expenses</a>
            </div>
            <button type="button" class="reports-table-tab-caret" aria-label="More expense filters">
                <i class="fa-solid fa-caret-down" aria-hidden="true"></i>
            </button>
        </div>

        <div class="reports-table-actions">
            <a class="trip-primary reports-table-new" href="<?= e(route_url('expenses/new/')) ?>">+ New Expense</a>
            <div class="reports-more-menu" data-topbar-popover>
                <button type="button" class="reports-table-icon-btn" aria-label="More" data-topbar-toggle aria-expanded="false">
                    <i class="fa-solid fa-ellipsis" aria-hidden="true"></i>
                </button>
                <div class="topbar-popover-menu reports-more-popover" data-topbar-menu aria-hidden="true">
                    <div class="reports-more-heading">SORT BY</div>
                    <a class="reports-more-item<?= $sortColumn === 'date' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['sort_column' => 'date', 'sort_order' => $sortColumn === 'date' && $sortOrder === 'A' ? 'D' : 'A'])) ?>">Expense Date</a>
                    <a class="reports-more-item<?= $sortColumn === 'merchant' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['sort_column' => 'merchant', 'sort_order' => $sortColumn === 'merchant' && $sortOrder === 'A' ? 'D' : 'A'])) ?>">Merchant</a>
                    <a class="reports-more-item<?= $sortColumn === 'category' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['sort_column' => 'category', 'sort_order' => $sortColumn === 'category' && $sortOrder === 'A' ? 'D' : 'A'])) ?>">Category</a>
                    <a class="reports-more-item<?= $sortColumn === 'amount' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['sort_column' => 'amount', 'sort_order' => $sortColumn === 'amount' && $sortOrder === 'A' ? 'D' : 'A'])) ?>">Amount</a>
                    <a class="reports-more-item<?= $sortColumn === 'report' ? ' is-active' : '' ?>" href="<?= e(expenses_board_url(['sort_column' => 'report', 'sort_order' => $sortColumn === 'report' && $sortOrder === 'A' ? 'D' : 'A'])) ?>">Report</a>
                    <div class="reports-more-divider"></div>
                    <a class="reports-more-action" href="<?= e(expenses_board_url(['view' => $view, 'sort_column' => null, 'sort_order' => null])) ?>">
                        <i class="fa-solid fa-rotate-right" aria-hidden="true"></i>
                        <span>Refresh List</span>
                    </a>
                    <a class="reports-more-action" href="<?= e(route_url('expenses/new/transactions/')) ?>">
                        <i class="fa-regular fa-credit-card" aria-hidden="true"></i>
                        <span>From Cards</span>
                    </a>
                </div>
            </div>
            <button type="button" class="reports-table-help-btn" aria-label="Help">?</button>
        </div>
    </header>

    <section class="expenses-board-summary">
        <article class="expenses-summary-card">
            <span>Total Expenses</span>
            <strong><?= e((string) count($items)) ?></strong>
            <small><?= e(expense_flow_format_money($totalAmount, 'INR')) ?></small>
        </article>
        <article class="expenses-summary-card">
            <span>Unreported</span>
            <strong><?= e((string) count($pendingItems)) ?></strong>
            <small>Ready to add to a report</small>
        </article>
        <article class="expenses-summary-card">
            <span>Reported</span>
            <strong><?= e((string) $reportedCount) ?></strong>
            <small>Already attached to reports</small>
        </article>
        <article class="expenses-summary-card">
            <span>Reimbursable</span>
            <strong><?= e(expense_flow_format_money($reimbursableAmount, 'INR')) ?></strong>
            <small>Claimable amount</small>
        </article>
    </section>

    <section class="expenses-board-list">
        <?php if ($visibleItems === []): ?>
            <div class="expenses-board-empty">
                <div class="expenses-board-empty-icon">
                    <i class="fa-regular fa-receipt" aria-hidden="true"></i>
                </div>
                <h2><?= e($view === 'all' ? 'No expenses yet' : 'No unreported expenses right now') ?></h2>
                <p><?= e($view === 'all' ? 'Start by recording your first expense or matching a card transaction.' : 'Every recorded expense is already linked to a report.') ?></p>
                <div class="expenses-board-empty-actions">
                    <a class="expense-primary" href="<?= e(route_url('expenses/new/')) ?>">+ New Expense</a>
                    <a class="expense-secondary" href="<?= e(route_url('expenses/new/transactions/')) ?>">From Cards</a>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($visibleItems as $item): ?>
                <?php
                    $expenseId = (int) ($item['id'] ?? 0);
                    $title = trim((string) ($item['category_name'] ?? '')) ?: trim((string) ($item['expense_title'] ?? 'Expense')) ?: 'Expense';
                    $merchant = trim((string) ($item['merchant_name'] ?? ''));
                    $reportTitle = trim((string) ($item['report_title'] ?? ''));
                    $tripName = trim((string) ($item['trip_name'] ?? ''));
                    $receiptPath = trim((string) ($item['receipt_path'] ?? ''));
                    $receiptUrl = $receiptPath !== '' ? asset_url(ltrim($receiptPath, '/')) : '';
                    $receiptExt = strtolower(pathinfo($receiptPath, PATHINFO_EXTENSION));
                    $isReceiptImage = in_array($receiptExt, ['jpg', 'jpeg', 'png', 'webp', 'gif'], true);
                ?>
                <article class="report-expense-card expenses-board-card">
                    <label class="report-expense-check">
                        <input type="checkbox" aria-label="Select expense <?= e($title) ?>">
                    </label>
                    <div class="report-expense-thumb">
                        <?php if ($receiptUrl !== '' && $isReceiptImage): ?>
                            <img src="<?= e($receiptUrl) ?>" alt="Receipt preview">
                        <?php else: ?>
                            <span><?= e($receiptExt !== '' ? strtoupper($receiptExt) : 'NO RECEIPT') ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="report-expense-copy">
                        <span><?= e(expenses_board_date((string) ($item['expense_date'] ?? $item['created_at'] ?? ''))) ?></span>
                        <strong><?= e($title) ?></strong>
                        <div class="report-expense-meta">
                            <a href="<?= e(route_url('expenses/view/?expense_id=' . $expenseId)) ?>"><?= e($merchant !== '' ? $merchant : 'View expense') ?></a>
                            <?php if ((int) ($item['claim_reimbursement'] ?? 1) === 1): ?>
                                <span class="report-expense-flag">R</span>
                            <?php endif; ?>
                        </div>
                        <p class="expenses-board-card-meta">
                            <span><?= e($reportTitle !== '' ? $reportTitle : 'Unreported') ?></span>
                            <span><?= e($tripName !== '' ? $tripName : 'No trip linked') ?></span>
                        </p>
                        <?php if (trim((string) ($item['description'] ?? '')) !== ''): ?>
                            <p><?= e((string) ($item['description'] ?? '')) ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="report-expense-side">
                        <div class="report-expense-amount"><?= e(expense_flow_format_money((float) ($item['amount'] ?? 0), (string) ($item['currency_code'] ?? 'INR'))) ?></div>
                        <div class="report-expense-tools">
                            <a class="report-expense-tool" href="<?= e(route_url('expenses/view/?expense_id=' . $expenseId)) ?>" aria-label="View expense">
                                <i class="fa-solid fa-magnifying-glass-plus" aria-hidden="true"></i>
                            </a>
                            <a class="report-expense-tool" href="<?= e(route_url('expenses/new/?expense_id=' . $expenseId . '&edit=1')) ?>" aria-label="Edit expense">
                                <i class="fa-regular fa-pen-to-square" aria-hidden="true"></i>
                            </a>
                            <a class="report-expense-tool report-expense-tool--more" href="<?= e(route_url('reports/new/' . ($expenseId > 0 ? '?expense_id=' . $expenseId : ''))) ?>" aria-label="Create report">
                                <i class="fa-regular fa-folder-open" aria-hidden="true"></i>
                            </a>
                        </div>
                    </div>
                </article>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>
</div>
<?php render_expense_shell_end(); ?>
