<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Audit Log';

$allowedTypes = ['master', 'manager', 'accounts','2'];
$currentType = strtolower(trim((string)($_SESSION['type'] ?? '')));
if (!in_array($currentType, $allowedTypes, true)) {
    http_response_code(403);
    exit('You are not allowed to view audit logs.');
}

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('build_page_url')) {
    function build_page_url(array $baseParams, int $pageNo): string
    {
        $baseParams['page'] = $pageNo;
        return 'audit_log.php?' . http_build_query($baseParams);
    }
}

$properties = $pdo->query("
    SELECT id, name, code
    FROM properties
    WHERE is_active = 1
    ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$propertyId = (int)($_GET['property_id'] ?? 0);
$orderId    = (int)($_GET['order_id'] ?? 0);
$actionType = trim((string)($_GET['action_type'] ?? ''));
$userType   = trim((string)($_GET['user_type'] ?? ''));
$dateFrom   = trim((string)($_GET['date_from'] ?? ''));
$dateTo     = trim((string)($_GET['date_to'] ?? ''));
$q          = trim((string)($_GET['q'] ?? ''));
$export     = (int)($_GET['export'] ?? 0);

$page       = max(1, (int)($_GET['page'] ?? 1));
$perPage    = (int)($_GET['per_page'] ?? 25);
$allowedPerPage = [25, 50, 100, 200];
if (!in_array($perPage, $allowedPerPage, true)) {
    $perPage = 25;
}
$offset = ($page - 1) * $perPage;

$actionTypes = [
    'void_payment',
    'reverse_folio_transaction',
    'lock_pricing',
    'unlock_pricing',
    'rebuild_folio_charges',
    'manual_extra_posted'
];

$userTypes = ['master', 'manager', 'accounts'];

/*
   If your auth table is not `users`, change this join.
   Example:
   LEFT JOIN tbluser u ON u.id = l.action_by
*/
$fromSql = "
    FROM payment_audit_log l
    LEFT JOIN orders o ON o.id = l.order_id
    LEFT JOIN properties p ON p.id = l.property_id
    LEFT JOIN users u ON u.id = l.action_by
    WHERE 1=1
";
$params = [];

if ($propertyId > 0) {
    $fromSql .= " AND l.property_id = :property_id ";
    $params[':property_id'] = $propertyId;
}

if ($orderId > 0) {
    $fromSql .= " AND l.order_id = :order_id ";
    $params[':order_id'] = $orderId;
}

if ($actionType !== '') {
    $fromSql .= " AND l.action_type = :action_type ";
    $params[':action_type'] = $actionType;
}

if ($userType !== '') {
    $fromSql .= " AND l.action_by_type = :user_type ";
    $params[':user_type'] = $userType;
}

if ($dateFrom !== '') {
    $fromSql .= " AND DATE(l.action_at) >= :date_from ";
    $params[':date_from'] = $dateFrom;
}

if ($dateTo !== '') {
    $fromSql .= " AND DATE(l.action_at) <= :date_to ";
    $params[':date_to'] = $dateTo;
}

if ($q !== '') {
    $fromSql .= "
        AND (
            l.action_type LIKE :q
            OR l.action_reason LIKE :q
            OR l.payload_json LIKE :q
            OR o.order_no LIKE :q
            OR p.name LIKE :q
            OR p.code LIKE :q
            OR CONCAT(COALESCE(u.firstname,''), ' ', COALESCE(u.lastname,'')) LIKE :q
            OR u.name LIKE :q
        )
    ";
    $params[':q'] = '%' . $q . '%';
}

/* ---------------------------------
   Count total rows for pagination
--------------------------------- */
$countSql = "SELECT COUNT(*) " . $fromSql;
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$totalRows = (int)$stmt->fetchColumn();

$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

/* ---------------------------------
   Main select
--------------------------------- */
$selectSql = "
    SELECT
        l.*,
        o.order_no,
        p.name AS property_name,
        p.code AS property_code,
        COALESCE(
            NULLIF(TRIM(CONCAT(COALESCE(u.firstname,''), ' ', COALESCE(u.lastname,''))), ''),
            NULLIF(u.firstname, ''),
            CONCAT('User #', COALESCE(l.action_by, 0))
        ) AS action_by_name
" . $fromSql . "
    ORDER BY l.action_at DESC, l.id DESC
";

if (!$export) {
    $selectSql .= " LIMIT :limit OFFSET :offset ";
}

$stmt = $pdo->prepare($selectSql);
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}
if (!$export) {
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
}
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ---------------------------------
   Export CSV
--------------------------------- */
if ($export === 1) {
    $filename = 'global_audit_log_' . date('Ymd_His') . '.csv';

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');

    fputcsv($out, [
        'ID',
        'Action Date',
        'Action Type',
        'Reason',
        'Done By',
        'User Type',
        'Property',
        'Order ID',
        'Order No',
        'Folio ID',
        'Payment ID',
        'Folio Transaction ID',
        'Payload JSON'
    ]);

    foreach ($rows as $row) {
        $propertyLabel = trim((string)($row['property_name'] ?? ''));
        if (!empty($row['property_code'])) {
            $propertyLabel .= ($propertyLabel !== '' ? ' - ' : '') . $row['property_code'];
        }

        fputcsv($out, [
            (int)($row['id'] ?? 0),
            (string)($row['action_at'] ?? ''),
            (string)($row['action_type'] ?? ''),
            (string)($row['action_reason'] ?? ''),
            (string)($row['action_by_name'] ?? ''),
            (string)($row['action_by_type'] ?? ''),
            $propertyLabel,
            (int)($row['order_id'] ?? 0),
            (string)($row['order_no'] ?? ''),
            (int)($row['folio_id'] ?? 0),
            (int)($row['payment_id'] ?? 0),
            (int)($row['folio_transaction_id'] ?? 0),
            (string)($row['payload_json'] ?? ''),
        ]);
    }

    fclose($out);
    exit;
}

/* ---------------------------------
   Summary cards
--------------------------------- */
$monthStart = date('Y-m-01');
$today = date('Y-m-d');

$summaryWhere = " WHERE 1=1 ";
$summaryParams = [];

if ($propertyId > 0) {
    $summaryWhere .= " AND property_id = :s_property_id ";
    $summaryParams[':s_property_id'] = $propertyId;
}

if ($userType !== '') {
    $summaryWhere .= " AND action_by_type = :s_user_type ";
    $summaryParams[':s_user_type'] = $userType;
}

$summary = [
    'filtered_total'       => $totalRows,
    'voids_this_month'     => 0,
    'reversals_this_month' => 0,
    'actions_today'        => 0,
    'top_user_type'        => '-',
    'top_user_type_count'  => 0,
];

$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM payment_audit_log
    $summaryWhere
      AND action_type = 'void_payment'
      AND DATE(action_at) >= :month_start
");
$tmpParams = $summaryParams;
$tmpParams[':month_start'] = $monthStart;
$stmt->execute($tmpParams);
$summary['voids_this_month'] = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM payment_audit_log
    $summaryWhere
      AND action_type = 'reverse_folio_transaction'
      AND DATE(action_at) >= :month_start
");
$tmpParams = $summaryParams;
$tmpParams[':month_start'] = $monthStart;
$stmt->execute($tmpParams);
$summary['reversals_this_month'] = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM payment_audit_log
    $summaryWhere
      AND DATE(action_at) = :today
");
$tmpParams = $summaryParams;
$tmpParams[':today'] = $today;
$stmt->execute($tmpParams);
$summary['actions_today'] = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT action_by_type, COUNT(*) AS total_count
    FROM payment_audit_log
    $summaryWhere
      AND action_by_type IS NOT NULL
      AND action_by_type <> ''
      AND DATE(action_at) >= :month_start
    GROUP BY action_by_type
    ORDER BY total_count DESC, action_by_type ASC
    LIMIT 1
");
$tmpParams = $summaryParams;
$tmpParams[':month_start'] = $monthStart;
$stmt->execute($tmpParams);
$topUserType = $stmt->fetch(PDO::FETCH_ASSOC);

if ($topUserType) {
    $summary['top_user_type'] = (string)$topUserType['action_by_type'];
    $summary['top_user_type_count'] = (int)$topUserType['total_count'];
}

/* ---------------------------------
   30-day trend data
--------------------------------- */
$trendDays = 30;
$trendStart = date('Y-m-d', strtotime('-29 days'));
$trendEnd   = date('Y-m-d');

$trendWhere = " WHERE DATE(action_at) BETWEEN :trend_start AND :trend_end ";
$trendParams = [
    ':trend_start' => $trendStart,
    ':trend_end'   => $trendEnd,
];

if ($propertyId > 0) {
    $trendWhere .= " AND property_id = :trend_property_id ";
    $trendParams[':trend_property_id'] = $propertyId;
}
if ($userType !== '') {
    $trendWhere .= " AND action_by_type = :trend_user_type ";
    $trendParams[':trend_user_type'] = $userType;
}

$trendMap = [];
for ($i = 0; $i < $trendDays; $i++) {
    $d = date('Y-m-d', strtotime($trendStart . ' +' . $i . ' days'));
    $trendMap[$d] = [
        'date'      => $d,
        'total'     => 0,
        'voids'     => 0,
        'reversals' => 0,
    ];
}

$stmt = $pdo->prepare("
    SELECT DATE(action_at) AS d, COUNT(*) AS total_count
    FROM payment_audit_log
    $trendWhere
    GROUP BY DATE(action_at)
    ORDER BY DATE(action_at) ASC
");
$stmt->execute($trendParams);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $d = (string)$row['d'];
    if (isset($trendMap[$d])) {
        $trendMap[$d]['total'] = (int)$row['total_count'];
    }
}

$stmt = $pdo->prepare("
    SELECT DATE(action_at) AS d, COUNT(*) AS total_count
    FROM payment_audit_log
    $trendWhere
      AND action_type = 'void_payment'
    GROUP BY DATE(action_at)
    ORDER BY DATE(action_at) ASC
");
$stmt->execute($trendParams);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $d = (string)$row['d'];
    if (isset($trendMap[$d])) {
        $trendMap[$d]['voids'] = (int)$row['total_count'];
    }
}

$stmt = $pdo->prepare("
    SELECT DATE(action_at) AS d, COUNT(*) AS total_count
    FROM payment_audit_log
    $trendWhere
      AND action_type = 'reverse_folio_transaction'
    GROUP BY DATE(action_at)
    ORDER BY DATE(action_at) ASC
");
$stmt->execute($trendParams);
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $d = (string)$row['d'];
    if (isset($trendMap[$d])) {
        $trendMap[$d]['reversals'] = (int)$row['total_count'];
    }
}

$trendRows = array_values($trendMap);

$peakTotal = 0;
$peakVoids = 0;
$peakReversals = 0;
foreach ($trendRows as $tr) {
    if ($tr['total'] > $peakTotal) $peakTotal = $tr['total'];
    if ($tr['voids'] > $peakVoids) $peakVoids = $tr['voids'];
    if ($tr['reversals'] > $peakReversals) $peakReversals = $tr['reversals'];
}

$queryParams = $_GET;
unset($queryParams['page'], $queryParams['export']);

$exportParams = $_GET;
$exportParams['export'] = 1;
unset($exportParams['page']);

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-shield-check"></i> Finance Control</div>
            <div class="hero-title mt-2">Global Audit Log</div>
            <div class="hero-subtitle mt-2">
                Review payment voids, folio reversals, pricing locks, and other sensitive financial actions across all bookings.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="audit_log.php?<?php echo h(http_build_query($exportParams)); ?>" class="btn btn-outline-light">
                <i class="bi bi-download me-2"></i>Export CSV
            </a>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="card panel-card h-100">
            <div class="card-body">
                <div class="text-muted small mb-1"><i class="bi bi-funnel me-1"></i>Filtered Results</div>
                <div class="fs-3 fw-bold"><?php echo number_format($summary['filtered_total']); ?></div>
                <div class="small text-muted">Current search result count</div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="card panel-card h-100">
            <div class="card-body">
                <div class="text-muted small mb-1"><i class="bi bi-x-circle me-1"></i>Voids This Month</div>
                <div class="fs-3 fw-bold text-danger"><?php echo number_format($summary['voids_this_month']); ?></div>
                <div class="small text-muted">Payment void actions since <?php echo h($monthStart); ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="card panel-card h-100">
            <div class="card-body">
                <div class="text-muted small mb-1"><i class="bi bi-arrow-left-right me-1"></i>Reversals This Month</div>
                <div class="fs-3 fw-bold text-warning"><?php echo number_format($summary['reversals_this_month']); ?></div>
                <div class="small text-muted">Folio transaction reversals</div>
            </div>
        </div>
    </div>

    <div class="col-md-6 col-xl-3">
        <div class="card panel-card h-100">
            <div class="card-body">
                <div class="text-muted small mb-1"><i class="bi bi-calendar-day me-1"></i>Actions Today</div>
                <div class="fs-3 fw-bold text-primary"><?php echo number_format($summary['actions_today']); ?></div>
                <div class="small text-muted">All logged actions for today</div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-6 col-xl-4">
        <div class="card panel-card h-100">
            <div class="card-body">
                <div class="text-muted small mb-1"><i class="bi bi-people me-1"></i>Top User Type This Month</div>
                <div class="fs-4 fw-bold"><?php echo h($summary['top_user_type']); ?></div>
                <div class="small text-muted">
                    <?php echo number_format($summary['top_user_type_count']); ?> action(s) this month
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card mb-4">
    <div class="card-header">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
            <h5 class="mb-0">30-Day Audit Trends</h5>
            <span class="small text-muted">
                <?php echo h($trendStart); ?> to <?php echo h($trendEnd); ?>
            </span>
        </div>
    </div>
    <div class="card-body">
        <div class="mb-4">
            <div class="small text-muted mb-2">
                Totals by day. Blue = all actions, Red = voids, Yellow = reversals.
            </div>

            <div class="audit-trend-chart">
                <?php foreach ($trendRows as $row): ?>
                    <?php
                    $totalHeight = $peakTotal > 0 ? max(4, ($row['total'] / $peakTotal) * 120) : 4;
                    $voidHeight = $peakVoids > 0 ? max(4, ($row['voids'] / $peakVoids) * 120) : 4;
                    $revHeight = $peakReversals > 0 ? max(4, ($row['reversals'] / $peakReversals) * 120) : 4;
                    ?>
                    <div class="audit-trend-day" title="<?php echo h($row['date']); ?> | Total: <?php echo (int)$row['total']; ?> | Voids: <?php echo (int)$row['voids']; ?> | Reversals: <?php echo (int)$row['reversals']; ?>">
                        <div class="audit-trend-bars">
                            <div class="audit-bar audit-bar-total" style="height: <?php echo (float)$totalHeight; ?>px;"></div>
                            <div class="audit-bar audit-bar-void" style="height: <?php echo (float)$voidHeight; ?>px;"></div>
                            <div class="audit-bar audit-bar-reversal" style="height: <?php echo (float)$revHeight; ?>px;"></div>
                        </div>
                        <div class="audit-trend-label">
                            <?php echo h(date('d M', strtotime($row['date']))); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th class="text-end">Total Actions</th>
                        <th class="text-end">Void Payments</th>
                        <th class="text-end">Reversals</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach (array_reverse($trendRows) as $row): ?>
                        <tr>
                            <td><?php echo h(date('d M Y', strtotime($row['date']))); ?></td>
                            <td class="text-end fw-semibold"><?php echo (int)$row['total']; ?></td>
                            <td class="text-end text-danger"><?php echo (int)$row['voids']; ?></td>
                            <td class="text-end text-warning"><?php echo (int)$row['reversals']; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="card panel-card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-3">
                <label class="form-label">Property</label>
                <select name="property_id" class="form-select">
                    <option value="0">All properties</option>
                    <?php foreach ($properties as $p): ?>
                        <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyId === (int)$p['id'] ? 'selected' : ''; ?>>
                            <?php echo h($p['name']); ?> - <?php echo h($p['code']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">Order ID</label>
                <input type="number" name="order_id" class="form-control" value="<?php echo $orderId > 0 ? (int)$orderId : ''; ?>">
            </div>

            <div class="col-md-2">
                <label class="form-label">Action</label>
                <select name="action_type" class="form-select">
                    <option value="">All actions</option>
                    <?php foreach ($actionTypes as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $actionType === $type ? 'selected' : ''; ?>>
                            <?php echo h($type); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label">User Type</label>
                <select name="user_type" class="form-select">
                    <option value="">All user types</option>
                    <?php foreach ($userTypes as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $userType === $type ? 'selected' : ''; ?>>
                            <?php echo h($type); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-1">
                <label class="form-label">From</label>
                <input type="date" name="date_from" class="form-control" value="<?php echo h($dateFrom); ?>">
            </div>

            <div class="col-md-1">
                <label class="form-label">To</label>
                <input type="date" name="date_to" class="form-control" value="<?php echo h($dateTo); ?>">
            </div>

            <div class="col-md-3">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($q); ?>" placeholder="Reason, order no, user, payload...">
            </div>

            <div class="col-md-2">
                <label class="form-label">Per Page</label>
                <select name="per_page" class="form-select">
                    <?php foreach ($allowedPerPage as $pp): ?>
                        <option value="<?php echo $pp; ?>" <?php echo $perPage === $pp ? 'selected' : ''; ?>>
                            <?php echo $pp; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-4 d-flex gap-2">
                <button class="btn btn-primary">
                    <i class="bi bi-search me-2"></i>Filter
                </button>
                <a href="audit_log.php" class="btn btn-light">Reset</a>
            </div>
        </form>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Audit Entries</h5>
        <span class="badge text-bg-secondary">
            <?php echo number_format($totalRows); ?> record(s)
        </span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-modern align-middle mb-0">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Action</th>
                        <th>Property</th>
                        <th>Booking</th>
                        <th>Reason</th>
                        <th>Done By</th>
                        <th>User Type</th>
                        <th>Payment</th>
                        <th>Folio TX</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="10" class="text-center text-muted py-4">No audit log entries found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($rows as $row): ?>
                            <?php
                            $propertyLabel = trim((string)($row['property_name'] ?? ''));
                            if (!empty($row['property_code'])) {
                                $propertyLabel .= ($propertyLabel !== '' ? ' - ' : '') . $row['property_code'];
                            }

                            $doneBy = trim((string)($row['action_by_name'] ?? ''));
                            $userId = (int)($row['action_by'] ?? 0);
                            $reason = (string)($row['action_reason'] ?? '');
                            ?>
                            <tr>
                                <td><?php echo h($row['action_at']); ?></td>
                                <td><?php echo h($row['action_type']); ?></td>
                                <td><?php echo h($propertyLabel); ?></td>
                                <td>
                                    <div>ID <?php echo (int)($row['order_id'] ?? 0); ?></div>
                                    <div class="small text-muted"><?php echo h((string)($row['order_no'] ?? '')); ?></div>
                                </td>
                                <td><?php echo h(strlen($reason) > 50 ? substr($reason, 0, 50) . '...' : $reason); ?></td>
                                <td>
                                    <div><?php echo h($doneBy !== '' ? $doneBy : ('User #' . $userId)); ?></div>
                                    <div class="small text-muted">ID <?php echo $userId; ?></div>
                                </td>
                                <td><?php echo h((string)($row['action_by_type'] ?? '')); ?></td>
                                <td><?php echo (int)($row['payment_id'] ?? 0); ?></td>
                                <td><?php echo (int)($row['folio_transaction_id'] ?? 0); ?></td>
                                <td class="text-end">
                                    <div class="d-inline-flex gap-2">
                                        <?php if (!empty($row['order_id'])): ?>
                                            <a href="payments.php?order_id=<?php echo (int)$row['order_id']; ?>" class="btn btn-sm btn-outline-primary">
                                                Open Booking
                                            </a>
                                        <?php endif; ?>

                                        <?php if (!empty($row['payload_json'])): ?>
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-secondary btn-audit-details"
                                                    data-audit-action="<?php echo h((string)$row['action_type']); ?>"
                                                    data-audit-date="<?php echo h((string)$row['action_at']); ?>"
                                                    data-audit-reason="<?php echo h((string)$row['action_reason']); ?>"
                                                    data-audit-payload="<?php echo h((string)$row['payload_json']); ?>">
                                                Details
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if ($totalRows > 0): ?>
            <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 p-3 border-top">
                <div class="text-muted small">
                    Showing
                    <?php echo number_format($offset + 1); ?> -
                    <?php echo number_format(min($offset + $perPage, $totalRows)); ?>
                    of <?php echo number_format($totalRows); ?>
                </div>

                <nav aria-label="Audit pagination">
                    <ul class="pagination mb-0">
                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $page <= 1 ? '#' : h(build_page_url($queryParams, 1)); ?>">First</a>
                        </li>
                        <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $page <= 1 ? '#' : h(build_page_url($queryParams, $page - 1)); ?>">Prev</a>
                        </li>

                        <?php
                        $startPage = max(1, $page - 2);
                        $endPage = min($totalPages, $page + 2);
                        for ($p = $startPage; $p <= $endPage; $p++):
                        ?>
                            <li class="page-item <?php echo $p === $page ? 'active' : ''; ?>">
                                <a class="page-link" href="<?php echo h(build_page_url($queryParams, $p)); ?>">
                                    <?php echo $p; ?>
                                </a>
                            </li>
                        <?php endfor; ?>

                        <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $page >= $totalPages ? '#' : h(build_page_url($queryParams, $page + 1)); ?>">Next</a>
                        </li>
                        <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                            <a class="page-link" href="<?php echo $page >= $totalPages ? '#' : h(build_page_url($queryParams, $totalPages)); ?>">Last</a>
                        </li>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="auditDetailsModal" tabindex="-1" aria-labelledby="auditDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Audit Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <div><strong>Action:</strong> <span id="audit_details_action"></span></div>
                    <div><strong>Date:</strong> <span id="audit_details_date"></span></div>
                    <div><strong>Reason:</strong> <span id="audit_details_reason"></span></div>
                </div>

                <label class="form-label fw-semibold">Payload</label>
                <pre id="audit_details_payload"
                     class="bg-light border rounded p-3 small"
                     style="max-height: 420px; overflow:auto; white-space: pre-wrap; word-break: break-word;"></pre>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<style>
.audit-trend-chart{
    display:flex;
    align-items:flex-end;
    gap:8px;
    overflow-x:auto;
    padding:12px 4px 6px;
    border:1px solid #e9ecef;
    border-radius:14px;
    background:#fff;
}
.audit-trend-day{
    min-width:48px;
    text-align:center;
    flex:0 0 auto;
}
.audit-trend-bars{
    height:130px;
    display:flex;
    align-items:flex-end;
    justify-content:center;
    gap:4px;
    margin-bottom:8px;
}
.audit-bar{
    width:10px;
    border-radius:8px 8px 0 0;
    min-height:4px;
}
.audit-bar-total{
    background:#0d6efd;
}
.audit-bar-void{
    background:#dc3545;
}
.audit-bar-reversal{
    background:#ffc107;
}
.audit-trend-label{
    font-size:11px;
    color:#6c757d;
    line-height:1.2;
    white-space:nowrap;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var modalEl = document.getElementById('auditDetailsModal');
    if (!modalEl) return;

    var actionEl  = document.getElementById('audit_details_action');
    var dateEl    = document.getElementById('audit_details_date');
    var reasonEl  = document.getElementById('audit_details_reason');
    var payloadEl = document.getElementById('audit_details_payload');

    function prettyJson(input) {
        try {
            var obj = JSON.parse(input);
            return JSON.stringify(obj, null, 2);
        } catch (e) {
            return input || '';
        }
    }

    document.querySelectorAll('.btn-audit-details').forEach(function (btn) {
        btn.addEventListener('click', function () {
            actionEl.textContent = this.getAttribute('data-audit-action') || '';
            dateEl.textContent = this.getAttribute('data-audit-date') || '';
            reasonEl.textContent = this.getAttribute('data-audit-reason') || '-';
            payloadEl.textContent = prettyJson(this.getAttribute('data-audit-payload') || '');

            var modal = bootstrap.Modal.getOrCreateInstance(modalEl);
            modal.show();
        });
    });
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>