<?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 approvals_money(float $amount): string
{
    return html_entity_decode('&#8377;') . number_format($amount, 2);
}

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

$summary = [
    'pending_trips' => 0,
    'pending_reports' => 0,
];

$overview = fetch_one(
    'SELECT pending_trip_count, pending_report_count
     FROM vw_approvals_overview
     WHERE user_id = ?',
    'i',
    [$userId]
);

if ($overview) {
    $summary['pending_trips'] = (int) ($overview['pending_trip_count'] ?? 0);
    $summary['pending_reports'] = (int) ($overview['pending_report_count'] ?? 0);
}

$pendingTrips = fetch_all(
    'SELECT
        id,
        submitter_name,
        trip_number,
        trip_details,
        COALESCE(destination, "") AS destination,
        COALESCE(status, "") AS status,
        start_date,
        end_date,
        created_at
     FROM vw_approvals_pending_trips
     WHERE user_id = ?
     ORDER BY COALESCE(created_at, start_date) DESC, id DESC',
    'i',
    [$userId]
);

$pendingReports = fetch_all(
    'SELECT
        id,
        submitter_name,
        report_number,
        report_name,
        status,
        total_amount,
        currency_code,
        submitted_at,
        created_at,
        to_be_reimbursed
     FROM vw_approvals_pending_reports
     WHERE user_id = ?
     ORDER BY COALESCE(submitted_at, created_at) DESC, id DESC',
    'i',
    [$userId]
);

$pendingApprovalTrips = array_slice($pendingTrips, 0, 5);
$pendingApprovalReports = array_slice($pendingReports, 0, 5);

$tripRows = fetch_all(
    'SELECT
        id,
        submitter_name,
        trip_number,
        trip_details,
        COALESCE(destination, "") AS destination,
        COALESCE(status, "") AS status,
        start_date,
        end_date,
        created_at
     FROM vw_approvals_pending_trips
     WHERE user_id = ?
     ORDER BY COALESCE(created_at, start_date) DESC, id DESC',
    'i',
    [$userId]
);

$reportRows = fetch_all(
    'SELECT
        id,
        submitter_name,
        report_number,
        report_name,
        status,
        total_amount,
        currency_code,
        submitted_at,
        created_at,
        to_be_reimbursed
     FROM vw_approvals_pending_reports
     WHERE user_id = ?
     ORDER BY COALESCE(created_at, submitted_at) DESC, id DESC',
    'i',
    [$userId]
);

render_expense_shell_start('Approvals | Expense', 'dashboard-page approvals-page', 'approvals');
?>
<div class="page-surface approvals-surface">
    <header class="approvals-hero">
        <div>
            <p class="approvals-kicker">Pending Approval</p>
            <h1>Approvals</h1>
            <p class="approvals-lead">Review trips and reports waiting on your action, then move them forward with a quick approve or reject flow.</p>
        </div>
        <div class="approvals-hero-stats">
            <article class="approvals-stat-card">
                <span class="approvals-stat-value"><?= (int) $summary['pending_trips'] ?></span>
                <span class="approvals-stat-label">Pending Trips</span>
            </article>
            <article class="approvals-stat-card">
                <span class="approvals-stat-value"><?= (int) $summary['pending_reports'] ?></span>
                <span class="approvals-stat-label">Pending Reports</span>
            </article>
        </div>
    </header>

    <nav class="approvals-tabs" data-approval-tabs aria-label="Approval views">
        <button type="button" class="approvals-tab is-active" data-approval-tab="pending">Pending Approval</button>
        <button type="button" class="approvals-tab" data-approval-tab="trips">Trips</button>
        <button type="button" class="approvals-tab" data-approval-tab="reports">Reports</button>
    </nav>

    <section class="approvals-panel is-active" data-approval-panel="pending">
        <div class="approvals-summary-grid">
            <article class="approvals-summary-card">
                <header class="approvals-summary-card-head">
                    <div>
                        <span class="approvals-summary-count"><?= (int) $summary['pending_trips'] ?></span>
                        <h2>Pending Trips</h2>
                    </div>
                </header>
                <div class="approvals-summary-body">
                    <?php if (!empty($pendingApprovalTrips)): ?>
                        <?php foreach ($pendingApprovalTrips as $trip): ?>
                            <article class="approvals-mini-row">
                                <div>
                                    <strong><?= e(trim((string) ($trip['trip_details'] ?? ''))) ?: 'Trip' ?></strong>
                                    <span><?= e(trim((string) ($trip['destination'] ?? ''))) ?: 'Destination pending' ?></span>
                                </div>
                                <small><?= e(approvals_format_date((string) ($trip['created_at'] ?? ''))) ?></small>
                            </article>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="approvals-empty-state">
                            <p>No trips pending approval</p>
                        </div>
                    <?php endif; ?>
                </div>
            </article>

            <article class="approvals-summary-card">
                <header class="approvals-summary-card-head">
                    <div>
                        <span class="approvals-summary-count"><?= (int) $summary['pending_reports'] ?></span>
                        <h2>Pending Reports</h2>
                    </div>
                </header>
                <div class="approvals-summary-body">
                    <?php if (!empty($pendingApprovalReports)): ?>
                        <?php foreach ($pendingApprovalReports as $report): ?>
                            <article class="approvals-mini-row">
                                <div>
                                    <strong><?= e(trim((string) ($report['report_name'] ?? ''))) ?: 'Report' ?></strong>
                                    <span><?= e(ucfirst(str_replace('_', ' ', (string) ($report['status'] ?? '')))) ?></span>
                                </div>
                                <small><?= e(approvals_money((float) ($report['total_amount'] ?? 0))) ?></small>
                            </article>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="approvals-empty-state">
                            <p>No reports pending approval</p>
                        </div>
                    <?php endif; ?>
                </div>
            </article>
        </div>
    </section>

    <section class="approvals-panel" data-approval-panel="trips">
        <div class="approvals-list-toolbar">
            <div>
                <h2>Pending Trips</h2>
                <p><?= (int) $summary['pending_trips'] ?> trips need review</p>
            </div>
            <details class="approvals-sort">
                <summary>
                    Sort By
                    <i class="fa-solid fa-ellipsis" aria-hidden="true"></i>
                </summary>
                <div class="approvals-sort-menu">
                    <span>Created Time</span>
                    <span>Submitter</span>
                    <span>Submitted Date</span>
                    <span>Trip#</span>
                    <span>Trip Details</span>
                    <span>Status</span>
                    <button type="button">Refresh List</button>
                </div>
            </details>
        </div>

        <div class="approvals-table-wrap">
            <table class="approvals-table">
                <thead>
                    <tr>
                        <th>Submitter</th>
                        <th>Trip#</th>
                        <th>Trip Details</th>
                        <th>Destination</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($tripRows)): ?>
                        <?php foreach ($tripRows as $trip): ?>
                            <tr>
                                <td><?= e(trim((string) ($trip['submitter_name'] ?? ($_SESSION['user_company'] ?? $_SESSION['user'] ?? 'Expense user')))) ?></td>
                                <td><?= e((string) ($trip['trip_number'] ?? ('TR-' . str_pad((string) ((int) ($trip['id'] ?? 0)), 4, '0', STR_PAD_LEFT)))) ?></td>
                                <td>
                                    <strong><?= e(trim((string) ($trip['trip_details'] ?? ''))) ?: 'Trip' ?></strong>
                                    <span><?= e(approvals_format_date((string) ($trip['start_date'] ?? ''))) ?> - <?= e(approvals_format_date((string) ($trip['end_date'] ?? ''))) ?></span>
                                </td>
                                <td><?= e(trim((string) ($trip['destination'] ?? ''))) ?: '-' ?></td>
                                <td><span class="approvals-status approvals-status--pending"><?= e(ucfirst((string) ($trip['status'] ?? 'pending'))) ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5">
                                <div class="approvals-empty-table">No trips pending approval</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>

    <section class="approvals-panel" data-approval-panel="reports">
        <div class="approvals-list-toolbar">
            <div>
                <h2>Pending Reports</h2>
                <p><?= (int) $summary['pending_reports'] ?> reports need review</p>
            </div>
            <details class="approvals-sort">
                <summary>
                    Sort By
                    <i class="fa-solid fa-ellipsis" aria-hidden="true"></i>
                </summary>
                <div class="approvals-sort-menu">
                    <span>Created Time</span>
                    <span>Submitter</span>
                    <span>Submitted Date</span>
                    <span>Report#</span>
                    <span>Report Name</span>
                    <span>Status</span>
                    <span>Total</span>
                    <span>To Be Reimbursed</span>
                    <button type="button">Refresh List</button>
                </div>
            </details>
        </div>

        <div class="approvals-table-wrap">
            <table class="approvals-table approvals-table--reports">
                <thead>
                    <tr>
                        <th>Submitter</th>
                        <th>Report#</th>
                        <th>Report Name</th>
                        <th>Status</th>
                        <th>Total</th>
                        <th>To Be Reimbursed</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($reportRows)): ?>
                        <?php foreach ($reportRows as $report): ?>
                            <tr>
                                <td><?= e(trim((string) ($report['submitter_name'] ?? ($_SESSION['user_company'] ?? $_SESSION['user'] ?? 'Expense user')))) ?></td>
                                <td><?= e((string) ($report['report_number'] ?? ('RP-' . str_pad((string) ((int) ($report['id'] ?? 0)), 4, '0', STR_PAD_LEFT)))) ?></td>
                                <td>
                                    <strong><?= e(trim((string) ($report['report_name'] ?? ''))) ?: 'Report' ?></strong>
                                    <span><?= e(approvals_format_date((string) ($report['submitted_at'] ?? $report['created_at'] ?? ''))) ?></span>
                                </td>
                                <td><span class="approvals-status approvals-status--pending"><?= e(ucfirst(str_replace('_', ' ', (string) ($report['status'] ?? 'pending')))) ?></span></td>
                                <td><?= e(approvals_money((float) ($report['total_amount'] ?? 0))) ?></td>
                                <td><?= e(approvals_money((float) ($report['to_be_reimbursed'] ?? 0))) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6">
                                <div class="approvals-empty-table">No reports pending approval</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>
<?php render_expense_shell_end(); ?>
