<?php
// pengawas/logs/index.php
$pageTitle = 'Log Aktivitas';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya pengawas
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'pengawas') {
    // Redirect ke halaman login jika belum login atau bukan pengawas
    setFlash('login_required', 'Anda harus login sebagai pengawas untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Pagination
$current_page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 25;
$offset = ($current_page - 1) * $limit;

// Filter
$entity_type = isset($_GET['entity_type']) ? $_GET['entity_type'] : '';
$user_role = isset($_GET['user_role']) ? $_GET['user_role'] : '';
$tanggal_awal = isset($_GET['tanggal_awal']) ? $_GET['tanggal_awal'] : '';
$tanggal_akhir = isset($_GET['tanggal_akhir']) ? $_GET['tanggal_akhir'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

// Query untuk menghitung total log
$query_count = "SELECT COUNT(*) as total FROM logs l
                JOIN users u ON l.user_id = u.id
                WHERE 1=1";

$query_params = [];

if (!empty($entity_type)) {
    $query_count .= " AND l.entity_type = :entity_type";
    $query_params[':entity_type'] = $entity_type;
}

if (!empty($user_role)) {
    $query_count .= " AND u.role = :user_role";
    $query_params[':user_role'] = $user_role;
}

if (!empty($tanggal_awal)) {
    $query_count .= " AND DATE(l.created_at) >= :tanggal_awal";
    $query_params[':tanggal_awal'] = $tanggal_awal;
}

if (!empty($tanggal_akhir)) {
    $query_count .= " AND DATE(l.created_at) <= :tanggal_akhir";
    $query_params[':tanggal_akhir'] = $tanggal_akhir;
}

if (!empty($search)) {
    $query_count .= " AND (l.activity LIKE :search OR l.description LIKE :search OR u.nama_lengkap LIKE :search)";
    $query_params[':search'] = "%$search%";
}

$db->query($query_count);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$total_rows = $db->single()->total;
$total_pages = ceil($total_rows / $limit);

// Query untuk mengambil data log
$query = "SELECT l.*, u.nama_lengkap, u.role
          FROM logs l
          JOIN users u ON l.user_id = u.id
          WHERE 1=1";

if (!empty($entity_type)) {
    $query .= " AND l.entity_type = :entity_type";
}

if (!empty($user_role)) {
    $query .= " AND u.role = :user_role";
}

if (!empty($tanggal_awal)) {
    $query .= " AND DATE(l.created_at) >= :tanggal_awal";
}

if (!empty($tanggal_akhir)) {
    $query .= " AND DATE(l.created_at) <= :tanggal_akhir";
}

if (!empty($search)) {
    $query .= " AND (l.activity LIKE :search OR l.description LIKE :search OR u.nama_lengkap LIKE :search)";
}

$query .= " ORDER BY l.created_at DESC LIMIT :offset, :limit";

$db->query($query);
foreach ($query_params as $param => $value) {
    $db->bind($param, $value);
}
$db->bind(':offset', $offset, PDO::PARAM_INT);
$db->bind(':limit', $limit, PDO::PARAM_INT);
$logs = $db->resultSet();

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

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <!-- <li class="nav-item"> -->
                        <!-- <a class="nav-link" href="< ?= SITE_URL ?>/pengawas/audit/index.php"> -->
                            <!-- <i class="fas fa-search -dollar me-2"></i> -->
                            <!-- Audit Transaksi -->
                        <!-- </a> -->
                    <!-- </li> -->
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/laporan/index.php">
                            <i class="fas fa-file-alt me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/pengawas/logs/index.php">
                            <i class="fas fa-history me-2"></i>
                            Log Aktivitas
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Log Aktivitas</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="dropdown">
                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-file-export me-1"></i> Export
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/pengawas/logs/export.php?type=pdf<?= !empty($entity_type) ? '&entity_type=' . $entity_type : '' ?><?= !empty($user_role) ? '&user_role=' . $user_role : '' ?><?= !empty($tanggal_awal) ? '&tanggal_awal=' . $tanggal_awal : '' ?><?= !empty($tanggal_akhir) ? '&tanggal_akhir=' . $tanggal_akhir : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">PDF</a></li>
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/pengawas/logs/export.php?type=excel<?= !empty($entity_type) ? '&entity_type=' . $entity_type : '' ?><?= !empty($user_role) ? '&user_role=' . $user_role : '' ?><?= !empty($tanggal_awal) ? '&tanggal_awal=' . $tanggal_awal : '' ?><?= !empty($tanggal_akhir) ? '&tanggal_akhir=' . $tanggal_akhir : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Excel</a></li>
                        </ul>
                    </div>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Filter -->
            <div class="card mb-4">
                <div class="card-body">
                    <form action="" method="get" class="row g-3">
                        <div class="col-md-3">
                            <label for="entity_type" class="form-label">Jenis Entitas</label>
                            <select class="form-select" id="entity_type" name="entity_type">
                                <option value="">Semua Jenis</option>
                                <option value="kampanye" <?= $entity_type == 'kampanye' ? 'selected' : '' ?>>Kampanye</option>
                                <option value="donasi" <?= $entity_type == 'donasi' ? 'selected' : '' ?>>Donasi</option>
                                <option value="user" <?= $entity_type == 'user' ? 'selected' : '' ?>>User</option>
                                <option value="berita" <?= $entity_type == 'berita' ? 'selected' : '' ?>>Berita</option>
                                <option value="system" <?= $entity_type == 'system' ? 'selected' : '' ?>>Sistem</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="user_role" class="form-label">Role User</label>
                            <select class="form-select" id="user_role" name="user_role">
                                <option value="">Semua Role</option>
                                <option value="admin" <?= $user_role == 'admin' ? 'selected' : '' ?>>Admin</option>
                                <option value="ketua" <?= $user_role == 'ketua' ? 'selected' : '' ?>>Ketua</option>
                                <option value="bendahara" <?= $user_role == 'bendahara' ? 'selected' : '' ?>>Bendahara</option>
                                <option value="sekretaris" <?= $user_role == 'sekretaris' ? 'selected' : '' ?>>Sekretaris</option>
                                <option value="pengawas" <?= $user_role == 'pengawas' ? 'selected' : '' ?>>Pengawas</option>
                                <option value="donatur" <?= $user_role == 'donatur' ? 'selected' : '' ?>>Donatur</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="tanggal_awal" class="form-label">Tanggal Awal</label>
                            <input type="date" class="form-control" id="tanggal_awal" name="tanggal_awal" value="<?= $tanggal_awal ?>">
                        </div>
                        <div class="col-md-2">
                            <label for="tanggal_akhir" class="form-label">Tanggal Akhir</label>
                            <input type="date" class="form-control" id="tanggal_akhir" name="tanggal_akhir" value="<?= $tanggal_akhir ?>">
                        </div>
                        <!-- <div class="col-md-3"> -->
                            <!-- <label for="search" class="form-label">Pencarian</label> -->
                            <!-- <input type="text" class="form-control" id="search" name="search" placeholder="Cari aktivitas, deskripsi, user..." value="< ?= $search ?>"> -->
                        <!-- </div> -->
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="fas fa-filter me-1"></i> Filter
                            </button>
                            <a href="<?= SITE_URL ?>/pengawas/logs/index.php" class="btn btn-secondary">
                                <i class="fas fa-sync-alt me-1"></i> Reset
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Tabel Log -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>Tanggal & Waktu</th>
                                    <th>User</th>
                                    <th>Role</th>
                                    <th>Aktivitas</th>
                                    <th>Jenis Entitas</th>
                                    <th>Deskripsi</th>
                                    <th>IP Address</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($logs)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-4">Tidak ada data log aktivitas</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($logs as $log): ?>
                                        <tr>
                                            <td><?= date('d/m/Y H:i:s', strtotime($log->created_at)) ?></td>
                                            <td><?= $log->nama_lengkap ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    switch($log->role) {
                                                        case 'admin': echo 'primary'; break;
                                                        case 'ketua': echo 'danger'; break;
                                                        case 'bendahara': echo 'success'; break;
                                                        case 'sekretaris': echo 'info'; break;
                                                        case 'pengawas': echo 'warning'; break;
                                                        default: echo 'secondary';
                                                    }
                                                ?>">
                                                    <?= getRoleName($log->role) ?>
                                                </span>
                                            </td>
                                            <td><?= $log->activity ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    switch($log->entity_type) {
                                                        case 'kampanye': echo 'success'; break;
                                                        case 'donasi': echo 'primary'; break;
                                                        case 'user': echo 'info'; break;
                                                        case 'berita': echo 'warning'; break;
                                                        default: echo 'secondary';
                                                    }
                                                ?>">
                                                    <?= ucfirst($log->entity_type) ?>
                                                </span>
                                            </td>
                                            <td><?= $log->description ?></td>
                                            <td><small><?= $log->ip_address ?? '-' ?></small></td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center">
                                <li class="page-item <?= ($current_page <= 1) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/pengawas/logs/index.php?page=<?= $current_page - 1 ?><?= !empty($entity_type) ? '&entity_type=' . $entity_type : '' ?><?= !empty($user_role) ? '&user_role=' . $user_role : '' ?><?= !empty($tanggal_awal) ? '&tanggal_awal=' . $tanggal_awal : '' ?><?= !empty($tanggal_akhir) ? '&tanggal_akhir=' . $tanggal_akhir : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Previous</a>
                                </li>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?= ($current_page == $i) ? 'active' : '' ?>">
                                        <a class="page-link" href="<?= SITE_URL ?>/pengawas/logs/index.php?page=<?= $i ?><?= !empty($entity_type) ? '&entity_type=' . $entity_type : '' ?><?= !empty($user_role) ? '&user_role=' . $user_role : '' ?><?= !empty($tanggal_awal) ? '&tanggal_awal=' . $tanggal_awal : '' ?><?= !empty($tanggal_akhir) ? '&tanggal_akhir=' . $tanggal_akhir : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : '' ?>">
                                    <a class="page-link" href="<?= SITE_URL ?>/pengawas/logs/index.php?page=<?= $current_page + 1 ?><?= !empty($entity_type) ? '&entity_type=' . $entity_type : '' ?><?= !empty($user_role) ? '&user_role=' . $user_role : '' ?><?= !empty($tanggal_awal) ? '&tanggal_awal=' . $tanggal_awal : '' ?><?= !empty($tanggal_akhir) ? '&tanggal_akhir=' . $tanggal_akhir : '' ?><?= !empty($search) ? '&search=' . $search : '' ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Statistik Log -->
            <div class="row mt-4">
                <!-- Aktivitas per Role -->
                <div class="col-md-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">Aktivitas per Role</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Hitung aktivitas per role
                            $db->query("SELECT u.role, COUNT(*) as count 
                                      FROM logs l
                                      JOIN users u ON l.user_id = u.id
                                      GROUP BY u.role
                                      ORDER BY count DESC");
                            $role_stats = $db->resultSet();
                            
                            if (!empty($role_stats)):
                            ?>
                                <canvas id="roleChart" height="250"></canvas>
                            <?php else: ?>
                                <p class="text-center py-3">Tidak ada data statistik</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Aktivitas per Jenis Entitas -->
                <div class="col-md-6 mb-4">
                    <div class="card h-100">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">Aktivitas per Jenis Entitas</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Hitung aktivitas per jenis entitas
                            $db->query("SELECT entity_type, COUNT(*) as count 
                                      FROM logs
                                      GROUP BY entity_type
                                      ORDER BY count DESC");
                            $entity_stats = $db->resultSet();
                            
                            if (!empty($entity_stats)):
                            ?>
                                <canvas id="entityChart" height="250"></canvas>
                            <?php else: ?>
                                <p class="text-center py-3">Tidak ada data statistik</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Script untuk chart -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    <?php if (!empty($role_stats)): ?>
    // Chart untuk aktivitas per role
    const roleCtx = document.getElementById('roleChart').getContext('2d');
    const roleChart = new Chart(roleCtx, {
        type: 'bar',
        data: {
            labels: [
                <?php foreach ($role_stats as $stat): ?>
                    '<?= getRoleName($stat->role) ?>',
                <?php endforeach; ?>
            ],
            datasets: [{
                label: 'Jumlah Aktivitas',
                data: [
                    <?php foreach ($role_stats as $stat): ?>
                        <?= $stat->count ?>,
                    <?php endforeach; ?>
                ],
                backgroundColor: [
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(255, 206, 86, 0.5)',
                    'rgba(153, 102, 255, 0.5)',
                    'rgba(255, 159, 64, 0.5)'
                ],
                borderColor: [
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 99, 132, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    <?php endif; ?>

    <?php if (!empty($entity_stats)): ?>
    // Chart untuk aktivitas per jenis entitas
    const entityCtx = document.getElementById('entityChart').getContext('2d');
    const entityChart = new Chart(entityCtx, {
        type: 'doughnut',
        data: {
            labels: [
                <?php foreach ($entity_stats as $stat): ?>
                    '<?= ucfirst($stat->entity_type) ?>',
                <?php endforeach; ?>
            ],
            datasets: [{
                label: 'Jumlah Aktivitas',
                data: [
                    <?php foreach ($entity_stats as $stat): ?>
                        <?= $stat->count ?>,
                    <?php endforeach; ?>
                ],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 206, 86, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(153, 102, 255, 0.5)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'right',
                }
            }
        }
    });
    <?php endif; ?>
});
</script>

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