<?php
/**
 * guest_audit_viewer.php
 * Upload to the application root beside login.php.
 */
require_once __DIR__ . '/includes/bootstrap.php';
require_login();

function gav_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$orderId = max(0, (int)($_GET['order_id'] ?? 0));
$userId  = max(0, (int)($_GET['user_id'] ?? 0));
$event   = trim((string)($_GET['event_type'] ?? ''));
$dateFrom = trim((string)($_GET['date_from'] ?? ''));
$dateTo   = trim((string)($_GET['date_to'] ?? ''));
$limit = (int)($_GET['limit'] ?? 200);
$limit = max(25, min(1000, $limit));

$where = [];
$params = [];
if ($orderId > 0) { $where[] = 'a.order_id = :order_id'; $params[':order_id'] = $orderId; }
if ($userId > 0) { $where[] = 'a.app_user_id = :user_id'; $params[':user_id'] = $userId; }
if ($event !== '') { $where[] = 'a.event_type = :event_type'; $params[':event_type'] = $event; }
if ($dateFrom !== '') { $where[] = 'a.changed_at >= :date_from'; $params[':date_from'] = substr($dateFrom,0,10) . ' 00:00:00'; }
if ($dateTo !== '') { $where[] = 'a.changed_at < DATE_ADD(:date_to, INTERVAL 1 DAY)'; $params[':date_to'] = substr($dateTo,0,10); }

$sql = "SELECT a.* FROM guest_change_audit a";
if ($where) $sql .= ' WHERE ' . implode(' AND ', $where);
$sql .= ' ORDER BY a.id DESC LIMIT ' . $limit;

$rows = [];
$error = '';
try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$eventTypes = [];
try {
    $eventTypes = $pdo->query("SELECT DISTINCT event_type FROM guest_change_audit ORDER BY event_type")->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Guest Change Audit</title>
<style>
body{margin:0;background:#eef3f8;color:#162033;font-family:Inter,Arial,sans-serif}.wrap{max-width:1500px;margin:24px auto;padding:0 18px}.head{display:flex;justify-content:space-between;align-items:end;gap:16px;margin-bottom:16px}.head h1{margin:0}.muted{color:#64748b}.card{background:#fff;border-radius:15px;box-shadow:0 10px 30px rgba(15,23,42,.08);padding:18px;margin-bottom:16px}.filters{display:grid;grid-template-columns:repeat(6,minmax(120px,1fr));gap:10px;align-items:end}label{font-size:12px;font-weight:800;color:#475569;display:block;margin-bottom:5px}input,select,button{width:100%;box-sizing:border-box;padding:10px 11px;border:1px solid #cbd5e1;border-radius:9px;background:#fff}button{background:#0f172a;color:#fff;font-weight:800;cursor:pointer}.tablebox{overflow:auto}table{width:100%;border-collapse:collapse;min-width:1350px}th,td{padding:10px;border-bottom:1px solid #e2e8f0;text-align:left;vertical-align:top;font-size:13px}th{background:#f8fafc;position:sticky;top:0;z-index:1}.event{font-weight:800}.name-old{color:#b91c1c}.name-new{color:#047857}.uri{max-width:300px;word-break:break-word}.empty{padding:35px;text-align:center;color:#64748b}.error{background:#fff1f2;border:1px solid #fecdd3;color:#9f1239;padding:12px;border-radius:9px}@media(max-width:1000px){.filters{grid-template-columns:repeat(2,1fr)}}
</style>
</head><body><div class="wrap">
<div class="head"><div><h1>Guest Change Audit</h1><div class="muted">Every booking guest link, guest name and room occupant change.</div></div><div class="muted"><?php echo count($rows); ?> rows shown</div></div>
<div class="card"><form method="get" class="filters">
<div><label>Order ID</label><input type="number" name="order_id" value="<?php echo $orderId ?: ''; ?>"></div>
<div><label>User ID</label><input type="number" name="user_id" value="<?php echo $userId ?: ''; ?>"></div>
<div><label>Event</label><select name="event_type"><option value="">All events</option><?php foreach($eventTypes as $t): ?><option value="<?php echo gav_h($t); ?>" <?php echo $event===$t?'selected':''; ?>><?php echo gav_h($t); ?></option><?php endforeach; ?></select></div>
<div><label>From</label><input type="date" name="date_from" value="<?php echo gav_h($dateFrom); ?>"></div>
<div><label>To</label><input type="date" name="date_to" value="<?php echo gav_h($dateTo); ?>"></div>
<div><label>Rows</label><select name="limit"><?php foreach([50,100,200,500,1000] as $n): ?><option value="<?php echo $n; ?>" <?php echo $limit===$n?'selected':''; ?>><?php echo $n; ?></option><?php endforeach; ?></select></div>
<div><button type="submit">Apply filters</button></div>
</form></div>
<div class="card tablebox">
<?php if($error): ?><div class="error"><?php echo gav_h($error); ?></div>
<?php elseif(!$rows): ?><div class="empty">No guest changes match the selected filters.</div>
<?php else: ?><table><thead><tr><th>Date/time</th><th>Event</th><th>Order</th><th>Guest row</th><th>Old name</th><th>New name</th><th>User</th><th>Page</th><th>Request</th><th>Session / IP</th></tr></thead><tbody>
<?php foreach($rows as $r): ?>
<tr>
<td><?php echo gav_h($r['changed_at']); ?><br><span class="muted">#<?php echo (int)$r['id']; ?></span></td>
<td class="event"><?php echo gav_h($r['event_type']); ?><br><span class="muted"><?php echo gav_h($r['source_table']); ?> #<?php echo gav_h($r['source_row_id']); ?></span></td>
<td><?php echo gav_h($r['order_id']); ?><?php if(!empty($r['affected_order_ids'])): ?><br><span class="muted">Affected: <?php echo gav_h($r['affected_order_ids']); ?></span><?php endif; ?></td>
<td><?php echo gav_h($r['guest_id']); ?><?php if($r['old_guest_id']!==null || $r['new_guest_id']!==null): ?><br><span class="muted"><?php echo gav_h($r['old_guest_id']); ?> → <?php echo gav_h($r['new_guest_id']); ?></span><?php endif; ?></td>
<td class="name-old"><?php echo gav_h($r['old_full_name']); ?></td>
<td class="name-new"><?php echo gav_h($r['new_full_name']); ?></td>
<td><?php echo gav_h($r['app_username'] ?: 'System/API'); ?><br><span class="muted">ID <?php echo gav_h($r['app_user_id']); ?></span></td>
<td><?php echo gav_h($r['script_name']); ?><br><span class="muted"><?php echo gav_h($r['request_method']); ?></span></td>
<td class="uri"><?php echo gav_h($r['request_uri']); ?><br><span class="muted">Request: <?php echo gav_h($r['request_id']); ?></span></td>
<td><?php echo gav_h($r['session_id']); ?><br><span class="muted"><?php echo gav_h($r['ip_address']); ?></span></td>
</tr>
<?php endforeach; ?></tbody></table><?php endif; ?>
</div></div></body></html>
