<?php
require_once __DIR__ . '/includes/layout.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'transaksi_log_pengguna', 'read');

$search = trim($_GET['search'] ?? '');
$filterYear = trim($_GET['tahun'] ?? '');
$filterMonth = trim($_GET['bulan'] ?? '');
$filterDate = trim($_GET['tarikh'] ?? '');

$whereClauses = [];
$types = '';
$params = [];

if ($search !== '') {
    $searchLike = '%' . $search . '%';
    $whereClauses[] = "(nama LIKE ? OR jabatan LIKE ? OR role LIKE ? OR operasi LIKE ?)";
    $types .= 'ssss';
    array_push($params, $searchLike, $searchLike, $searchLike, $searchLike);
}

if ($filterYear !== '' && ctype_digit($filterYear)) {
    $whereClauses[] = "YEAR(created_at) = ?";
    $types .= 'i';
    $params[] = (int) $filterYear;
}

if ($filterMonth !== '' && ctype_digit($filterMonth)) {
    $whereClauses[] = "MONTH(created_at) = ?";
    $types .= 'i';
    $params[] = (int) $filterMonth;
}

if ($filterDate !== '') {
    $whereClauses[] = "DATE(created_at) = ?";
    $types .= 's';
    $params[] = $filterDate;
}

$sql = "
    SELECT id, nama, jabatan, role, operasi, created_at
    FROM user_transaction_logs
";

if (!empty($whereClauses)) {
    $sql .= ' WHERE ' . implode(' AND ', $whereClauses);
}

$sql .= ' ORDER BY created_at DESC, id DESC';

$yearResult = $conn->query("SELECT DISTINCT YEAR(created_at) AS tahun FROM user_transaction_logs ORDER BY tahun DESC");
$years = $yearResult ? array_column($yearResult->fetch_all(MYSQLI_ASSOC), 'tahun') : [];

if (!empty($whereClauses)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $logs = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
} else {
    $result = $conn->query($sql);
    $logs = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}

render_layout_start('Transaksi Log Pengguna - Dashboard Audit MAINPP');
?>
<div class="page-card">
    <h3><i class="fa-solid fa-clock-rotate-left"></i> Transaksi Log Pengguna</h3>
    <form method="GET" class="search-form">
        <div class="search-input-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" name="search" class="search-input" placeholder="Cari nama, bahagian, role atau operasi" value="<?= htmlspecialchars($search) ?>">
        </div>
        <select name="tahun">
            <option value="">Semua Tahun</option>
            <?php foreach ($years as $year): ?>
                <option value="<?= htmlspecialchars((string) $year) ?>" <?= $filterYear === (string) $year ? 'selected' : '' ?>><?= htmlspecialchars((string) $year) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="bulan">
            <option value="">Semua Bulan</option>
            <?php for ($month = 1; $month <= 12; $month++): ?>
                <option value="<?= $month ?>" <?= $filterMonth === (string) $month ? 'selected' : '' ?>><?= date('F', mktime(0, 0, 0, $month, 1)) ?></option>
            <?php endfor; ?>
        </select>
        <input type="date" name="tarikh" value="<?= htmlspecialchars($filterDate) ?>" style="max-width:180px;">
        <button type="submit" class="search-btn">Cari</button>
        <a href="transaksi_log_pengguna.php" class="reset-btn">Reset</a>
    </form>
</div>

<div class="table-container">
    <table>
        <thead>
            <tr>
                <th>Bil</th>
                <th>Nama</th>
                <th>Bahagian</th>
                <th>Role</th>
                <th>Tarikh</th>
                <th>Masa</th>
                <th>Operasi</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($logs)): ?>
                <?php $bil = 1; foreach ($logs as $log): ?>
                <tr>
                    <td><?= $bil++ ?></td>
                    <td><strong><?= htmlspecialchars($log['nama']) ?></strong></td>
                    <td><?= htmlspecialchars($log['jabatan']) ?></td>
                    <td><span class="role-badge"><i class="fa-solid fa-user-shield"></i><?= htmlspecialchars($log['role']) ?></span></td>
                    <td><?= date('d/m/Y', strtotime($log['created_at'])) ?></td>
                    <td><?= date('h:i A', strtotime($log['created_at'])) ?></td>
                    <td><?= htmlspecialchars($log['operasi']) ?></td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
            <tr>
                <td colspan="7" class="empty-state">Tiada transaksi log pengguna ditemui.</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>
<?php render_layout_end(); ?>
