<?php
// admin/dashboard.php
$pageTitle = 'Dashboard Admin';
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/functions.php';

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

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin 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 donasi menunggu verifikasi
$db->query("SELECT COUNT(*) as count FROM donasi WHERE status = 'menunggu'");
$donasi_menunggu = $db->single();
$donasi_menunggu_value = $donasi_menunggu->count ?? 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 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 
           FROM donasi d 
           JOIN kampanye k ON d.kampanye_id = k.id 
           JOIN users u ON d.user_id = u.id 
           ORDER BY d.created_at DESC 
           LIMIT 5");
$donasi_recent = $db->resultSet();

// Kampanye dengan donasi terbanyak (top 5)
$db->query("SELECT k.id, k.judul, k.target_donasi, 
           (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 
           WHERE k.status = 'aktif'
           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 admin
require_once '../includes/header.php';
?>

<!-- Sidebar Admin -->
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <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 ?>/admin/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 ?>/admin/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/admin/donasi/index.php">
                            <i class="fas fa-donate me-2"></i>
                            Donasi
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/admin/berita/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Berita
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/admin/users/index.php">
                            <i class="fas fa-users me-2"></i>
                            Users
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/admin/kontak/index.php">
                            <i class="fas fa-envelope me-2"></i>
                            Pesan Kontak
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/admin/profil/index.php">
                            <i class="fas fa-building me-2"></i>
                            Profil Yayasan
                        </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>
            </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 Admin</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <div class="btn-group me-2">
                        <a href="<?= SITE_URL ?>" class="btn btn-sm btn-outline-secondary">Lihat Website</a>
                    </div>
                </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-clock"></i>
                                </div>
                                <div>
                                    <h5 class="card-title">Menunggu Verifikasi</h5>
                                    <h3 class="mb-0"><?= $donasi_menunggu_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-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 & Tabel -->
            <div class="row">
                <!-- Grafik Donasi Per Bulan -->
                <div class="col-md-8 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Donasi Per Bulan</h5>
                            <canvas id="donasiChart" height="250"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Donasi Terbaru -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Menunggu Verifikasi</h5>
                            <?php if (empty($donasi_recent) || $donasi_menunggu_value == 0): ?>
                                <p class="text-center py-3">Tidak ada donasi yang menunggu verifikasi</p>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach ($donasi_recent as $donasi): ?>
                                        <?php if ($donasi->status == 'menunggu'): ?>
                                            <a href="<?= SITE_URL ?>/admin/donasi/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><?= rupiah($donasi->jumlah) ?></small>
                                                </div>
                                                <small class="text-muted"><?= $donasi->kampanye_judul ?></small>
                                                <small class="d-block">
                                                    <?= date('d M Y H:i', strtotime($donasi->created_at)) ?>
                                                </small>
                                            </a>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                                <?php if ($donasi_menunggu_value > count($donasi_recent)): ?>
                                    <div class="text-center mt-3">
                                        <a href="<?= SITE_URL ?>/admin/donasi/index.php?status=menunggu" class="btn btn-sm btn-outline-primary">Lihat Semua</a>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Kampanye & Donasi Terbaru -->
            <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>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 ?>/admin/kampanye/edit.php?id=<?= $kampanye->id ?>" class="text-decoration-none text-dark">
                                                            <?= $kampanye->judul ?>
                                                        </a>
                                                    </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 ?>/admin/kampanye/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua Kampanye</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Tabel Donasi Terbaru -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Donasi Terbaru</h5>
                            <?php if (empty($donasi_recent)): ?>
                                <p class="text-center py-3">Belum ada data donasi</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Donatur</th>
                                                <th>Jumlah</th>
                                                <th>Status</th>
                                                <th>Tanggal</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($donasi_recent as $donasi): ?>
                                                <tr>
                                                    <td><?= $donasi->is_anonim ? 'Anonim' : $donasi->donatur_nama ?></td>
                                                    <td><?= rupiah($donasi->jumlah) ?></td>
                                                    <td>
                                                        <?php if ($donasi->status == 'menunggu'): ?>
                                                            <span class="badge bg-warning text-dark">Menunggu</span>
                                                        <?php elseif ($donasi->status == 'diverifikasi'): ?>
                                                            <span class="badge bg-success">Diverifikasi</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-danger">Ditolak</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <small><?= date('d M Y', strtotime($donasi->created_at)) ?></small>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/admin/donasi/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: 'bar',
        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'; ?>