<?php
// pengawas/dashboard.php
$pageTitle = 'Dashboard Pengawas';
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Definisi fungsi jika tidak tersedia
if (!function_exists('getKampanyeStatusBadge')) {
    function getKampanyeStatusBadge($status) {
        switch($status) {
            case 'aktif':
                return '<span class="badge bg-success">Aktif</span>';
            case 'selesai':
                return '<span class="badge bg-primary">Selesai</span>';
            case 'dibatalkan':
                return '<span class="badge bg-danger">Dibatalkan</span>';
            case 'menunggu_persetujuan':
                return '<span class="badge bg-warning text-dark">Menunggu Persetujuan</span>';
            default:
                return '<span class="badge bg-secondary">' . ucfirst($status) . '</span>';
        }
    }
}

if (!function_exists('getDonasiStatusBadge')) {
    function getDonasiStatusBadge($status) {
        switch($status) {
            case 'menunggu':
                return '<span class="badge bg-warning text-dark">Menunggu</span>';
            case 'diverifikasi':
                return '<span class="badge bg-success">Diverifikasi</span>';
            case 'ditolak':
                return '<span class="badge bg-danger">Ditolak</span>';
            default:
                return '<span class="badge bg-secondary">' . ucfirst($status) . '</span>';
        }
    }
}
// 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;
}

// Ambil data untuk dashboard
$db = dbConnect();

// Total donasi berhasil
$db->query("SELECT SUM(jumlah) as total_donasi FROM donasi WHERE status = 'diverifikasi'");
$total_donasi = $db->single();
$total_donasi_value = $total_donasi->total_donasi ?? 0;

// Jumlah kampanye aktif
$db->query("SELECT COUNT(*) as count FROM kampanye WHERE status = 'aktif'");
$kampanye_aktif = $db->single();
$kampanye_aktif_value = $kampanye_aktif->count ?? 0;

// Jumlah kampanye selesai
$db->query("SELECT COUNT(*) as count FROM kampanye WHERE status = 'selesai'");
$kampanye_selesai = $db->single();
$kampanye_selesai_value = $kampanye_selesai->count ?? 0;

// Jumlah total user
$db->query("SELECT COUNT(*) as count FROM users WHERE role = 'donatur'");
$total_user = $db->single();
$total_user_value = $total_user->count ?? 0;

// Donasi terbaru untuk ditampilkan di tabel
$db->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 d.status = 'diverifikasi'
           ORDER BY d.updated_at DESC 
           LIMIT 10");
$donasi_verified = $db->resultSet();

// Kampanye dengan donasi terbanyak (top 5)
$db->query("SELECT k.id, k.judul, k.target_donasi, k.status,
           (SELECT SUM(d.jumlah) FROM donasi d WHERE d.kampanye_id = k.id AND d.status = 'diverifikasi') as total_terkumpul,
           (SELECT COUNT(d.id) FROM donasi d WHERE d.kampanye_id = k.id AND d.status = 'diverifikasi') as jumlah_donatur
           FROM kampanye k 
           ORDER BY total_terkumpul DESC 
           LIMIT 5");
$top_kampanye = $db->resultSet();

// Hitung untuk chart statistik donasi per bulan (6 bulan terakhir)
$donasi_perbulan = [];
for ($i = 5; $i >= 0; $i--) {
    $bulan = date('Y-m', strtotime('-' . $i . ' months'));
    $bulan_awal = $bulan . '-01';
    $bulan_akhir = $bulan . '-31';
    
    $db->query("SELECT SUM(jumlah) as total FROM donasi WHERE status = 'diverifikasi' AND created_at BETWEEN :awal AND :akhir");
    $db->bind(':awal', $bulan_awal);
    $db->bind(':akhir', $bulan_akhir);
    $hasil = $db->single();
    
    $donasi_perbulan[] = [
        'bulan' => date('M Y', strtotime($bulan_awal)),
        'total' => $hasil->total ?? 0
    ];
}

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

<!-- Sidebar & Content -->
<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 active" 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-clipboard-check 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-chart-bar 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">Dashboard Pengawas</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/pengawas/audit/index.php" class="btn btn-sm btn-outline-primary me-2">
                        <i class="fas fa-search me-1"></i> Audit Transaksi
                    </a>
                    <a href="<?= SITE_URL ?>/pengawas/laporan/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-file-alt me-1"></i> Laporan Keuangan
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Statistik Overview -->
            <div class="row dashboard-stats">
                <div class="col-md-3 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-money-bill-wave"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Total Donasi</h5>
                                    <h3 class="mb-0"><?= rupiah($total_donasi_value) ?></h3>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-project-diagram"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Kampanye Aktif</h5>
                                    <h3 class="mb-0"><?= $kampanye_aktif_value ?></h3>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-flag-checkered"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Kampanye Selesai</h5>
                                    <h3 class="mb-0"><?= $kampanye_selesai_value ?></h3>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mb-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="d-flex align-items-center">
                                <div class="card-icon rounded-circle d-flex align-items-center justify-content-center me-3">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Total Donatur</h5>
                                    <h3 class="mb-0"><?= $total_user_value ?></h3>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Grafik & Donasi Terverifikasi -->
            <div class="row">
                <!-- Grafik Donasi Per Bulan -->
                <div class="col-md-7 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Trend Donasi 6 Bulan Terakhir</h5>
                            <canvas id="donasiChart" height="250"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Donasi Terverifikasi Terbaru -->
                <div class="col-md-5 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Donasi Terverifikasi Terbaru</h5>
                            <?php if (empty($donasi_verified)): ?>
                                <p class="text-center py-3">Belum ada donasi terverifikasi</p>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach (array_slice($donasi_verified, 0, 5) as $donasi): ?>
                                        <a href="<?= SITE_URL ?>/pengawas/audit/detail.php?id=<?= $donasi->id ?>" class="list-group-item list-group-item-action">
                                            <div class="d-flex w-100 justify-content-between">
                                                <h6 class="mb-1"><?= $donasi->is_anonim ? 'Anonim' : $donasi->donatur_nama ?></h6>
                                                <small class="fw-bold"><?= rupiah($donasi->jumlah) ?></small>
                                            </div>
                                            <p class="mb-1 text-muted small">Kampanye: <?= $donasi->kampanye_judul ?></p>
                                            <small>
                                                <i class="far fa-clock me-1"></i> <?= date('d M Y H:i', strtotime($donasi->updated_at)) ?>
                                                <br>
                                                <i class="far fa-user me-1"></i> Diverifikasi oleh: <?= $donasi->verifikator_nama ?? 'N/A' ?>
                                            </small>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/pengawas/audit/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top Kampanye & Aktivitas -->
            <div class="row">
                <!-- Top Kampanye -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Kampanye Dengan Donasi Terbanyak</h5>
                            <?php if (empty($top_kampanye)): ?>
                                <p class="text-center py-3">Belum ada data kampanye</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Kampanye</th>
                                                <th>Status</th>
                                                <th>Terkumpul</th>
                                                <th>Progress</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($top_kampanye as $kampanye): ?>
                                                <?php 
                                                $persentase = hitungPersentase($kampanye->total_terkumpul ?? 0, $kampanye->target_donasi);
                                                ?>
                                                <tr>
                                                    <td>
                                                        <a href="<?= SITE_URL ?>/pengawas/audit/kampanye.php?id=<?= $kampanye->id ?>" class="text-decoration-none text-dark">
                                                            <?= $kampanye->judul ?>
                                                        </a>
                                                    </td>
                                                    <td><?= getKampanyeStatusBadge($kampanye->status) ?></td>
                                                    <td><?= rupiah($kampanye->total_terkumpul ?? 0) ?></td>
                                                    <td>
                                                        <div class="progress" style="height: 6px;">
                                                            <div class="progress-bar bg-success" role="progressbar" style="width: <?= $persentase ?>%;" aria-valuenow="<?= $persentase ?>" aria-valuemin="0" aria-valuemax="100"></div>
                                                        </div>
                                                        <small><?= $persentase ?>%</small>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/pengawas/audit/kampanye-list.php" class="btn btn-sm btn-outline-primary">Lihat Semua Kampanye</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Aktivitas Sistem -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Aktivitas Sistem Terbaru</h5>
                            <?php
                            // Ambil log aktivitas terbaru
                            $db->query("SELECT l.*, u.nama_lengkap, u.role 
                                    FROM logs l 
                                    JOIN users u ON l.user_id = u.id 
                                    ORDER BY l.created_at DESC 
                                    LIMIT 8");
                            $logs = $db->resultSet();
                            
                            if (empty($logs)):
                            ?>
                                <p class="text-center py-3">Belum ada aktivitas terbaru</p>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach ($logs as $log): ?>
                                        <div class="list-group-item">
                                            <div class="d-flex w-100 justify-content-between">
                                                <h6 class="mb-1"><?= $log->activity ?></h6>
                                                <small><?= date('d/m/Y H:i', strtotime($log->created_at)) ?></small>
                                            </div>
                                            <p class="mb-1 text-muted small"><?= $log->description ?></p>
                                            <small>
                                                <span class="badge bg-info text-white"><?= $log->entity_type ?></span>
                                                Oleh: <?= $log->nama_lengkap ?> (<?= getRoleName($log->role) ?>)
                                            </small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/pengawas/logs/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua Aktivitas</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tabel Donasi Terverifikasi -->
            <div class="row">
                <div class="col-12 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Daftar Donasi Terverifikasi</h5>
                            <?php if (empty($donasi_verified)): ?>
                                <p class="text-center py-3">Belum ada donasi terverifikasi</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Donatur</th>
                                                <th>Kampanye</th>
                                                <th>Jumlah</th>
                                                <th>Tanggal</th>
                                                <th>Diverifikasi Oleh</th>
                                                <th>Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($donasi_verified as $donasi): ?>
                                                <tr>
                                                    <td>#<?= $donasi->id ?></td>
                                                    <td><?= $donasi->is_anonim ? 'Anonim' : $donasi->donatur_nama ?></td>
                                                    <td><?= potongTeks($donasi->kampanye_judul, 30) ?></td>
                                                    <td><?= rupiah($donasi->jumlah) ?></td>
                                                    <td><?= date('d/m/Y', strtotime($donasi->created_at)) ?></td>
                                                    <td><?= $donasi->verifikator_nama ?? 'N/A' ?></td>
                                                    <td>
                                                        <a href="<?= SITE_URL ?>/pengawas/audit/detail.php?id=<?= $donasi->id ?>" class="btn btn-sm btn-info text-white">
                                                            <i class="fas fa-search"></i> Audit
                                                        </a>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/pengawas/audit/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua Donasi</a>
                                </div>
                            <?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() {
    // Data untuk chart
    const donasiData = {
        labels: [
            <?php foreach ($donasi_perbulan as $bulan): ?>
                '<?= $bulan['bulan'] ?>',
            <?php endforeach; ?>
        ],
        datasets: [{
            label: 'Total Donasi',
            data: [
                <?php foreach ($donasi_perbulan as $bulan): ?>
                    <?= $bulan['total'] ?>,
                <?php endforeach; ?>
            ],
            backgroundColor: 'rgba(40, 167, 69, 0.2)',
            borderColor: 'rgba(40, 167, 69, 1)',
            borderWidth: 2,
            borderRadius: 5,
            tension: 0.3
        }]
    };

    // Konfigurasi chart
    const config = {
        type: 'line',
        data: donasiData,
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(context.parsed.y);
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value, index, values) {
                            return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumSignificantDigits: 3 }).format(value);
                        }
                    }
                }
            }
        },
    };

    // Render chart
    var donasiChart = new Chart(
        document.getElementById('donasiChart'),
        config
    );
});
</script>

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