<?php
// pengawas/audit/index.php
$pageTitle = 'Audit Transaksi';
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 = 10;
$offset = ($current_page - 1) * $limit;

// Filter
$kampanye_id = isset($_GET['kampanye_id']) ? $_GET['kampanye_id'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$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 donasi
$query_count = "SELECT COUNT(*) as total FROM donasi d
                JOIN kampanye k ON d.kampanye_id = k.id
                JOIN users u ON d.user_id = u.id
                LEFT JOIN users v ON d.verified_by_bendahara = v.id
                WHERE 1=1";

$query_params = [];

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

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

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

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

if (!empty($search)) {
    $query_count .= " AND (k.judul LIKE :search OR u.nama_lengkap LIKE :search OR d.keterangan 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 donasi
$query = "SELECT d.*, k.judul as kampanye_judul, u.nama_lengkap as donatur_nama, 
          v.nama_lengkap as verifikator_nama
          FROM donasi d
          JOIN kampanye k ON d.kampanye_id = k.id
          JOIN users u ON d.user_id = u.id
          LEFT JOIN users v ON d.verified_by_bendahara = v.id
          WHERE 1=1";

if (!empty($kampanye_id)) {
    $query .= " AND d.kampanye_id = :kampanye_id";
}

if (!empty($status)) {
    $query .= " AND d.status = :status";
}

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

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

if (!empty($search)) {
    $query .= " AND (k.judul LIKE :search OR u.nama_lengkap LIKE :search OR d.keterangan LIKE :search)";
}

$query .= " ORDER BY d.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);
$donasi_list = $db->resultSet();

// Ambil daftar kampanye untuk filter
$db->query("SELECT id, judul FROM kampanye ORDER BY judul ASC");
$kampanye_options = $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 active" 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" 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">Audit Transaksi</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/audit/export.php?type=pdf<?= !empty($kampanye_id) ? '&kampanye_id=' . $kampanye_id : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !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/audit/export.php?type=excel<?= !empty($kampanye_id) ? '&kampanye_id=' . $kampanye_id : '' ?><?= !empty($status) ? '&status=' . $status : '' ?><?= !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-4">
                            <label for="kampanye_id" class="form-label">Kampanye</label>
                            <select class="form-select" id="kampanye_id" name="kampanye_id">
                                <option value="">Semua Kampanye</option>
                                <?php foreach ($kampanye_options as $kampanye): ?>
                                    <option value="<?= $kampanye->id ?>" <?= $kampanye_id == $kampanye->id ? 'selected' : '' ?>>
                                        <?= $kampanye->judul ?>
                                    </option>
                                <?php endforeach; ?>