<?php
session_start();

require_once '../includes/functions.php';
require_once '../includes/db.php';

requireLogin();

$isAdmin = isAdmin();
$isManager = isManager();

if (!$isAdmin && !$isManager) {
    header('Location: /pages/dashboard.php');
    exit;
}

$accessibleBranches = getAccessibleBranches($pdo);
if (empty($accessibleBranches)) {
    die('No branch access assigned.');
}

$placeholders = implode(',', array_fill(0, count($accessibleBranches), '?'));
$branchStmt = $pdo->prepare("
    SELECT id, branch_name
    FROM branches
    WHERE id IN ($placeholders)
    ORDER BY branch_name ASC
");
$branchStmt->execute($accessibleBranches);
$branchList = $branchStmt->fetchAll(PDO::FETCH_ASSOC);

$search = trim($_GET['search'] ?? '');
$date = trim($_GET['date'] ?? '');
$branch = $_GET['branch'] ?? 'all';

$params = [];
$where = [];

if ($branch !== 'all') {
    $branch = (int)$branch;
    if (!in_array($branch, $accessibleBranches, true)) {
        die('Unauthorized branch access.');
    }
    $where[] = 'a.branch_id = ?';
    $params[] = $branch;
} else {
    $where[] = "a.branch_id IN ($placeholders)";
    $params = array_merge($params, $accessibleBranches);
}

if ($search !== '') {
    $where[] = '(a.details LIKE ? OR a.action LIKE ? OR COALESCE(b.bill_number, b2.bill_number) LIKE ?)';
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
    $params[] = "%{$search}%";
}

if ($date !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    $where[] = 'DATE(a.created_at) = ?';
    $params[] = $date;
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $pdo->prepare("
    SELECT 
        a.created_at,
        a.action,
        a.branch_id,
        br.branch_name,
        a.details,
        u.username,
        COALESCE(b.bill_number, b2.bill_number) AS bill_number
    FROM audit_logs a
    LEFT JOIN users u ON a.user_id = u.id
    LEFT JOIN branches br ON a.branch_id = br.id
    LEFT JOIN bills b ON a.table_name = 'bills' AND a.record_id = b.bill_id
    LEFT JOIN payments p ON a.table_name = 'payments' AND a.record_id = p.payment_id
    LEFT JOIN bills b2 ON p.bill_id = b2.bill_id
    $whereSql
    ORDER BY a.created_at DESC
    LIMIT 500
");
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

$actionCounts = [];
foreach ($logs as $log) {
    $action = $log['action'] ?: 'SYSTEM';
    $actionCounts[$action] = ($actionCounts[$action] ?? 0) + 1;
}
arsort($actionCounts);
$topActions = array_slice($actionCounts, 0, 3, true);

include '../includes/header.php';
?>

<section class="summary-strip mb-4">
    <div class="summary-card">
        <div class="label">Visible Logs</div>
        <div class="value"><?= count($logs) ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Branch Filter</div>
        <div class="value"><?= $branch === 'all' ? 'All' : htmlspecialchars((string)$branch) ?></div>
    </div>
    <div class="summary-card">
        <div class="label">Top Action</div>
        <div class="value"><?= htmlspecialchars((string)(array_key_first($topActions) ?: 'None')) ?></div>
    </div>
</section>

<section class="app-card p-4">
    <div class="page-toolbar">
        <div>
            <span class="app-eyebrow">Audit</span>
            <h2 class="mb-1">Audit logs</h2>
            <p class="text-muted mb-0">Filter the last 500 audit events by branch, date, bill, or action details.</p>
        </div>
    </div>

    <form method="GET" class="stack-form mb-4">
        <div class="form-grid">
            <div>
                <label class="form-label fw-semibold">Branch</label>
                <select class="form-select" name="branch">
                    <option value="all">All accessible branches</option>
                    <?php foreach ($branchList as $item): ?>
                        <option value="<?= (int)$item['id'] ?>" <?= (string)$branch === (string)$item['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($item['branch_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="form-label fw-semibold">Search</label>
                <input class="form-control" type="text" name="search" placeholder="Action, details, or bill number" value="<?= htmlspecialchars($search) ?>">
            </div>
            <div>
                <label class="form-label fw-semibold">Date</label>
                <input class="form-control" type="date" name="date" value="<?= htmlspecialchars($date) ?>">
            </div>
            <div class="d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-retro">Filter</button>
                <a href="/pages/audit_logs.php" class="btn btn-outline-secondary rounded-pill px-4">Reset</a>
            </div>
        </div>
    </form>

    <?php if (empty($logs)): ?>
        <div class="empty-state">No audit log entries matched the current filters.</div>
    <?php else: ?>
        <div class="table-responsive-wrap">
            <table class="table table-card align-middle">
                <thead>
                    <tr>
                        <th>Date / Time</th>
                        <th>Bill #</th>
                        <th>Branch</th>
                        <th>Action</th>
                        <th>User</th>
                        <th>Details</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($logs as $log): ?>
                        <?php
                        $actionMap = [
                            'BILL_CANCELLED' => 'BILL CANCEL',
                            'PAYMENT_DELETED' => 'PAYMENT CANCEL',
                        ];
                        $actionLabel = $actionMap[$log['action']] ?? $log['action'];
                        ?>
                        <tr>
                            <td><?= htmlspecialchars($log['created_at']) ?></td>
                            <td><?= htmlspecialchars($log['bill_number'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($log['branch_name'] ?? 'Unknown') ?></td>
                            <td><?= htmlspecialchars($actionLabel ?: 'SYSTEM') ?></td>
                            <td><?= htmlspecialchars($log['username'] ?? 'System') ?></td>
                            <td><?= htmlspecialchars($log['details'] ?? '-') ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<?php include '../includes/footer.php'; ?>
