<?php
// ketua/dashboard.php
// Tambahkan di awal file setelah require functions.php

error_reporting(E_ALL);

// Tampilkan error ke browser
ini_set('display_errors', 1);

// Untuk environment development
ini_set('display_startup_errors', 1);
$pageTitle = 'Dashboard Ketua Yayasan';
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 ketua
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'ketua') {
    // Redirect ke halaman login jika belum login atau bukan ketua
    setFlash('login_required', 'Anda harus login sebagai ketua yayasan 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 menunggu persetujuan
$db->query("SELECT COUNT(*) as count FROM kampanye WHERE status = 'menunggu_persetujuan'");
$kampanye_menunggu = $db->single();
$kampanye_menunggu_value = $kampanye_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;

// Kampanye yang menunggu persetujuan
$db->query("SELECT k.*, u.nama_lengkap as created_by_name 
           FROM kampanye k 
           JOIN users u ON k.created_by = u.id 
           WHERE k.status = 'menunggu_persetujuan' 
           ORDER BY k.created_at DESC 
           LIMIT 5");
$kampanye_approval = $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
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 ?>/ketua/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 ?>/ketua/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Persetujuan Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/laporan/index.php">
                            <i class="fas fa-chart-line me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kegiatan/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Kegiatan Yayasan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/staff/index.php">
                            <i class="fas fa-users-cog me-2"></i>
                            Manajemen Staff
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/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 Ketua Yayasan</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-cog me-1"></i> Pengaturan
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/ketua/profil/index.php">Profil Saya</a></li>
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/ketua/staff/index.php">Manajemen Staff</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="<?= SITE_URL ?>/auth/logout.php">Logout</a></li>
                        </ul>
                    </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 Persetujuan</h5>
                                    <h3 class="mb-0"><?= $kampanye_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 & Approval -->
            <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>

                <!-- Kampanye Menunggu Persetujuan -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Menunggu Persetujuan</h5>
                            <?php if (empty($kampanye_approval)): ?>
                                <p class="text-center py-3">Tidak ada kampanye yang menunggu persetujuan</p>
                            <?php else: ?>
                                <div class="list-group">
                                    <?php foreach ($kampanye_approval as $kampanye): ?>
                                        <a href="<?= SITE_URL ?>/ketua/kampanye/detail.php?id=<?= $kampanye->id ?>" class="list-group-item list-group-item-action">
                                            <div class="d-flex w-100 justify-content-between">
                                                <h6 class="mb-1"><?= $kampanye->judul ?></h6>
                                                <small class="text-primary">Detail</small>
                                            </div>
                                            <p class="mb-1 text-muted small"><?= potongTeks($kampanye->deskripsi, 50) ?></p>
                                            <div class="d-flex justify-content-between">
                                                <small>Target: <?= rupiah($kampanye->target_donasi) ?></small>
                                                <small>Diajukan: <?= date('d/m/Y', strtotime($kampanye->created_at)) ?></small>
                                            </div>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                                <?php if ($kampanye_menunggu_value > count($kampanye_approval)): ?>
                                    <div class="text-center mt-3">
                                        <a href="<?= SITE_URL ?>/ketua/kampanye/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua</a>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top Kampanye & Aktivitas 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 ?>/ketua/kampanye/detail.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 ?>/ketua/kampanye/index.php?status=aktif" class="btn btn-sm btn-outline-primary">Lihat Semua Kampanye</a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Aktivitas Terbaru -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">Aktivitas 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 5");
                            $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 list-group-item-action">
                                            <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>Oleh: <?= $log->nama_lengkap ?> (<?= getRoleName($log->role) ?>)</small>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="text-center mt-3">
                                    <a href="<?= SITE_URL ?>/ketua/logs/index.php" class="btn btn-sm btn-outline-primary">Lihat Semua Aktivitas</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'; ?>