<?php
// dashboard.php
include_once 'config/koneksi.php';
include_once 'header.php'; 

// --- 1. PROTEKSI FUNGSI ---
if (!function_exists('getTahunAktifId')) {
    function getTahunAktifId($conn) {
        $sql = "SELECT id FROM tahun_aktif WHERE is_aktif = 1 LIMIT 1";
        $result = $conn->query($sql);
        return ($result && $result->num_rows > 0) ? $result->fetch_assoc()['id'] : 0;
    }
}

if (!function_exists('getTahunAktifDisplay')) {
    function getTahunAktifDisplay($conn, $id) {
        $tahun_query = $conn->prepare("SELECT tahun FROM tahun_aktif WHERE id = ?");
        $tahun_query->bind_param("i", $id);
        $tahun_query->execute();
        $result = $tahun_query->get_result();
        $out = 'Periode Tidak Ditemukan';
        if ($result && $row = $result->fetch_assoc()) { $out = htmlspecialchars($row['tahun']); }
        $tahun_query->close();
        return $out;
    }
}

$tahun_aktif_id = getTahunAktifId($conn);
$tahun_display = getTahunAktifDisplay($conn, $tahun_aktif_id);

// --- 2. DATA STATISTIK KARTU ---
$sql_mitra = "SELECT COUNT(id) AS total FROM mitra WHERE tahun_aktif_id = $tahun_aktif_id";
$total_mitra_aktif = $conn->query($sql_mitra)->fetch_assoc()['total'] ?? 0;

$sql_stat = "SELECT 
    SUM(CASE WHEN nam.jenis_kegiatan = 'Pendataan' THEN 1 ELSE 0 END) AS jlp,
    SUM(CASE WHEN nam.jenis_kegiatan = 'Pengolahan' THEN 1 ELSE 0 END) AS jlo,
    COUNT(DISTINCT CASE WHEN nam.jenis_kegiatan = 'Pendataan' THEN nam.id END) AS jjp,
    COUNT(DISTINCT CASE WHEN nam.jenis_kegiatan = 'Pengolahan' THEN nam.id END) AS jjo
    FROM aktivitas_kerja ak 
    JOIN nama_aktivitas_master nam ON ak.nama_aktivitas_id = nam.id 
    WHERE ak.tahun_aktif_id = $tahun_aktif_id";
$data_stat = $conn->query($sql_stat)->fetch_assoc();

$sql_belum = "SELECT COUNT(m.id) AS total FROM mitra m LEFT JOIN aktivitas_kerja ak ON m.id = ak.mitra_id AND ak.tahun_aktif_id = $tahun_aktif_id WHERE m.tahun_aktif_id = $tahun_aktif_id AND ak.mitra_id IS NULL";
$total_mitra_belum = $conn->query($sql_belum)->fetch_assoc()['total'] ?? 0;

// --- 3. DATA GRAFIK KUMULATIF UNIK ---
$sql_graph = "
    SELECT ak.nama_aktivitas_id, ak.mitra_id
    FROM aktivitas_kerja ak
    JOIN nama_aktivitas_master nam ON ak.nama_aktivitas_id = nam.id
    WHERE ak.tahun_aktif_id = $tahun_aktif_id
    ORDER BY nam.id ASC
";
$res_graph = $conn->query($sql_graph);
$data_per_aktivitas = [];
while ($row = $res_graph->fetch_assoc()) {
    $data_per_aktivitas[$row['nama_aktivitas_id']][] = $row['mitra_id'];
}

$labels_x = [0]; $data_y = [0];
$mitra_tercatat = []; $count_step = 0;

foreach ($data_per_aktivitas as $id_act => $list_mitra) {
    $count_step++;
    foreach ($list_mitra as $id_m) {
        if (!in_array($id_m, $mitra_tercatat)) { $mitra_tercatat[] = $id_m; }
    }
    $labels_x[] = $count_step;
    $data_y[] = count($mitra_tercatat);
}
?>

<div class="container-fluid py-4">
    <div class="p-4 mb-4 rounded-3 shadow-sm bg-white" style="border-left: 8px solid #007bff;">
        <h1 class="display-6 fw-bold text-primary mb-1">Selamat Datang, <?php echo htmlspecialchars($_SESSION['nama'] ?? 'Admin'); ?></h1>
        <p class="lead text-muted">Statistik alokasi mitra Periode <?php echo $tahun_display; ?>.</p>
    </div>

    <div class="row mb-5">
        <div class="col-lg-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-primary text-white">
                <div class="card-body p-3">
                    <h3 class="fw-bold mb-1"><?php echo $total_mitra_aktif; ?></h3>
                    <p class="small mb-0 text-uppercase">Mitra Aktif</p>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-white border-bottom border-4 border-success">
                <div class="card-body p-3">
                    <h3 class="fw-bold text-success mb-1"><?php echo $data_stat['jjp'] ?? 0; ?></h3>
                    <p class="small mb-0 text-muted text-uppercase">Jenis Pendataan</p>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-white border-bottom border-4 border-warning">
                <div class="card-body p-3">
                    <h3 class="fw-bold text-warning mb-1"><?php echo $data_stat['jjo'] ?? 0; ?></h3>
                    <p class="small mb-0 text-muted text-uppercase">Jenis Pengolahan</p>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-6 col-sm-6 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-white border-bottom border-4 border-info">
                <div class="card-body p-3">
                    <h3 class="fw-bold text-info mb-1"><?php echo $data_stat['jlp'] ?? 0; ?></h3>
                    <p class="small mb-0 text-muted text-uppercase">Alokasi Pendataan</p>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-6 col-sm-6 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-white border-bottom border-4 border-danger">
                <div class="card-body p-3">
                    <h3 class="fw-bold text-danger mb-1"><?php echo $data_stat['jlo'] ?? 0; ?></h3>
                    <p class="small mb-0 text-muted text-uppercase">Alokasi Pengolahan</p>
                </div>
            </div>
        </div>
        <div class="col-lg-2 col-md-12 col-sm-12 mb-4">
            <div class="card border-0 shadow-sm h-100 bg-secondary text-white">
                <div class="card-body p-3">
                    <h3 class="fw-bold mb-1"><?php echo $total_mitra_belum; ?></h3>
                    <p class="small mb-0 text-uppercase">Belum Dialokasikan</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white py-3">
                    <h5 class="fw-bold mb-0">📈 Grafik Akumulasi Mitra Unik</h5>
                </div>
                <div class="card-body">
                    <div style="position: relative; height: 350px;">
                        <canvas id="unikChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    const ctx = document.getElementById('unikChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($labels_x); ?>,
            datasets: [{
                label: 'Akumulasi Mitra Unik',
                data: <?php echo json_encode($data_y); ?>,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                fill: true,
                tension: 0.1,
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true, title: { display: true, text: 'Jumlah Mitra' } },
                x: { title: { display: true, text: 'Urutan Aktivitas' } }
            }
        }
    });
});
</script>

<?php include_once 'footer.php'; ?>