<?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;
}

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

/* =========================================================
   ACCESSIBLE BRANCHES
========================================================= */

$accessibleBranches = getAccessibleBranches($pdo);

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

$placeholders = implode(',', array_fill(0, count($accessibleBranches), '?'));

/* =========================================================
   FETCH ALL SYSTEM ACTIONS (NO APPROVAL LOGIC)
========================================================= */

$sql = "
    SELECT sa.*,
           b.bill_number,
           c.name,
           u1.username AS requested_by_user,
           u2.username AS handled_by_user
    FROM system_actions sa
    JOIN bills b ON sa.bill_id = b.bill_id
    JOIN customers c ON b.customer_id = c.customer_id
    LEFT JOIN users u1 ON sa.created_by = u1.id
    LEFT JOIN users u2 ON sa.handled_by = u2.id
";

if (!$isAdmin) {
    $sql .= " WHERE sa.branch_id IN ($placeholders)";
}

$sql .= " ORDER BY sa.created_at DESC";

$stmt = $pdo->prepare($sql);

if (!$isAdmin) {
    $stmt->execute($accessibleBranches);
} else {
    $stmt->execute();
}

$actions = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div style="padding:30px; max-width:1100px; margin:auto;">

<h2>System Activity History</h2>

<?php if (!$actions): ?>
    <p style="color:green;">No activity recorded.</p>
<?php else: ?>

<table class="data-table">
<thead>
<tr>
    <th>Bill</th>
    <th>Customer</th>
    <th>Action</th>
    <th>Requested By</th>
    <th>Requested At</th>
    <th>Handled By</th>
    <th>Status</th>
    <th>Handled At</th>
</tr>
</thead>
<tbody>

<?php foreach ($actions as $a): ?>
<tr>
    <td><?= htmlspecialchars($a['bill_number']) ?></td>
    <td><?= htmlspecialchars($a['name']) ?></td>
    <td><?= htmlspecialchars($a['action_type']) ?></td>
    <td><?= htmlspecialchars($a['requested_by_user'] ?? '-') ?></td>
    <td><?= htmlspecialchars($a['created_at']) ?></td>
    <td><?= htmlspecialchars($a['handled_by_user'] ?? '-') ?></td>
    <td><?= htmlspecialchars($a['status']) ?></td>
    <td><?= htmlspecialchars($a['handled_at'] ?? '-') ?></td>
</tr>
<?php endforeach; ?>

</tbody>
</table>

<?php endif; ?>

</div>

<style>
.data-table { width:100%; border-collapse: collapse; margin-top:20px; }
.data-table th, .data-table td { border:1px solid #ddd; padding:10px; text-align:center; }
.data-table th { background:#f5f5f5; }
</style>

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