<?php
require_once 'db.php';

session_start();
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$instansi_id = $_SESSION['instansi_id']; 

// Ambil data instansi
$stmt_inst = $pdo->prepare("SELECT nama_instansi, logo_path FROM instansi WHERE id = ?");
$stmt_inst->execute([$instansi_id]);
$inst_data = $stmt_inst->fetch(PDO::FETCH_ASSOC);
$nama_instansi = $inst_data['nama_instansi'] ?? "Instansi ID $instansi_id";
$logo_path = !empty($inst_data['logo_path']) ? $inst_data['logo_path'] : '';

// Bulk Actions
$bulk_msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && isset($_POST['selected_ids'])) {
    $action = $_POST['bulk_action'];
    $ids = $_POST['selected_ids']; // array of IDs
    
    if (!empty($ids)) {
        // Sanitize IDs
        $in_ids = implode(',', array_map('intval', $ids));
        
        if ($action === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM berita WHERE id IN ($in_ids) AND instansi_id = ?");
            if ($stmt->execute([$instansi_id])) {
                $bulk_msg = "<div class='alert alert-success alert-dismissible fade show'><i class='fas fa-check-circle me-2'></i>" . count($ids) . " berita berhasil dihapus.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            }
        } elseif (in_array($action, ['positif', 'negatif', 'netral'])) {
            $stmt = $pdo->prepare("UPDATE berita SET sentimen = ? WHERE id IN ($in_ids) AND instansi_id = ?");
            if ($stmt->execute([$action, $instansi_id])) {
                $bulk_msg = "<div class='alert alert-success alert-dismissible fade show'><i class='fas fa-check-circle me-2'></i>Sentimen untuk " . count($ids) . " berita berhasil diubah menjadi ".strtoupper($action).".<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            }
        } elseif ($action === 'export_excel') {
            $stmt = $pdo->prepare("SELECT * FROM berita WHERE id IN ($in_ids) AND instansi_id = ? ORDER BY tanggal DESC");
            $stmt->execute([$instansi_id]);
            $berita_export = $stmt->fetchAll(PDO::FETCH_ASSOC);

            header("Content-Type: application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename=\"Export_Berita_" . date('Y-m-d') . ".xls\"");
            header("Pragma: no-cache");
            header("Expires: 0");

            echo "<table border='1'>";
            echo "<tr>";
            echo "<th>No</th>";
            echo "<th>Judul Berita</th>";
            echo "<th>Sumber</th>";
            echo "<th>Tanggal</th>";
            echo "<th>Sentimen</th>";
            echo "<th>Kategori</th>";
            echo "<th>Urgensi</th>";
            echo "<th>Link</th>";
            echo "</tr>";
            $no = 1;
            foreach ($berita_export as $b) {
                echo "<tr>";
                echo "<td>" . $no++ . "</td>";
                echo "<td>" . htmlspecialchars($b['judul'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['sumber'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['tanggal'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['sentimen'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['kategori_berita'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['urgensi'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['link'] ?? '') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            exit;
        }
    }
}

// Tambahkan Layout Header lebih awal agar loading screen bisa dirender browser segera
require_once 'layout_header.php';
?>
<!-- Loading Progress -->
<div id="dashboard-loader" style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 60vh;">
    <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;" role="status"></div>
    <h4 class="mt-4 text-muted fw-bold">Memuat Data Dashboard...</h4>
    <p class="text-secondary small">Mohon tunggu sebentar, sedang menyusun dan menganalisis data.</p>
</div>
<div id="dashboard-content" style="display: none;">
<?php
// Flush output ke browser agar loader langsung muncul tanpa menunggu query selesai
if (ob_get_level() > 0) {
    @ob_flush();
}
@flush();

// Filter params
if(!isset($_GET['bulan']) && !isset($_GET['tahun'])) {
    $stmt_max = $pdo->prepare("SELECT MAX(tanggal) FROM berita WHERE instansi_id = ?");
    $stmt_max->execute([$instansi_id]);
    $max_date = $stmt_max->fetchColumn();
    if($max_date) {
        $filter_bulan = date('m', strtotime($max_date));
        $filter_tahun = date('Y', strtotime($max_date));
    } else {
        $filter_bulan = date('m');
        $filter_tahun = date('Y');
    }
} else {
    $filter_bulan = isset($_GET['bulan']) ? $_GET['bulan'] : date('m');
    $filter_tahun = isset($_GET['tahun']) ? $_GET['tahun'] : date('Y');
}
$filter_tanggal = isset($_GET['tanggal']) ? $_GET['tanggal'] : '';
$filter_search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Base query parts
$start_date = "$filter_tahun-" . str_pad($filter_bulan, 2, '0', STR_PAD_LEFT) . "-01 00:00:00";
$end_date = date('Y-m-t 23:59:59', strtotime($start_date));

$where_clause = "b.instansi_id = :instansi_id AND b.tanggal >= :start_date AND b.tanggal <= :end_date";
$params = [
    ':instansi_id' => $instansi_id,
    ':start_date' => $start_date,
    ':end_date' => $end_date
];

if ($filter_tanggal != '') {
    $exact_date = "$filter_tahun-" . str_pad($filter_bulan, 2, '0', STR_PAD_LEFT) . "-" . str_pad($filter_tanggal, 2, '0', STR_PAD_LEFT);
    $where_clause = "b.instansi_id = :instansi_id AND b.tanggal >= :start_date_day AND b.tanggal <= :end_date_day";
    $params = [
        ':instansi_id' => $instansi_id,
        ':start_date_day' => "$exact_date 00:00:00",
        ':end_date_day' => "$exact_date 23:59:59"
    ];
}

if ($filter_search != '') {
    $where_clause .= " AND (b.judul LIKE :search OR b.cuplikan LIKE :search)";
    $params[':search'] = "%$filter_search%";
}

// 1. Trending Berita (5 Teratas, bebas bulan/tahun karena ini 'terbaru')
$stmt_trending = $pdo->prepare("SELECT b.* FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE b.instansi_id = ? ORDER BY b.tanggal DESC LIMIT 5");
$stmt_trending->execute([$instansi_id]);
$trending = $stmt_trending->fetchAll(PDO::FETCH_ASSOC);

// 2. Ambil berita terbaru (Filtered)
$stmt = $pdo->prepare("SELECT b.* FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause ORDER BY b.tanggal DESC");
$stmt->execute($params);
$berita = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 3. Ambil Berita Negatif (Filtered)
$stmt_neg = $pdo->prepare("SELECT b.* FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause AND b.sentimen IN ('negatif', 'buruk') ORDER BY b.tanggal DESC");
$stmt_neg->execute($params);
$berita_negatif = $stmt_neg->fetchAll(PDO::FETCH_ASSOC);

// 4. Statistik (Filtered)
$stmt_stat = $pdo->prepare("SELECT 
    COUNT(b.id) as total,
    SUM(CASE WHEN b.sentimen IN ('positif', 'baik') THEN 1 ELSE 0 END) as positif,
    SUM(CASE WHEN b.sentimen IN ('negatif', 'buruk') THEN 1 ELSE 0 END) as negatif
    FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id 
    WHERE $where_clause");
$stmt_stat->execute($params);
$stat_data = $stmt_stat->fetch(PDO::FETCH_ASSOC);

$stat_total = $stat_data['total'] ?? 0;
$stat_positif = $stat_data['positif'] ?? 0;
$stat_negatif_num = $stat_data['negatif'] ?? 0;
$stat_netral = $stat_total - $stat_positif - $stat_negatif_num;

// 5. Data untuk Chart (Filtered)
$stmt_bar = $pdo->prepare("SELECT m.nama as sumber, COUNT(b.id) as jumlah FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause GROUP BY m.nama ORDER BY jumlah DESC LIMIT 10");
$stmt_bar->execute($params);
$chart_bar_raw = $stmt_bar->fetchAll(PDO::FETCH_ASSOC);
$bar_labels = []; $bar_data = [];
foreach($chart_bar_raw as $row) {
    $bar_labels[] = $row['sumber'];
    $bar_data[] = (int) $row['jumlah'];
}

if(empty($bar_data)) {
    $bar_labels = ['Belum Ada Media'];
    $bar_data = [0];
}

$stmt_pie = $pdo->prepare("SELECT b.sentimen, COUNT(b.id) as jumlah FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause GROUP BY b.sentimen");
$stmt_pie->execute($params);
$chart_pie_raw = $stmt_pie->fetchAll(PDO::FETCH_ASSOC);
$pie_data = ['positif' => 0, 'negatif' => 0, 'netral' => 0];
foreach($chart_pie_raw as $row) {
    $s = strtolower($row['sentimen']);
    if($s == 'baik' || $s == 'positif') $pie_data['positif'] += $row['jumlah'];
    elseif($s == 'buruk' || $s == 'negatif') $pie_data['negatif'] += $row['jumlah'];
    else $pie_data['netral'] += $row['jumlah'];
}

// Data Kategori Berita (Filtered)
$stmt_kat = $pdo->prepare("SELECT kategori_berita, COUNT(b.id) as jumlah FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause AND b.kategori_berita IS NOT NULL AND b.kategori_berita != '' GROUP BY b.kategori_berita ORDER BY jumlah DESC LIMIT 10");
$stmt_kat->execute($params);
$chart_kat_raw = $stmt_kat->fetchAll(PDO::FETCH_ASSOC);
$kat_labels = []; $kat_data = [];
foreach($chart_kat_raw as $row) {
    $kat_labels[] = $row['kategori_berita'] ?: 'Lainnya';
    $kat_data[] = (int) $row['jumlah'];
}

if(empty($kat_data)) {
    $kat_labels = ['Belum Ada Kategori'];
    $kat_data = [1];
}

// 5b. Data Sentiment Berita Per SKPD (Positif vs Negatif)
$stmt_skpd_list = $pdo->prepare("SELECT id, nama_skpd, singkatan, keywords FROM skpd WHERE instansi_id = ? AND status = 'aktif'");
$stmt_skpd_list->execute([$instansi_id]);
$skpd_all = $stmt_skpd_list->fetchAll(PDO::FETCH_ASSOC);

$skpd_stats = [];
foreach ($skpd_all as $s) {
    $key_name = !empty($s['singkatan']) ? $s['singkatan'] : $s['nama_skpd'];
    $kw_array = array_filter(array_map('trim', explode(',', strtolower($s['keywords'] ?? ''))));
    $skpd_stats[$s['id']] = [
        'id' => $s['id'],
        'name' => $key_name,
        'full_name' => $s['nama_skpd'],
        'keywords' => $kw_array,
        'positif' => 0,
        'negatif' => 0,
        'netral' => 0,
        'total' => 0
    ];
}

$stmt_berita_skpd = $pdo->prepare("SELECT b.id, b.judul, b.cuplikan, b.sentimen, b.skpd_id FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_clause");
$stmt_berita_skpd->execute($params);
$berita_for_skpd = $stmt_berita_skpd->fetchAll(PDO::FETCH_ASSOC);

foreach ($berita_for_skpd as $b) {
    $s_type = strtolower($b['sentimen'] ?? 'netral');
    $is_pos = ($s_type === 'positif' || $s_type === 'baik');
    $is_neg = ($s_type === 'negatif' || $s_type === 'buruk');
    
    $matched_skpd_id = null;

    if (!empty($b['skpd_id']) && isset($skpd_stats[$b['skpd_id']])) {
        $matched_skpd_id = $b['skpd_id'];
    } else {
        $text = strtolower($b['judul'] . ' ' . ($b['cuplikan'] ?? ''));
        foreach ($skpd_stats as $sid => $sinfo) {
            if (!empty($sinfo['name']) && str_contains($text, strtolower($sinfo['name']))) {
                $matched_skpd_id = $sid;
                break;
            }
            foreach ($sinfo['keywords'] as $kw) {
                if (strlen($kw) > 2 && str_contains($text, $kw)) {
                    $matched_skpd_id = $sid;
                    break 2;
                }
            }
        }
    }

    if ($matched_skpd_id) {
        if ($is_pos) {
            $skpd_stats[$matched_skpd_id]['positif']++;
        } elseif ($is_neg) {
            $skpd_stats[$matched_skpd_id]['negatif']++;
        } else {
            $skpd_stats[$matched_skpd_id]['netral']++;
        }
        $skpd_stats[$matched_skpd_id]['total']++;
    }
}

// 5c. Integrasi Keluhan SP4N LAPOR per SKPD ke Chart Warning
$where_lapor_chart = "l.instansi_id = :instansi_id AND MONTH(l.tanggal_masuk) = :bulan AND YEAR(l.tanggal_masuk) = :tahun";
$params_lapor_chart = [
    ':instansi_id' => $instansi_id,
    ':bulan' => $filter_bulan,
    ':tahun' => $filter_tahun
];
if ($filter_tanggal != '') {
    $where_lapor_chart .= " AND DAY(l.tanggal_masuk) = :tanggal";
    $params_lapor_chart[':tanggal'] = $filter_tanggal;
}

$stmt_lapor_stats = $pdo->prepare("SELECT l.id, l.judul, l.isi_laporan, l.skpd_id, l.instansi_terdisposisi FROM lapor l WHERE $where_lapor_chart");
$stmt_lapor_stats->execute($params_lapor_chart);
$lapor_for_skpd = $stmt_lapor_stats->fetchAll(PDO::FETCH_ASSOC);

foreach ($lapor_for_skpd as $lp) {
    $matched_skpd_id = null;
    if (!empty($lp['skpd_id']) && isset($skpd_stats[$lp['skpd_id']])) {
        $matched_skpd_id = $lp['skpd_id'];
    } else {
        $cleanInst = strtolower($lp['instansi_terdisposisi'] ?? '');
        foreach ($skpd_stats as $sid => $sinfo) {
            if (!empty($sinfo['name']) && str_contains($cleanInst, strtolower($sinfo['name']))) {
                $matched_skpd_id = $sid;
                break;
            }
        }
    }

    if ($matched_skpd_id) {
        $skpd_stats[$matched_skpd_id]['negatif']++; // Dihitung sebagai keluhan/warning publik
        $skpd_stats[$matched_skpd_id]['total']++;
    }
}

$skpd_active_stats = array_filter($skpd_stats, function($item) {
    return $item['total'] > 0;
});

usort($skpd_active_stats, function($a, $b) {
    if ($b['negatif'] === $a['negatif']) {
        return $b['total'] <=> $a['total'];
    }
    return $b['negatif'] <=> $a['negatif'];
});

$skpd_active_stats = array_slice($skpd_active_stats, 0, 10);

$skpd_labels = [];
$skpd_pos_data = [];
$skpd_neg_data = [];
$skpd_net_data = [];

foreach ($skpd_active_stats as $sitem) {
    $skpd_labels[] = $sitem['name'];
    $skpd_pos_data[] = $sitem['positif'];
    $skpd_neg_data[] = $sitem['negatif'];
    $skpd_net_data[] = $sitem['netral'];
}

if (empty($skpd_labels)) {
    $skpd_labels = ['Belum Ada Data SKPD'];
    $skpd_pos_data = [0];
    $skpd_neg_data = [0];
    $skpd_net_data = [0];
}

// 5d. Data Isu Publik SP4N LAPOR Per SKPD (Filtered)
$stmt_lapor_chart = $pdo->prepare("
    SELECT 
        COALESCE(s.singkatan, s.nama_skpd, l.instansi_terdisposisi) as skpd_name,
        COUNT(l.id) as jumlah_keluhan
    FROM lapor l
    LEFT JOIN skpd s ON l.skpd_id = s.id
    WHERE l.instansi_id = :instansi_id
      AND MONTH(l.tanggal_masuk) = :bulan
      AND YEAR(l.tanggal_masuk) = :tahun
    GROUP BY skpd_name
    ORDER BY jumlah_keluhan DESC
    LIMIT 10
");
$stmt_lapor_chart->execute([
    ':instansi_id' => $instansi_id,
    ':bulan' => $filter_bulan,
    ':tahun' => $filter_tahun
]);
$chart_lapor_raw = $stmt_lapor_chart->fetchAll(PDO::FETCH_ASSOC);

$lapor_chart_labels = [];
$lapor_chart_data = [];
foreach ($chart_lapor_raw as $row) {
    $lapor_chart_labels[] = $row['skpd_name'] ?: 'Lainnya';
    $lapor_chart_data[] = (int)$row['jumlah_keluhan'];
}

if (empty($lapor_chart_data)) {
    $lapor_chart_labels = ['Belum Ada Keluhan LAPOR'];
    $lapor_chart_data = [0];
}

// 6. Algoritma Deteksi Isu Hangat (Clustering PHP)
// Mengambil berita bulan ini (atau sesuai filter)
$where_cluster = "b.instansi_id = :instansi_id AND MONTH(b.tanggal) = :bulan AND YEAR(b.tanggal) = :tahun";
$stmt_cluster = $pdo->prepare("SELECT b.id, b.judul, b.link, m.nama as sumber, b.tanggal FROM berita b JOIN media m ON b.sumber = m.nama AND b.instansi_id = m.instansi_id WHERE $where_cluster ORDER BY b.tanggal DESC");
$stmt_cluster->execute([
    ':instansi_id' => $instansi_id,
    ':bulan' => $filter_bulan,
    ':tahun' => $filter_tahun
]);
$berita_recent = $stmt_cluster->fetchAll(PDO::FETCH_ASSOC);

$clusters = [];
$stopwords = ['di','ke','dari','yang','dan','atau','untuk','dengan','ini','itu','dalam','pada','oleh','sebagai','menjadi','adalah','bahwa','tak','tidak','bisa','akan','sudah','telah','belum','jadi','malah','diduga','dugaan','kasus'];
$synonyms = ['perundungan' => 'bullying', 'dipolisikan' => 'polisi', 'diperiksa' => 'polisi', 'oknum' => 'polisi'];

foreach ($berita_recent as $b) {
    $found = false;
    $judul_clean = strtolower(preg_replace('/[^a-zA-Z0-9\s]/', ' ', $b['judul']));
    
    // Tokenisasi kata
    $words = array_filter(explode(' ', $judul_clean), function($w) use ($stopwords) {
        return strlen($w) > 2 && !in_array($w, $stopwords);
    });
    $mapped_words = array_unique(array_map(function($w) use ($synonyms) {
        return $synonyms[$w] ?? $w;
    }, $words));

    foreach ($clusters as &$c) {
        $is_similar = false;
        
        // Cek kemiripan dengan SETIAP berita di dalam cluster (bukan cuma index 0)
        foreach ($c['items'] as $item) {
            $item_clean = strtolower(preg_replace('/[^a-zA-Z0-9\s]/', ' ', $item['judul']));
            
            // 1. Cek similaritas karakter (Threshold 60%)
            $sim = 0;
            similar_text(str_replace(' ', '', $judul_clean), str_replace(' ', '', $item_clean), $sim);
            if ($sim > 60) {
                $is_similar = true;
                break;
            }
            
            // 2. Cek irisan kata (Word Intersection)
            $item_words = array_filter(explode(' ', $item_clean), function($w) use ($stopwords) {
                return strlen($w) > 2 && !in_array($w, $stopwords);
            });
            $item_mapped_words = array_unique(array_map(function($w) use ($synonyms) {
                return $synonyms[$w] ?? $w;
            }, $item_words));
            
            $intersect = array_intersect($mapped_words, $item_mapped_words);
            $union = array_unique(array_merge($mapped_words, $item_mapped_words));
            
            // Jika ada minimal 3 kata penting yang sama, atau Jaccard Index > 0.35
            if (count($intersect) >= 3 || (count($union) > 0 && count($intersect) / count($union) > 0.35)) {
                $is_similar = true;
                break;
            }
        }
        
        if ($is_similar) {
            $c['items'][] = $b;
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $clusters[] = [
            'judul_utama' => $b['judul'],
            'items' => [$b]
        ];
    }
}

$hot_issues = [];
foreach ($clusters as $c) {
    // Hitung berapa media berbeda yang meliput
    $sources = array_unique(array_column($c['items'], 'sumber'));
    if (count($sources) >= 3) { // Minimal 3 media meliput isu yang sama
        $c['jumlah_media'] = count($sources);
        $c['sources'] = $sources;
        $hot_issues[] = $c;
    }
}

// Urutkan dari yang paling banyak diliput
usort($hot_issues, function($a, $b) {
    return count($b['items']) <=> count($a['items']);
});

$hot_issues = array_slice($hot_issues, 0, 5); // Ambil Top 5
?>
        <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
            <h4 class="fw-bold m-0 text-slate-800">Dashboard Interaktif</h4>
            <div>
                <button type="button" class="btn btn-danger btn-sm fw-bold shadow-sm ms-1" onclick="exportPDF()">
                    <i class="fas fa-file-pdf me-1"></i> Export PDF
                </button>
                <button type="button" class="btn btn-success btn-sm fw-bold shadow-sm ms-1" onclick="exportExcelDashboard()">
                    <i class="fas fa-file-excel me-1"></i> Export Excel
                </button>
                <span class="badge bg-primary rounded-pill px-3 py-2 ms-2" style="font-size: 0.9rem;">
                    <i class="fas fa-building me-1"></i> <?= htmlspecialchars($nama_instansi) ?>
                </span>
            </div>
        </div>





        <!-- Combined Slider and Cards Layout -->
        <?php if(!empty($trending)): ?>
        <div class="row">
            <div class="col-md-6 grid-margin stretch-card">
                <div class="card card-tale">
                    <div id="trendingCarousel" class="carousel slide" data-bs-ride="carousel" style="width: 100%; height: 100%;">
                        <div class="carousel-inner" style="height: 100%;">
                            <?php foreach($trending as $index => $t): 
                                $img = $t['thumbnail'] ? $t['thumbnail'] : 'assets_skydash/images/dashboard/people.svg';
                            ?>
                            <div class="carousel-item <?= $index==0 ? 'active' : '' ?>" style="height: 100%;">
                                <div class="card-people mt-auto" style="position: relative; height: 100%; padding-top: 0;">
                                    <img src="<?= htmlspecialchars($img) ?>" alt="people" style="width: 100%; height: 300px; object-fit: cover; opacity: 0.3;">
                                    <div class="weather-info" style="position: absolute; bottom: 30px; left: 30px; right: 30px; text-shadow: 1px 1px 4px rgba(0,0,0,0.8);">
                                        <div class="d-flex flex-column">
                                            <div class="mb-2">
                                                <span class="badge bg-danger"><i class="fas fa-fire me-1"></i> Trending Terbaru</span>
                                            </div>
                                            <div>
                                                <h3 class="mb-2 font-weight-normal text-white" style="line-height: 1.4;"><?= htmlspecialchars($t['judul']) ?></h3>
                                            </div>
                                            <div>
                                                <p class="font-weight-normal text-white d-none d-md-block" style="opacity: 0.9;"><?= htmlspecialchars(mb_strimwidth($t['cuplikan'], 0, 150, '...')) ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <button class="carousel-control-prev" type="button" data-bs-target="#trendingCarousel" data-bs-slide="prev">
                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        </button>
                        <button class="carousel-control-next" type="button" data-bs-target="#trendingCarousel" data-bs-slide="next">
                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6 grid-margin transparent">
                <div class="row">
                    <div class="col-md-6 mb-4 stretch-card transparent">
                        <div class="card card-tale">
                            <div class="card-body">
                                <p class="mb-4 fw-bold">Total Berita</p>
                                <p class="fs-30 mb-2"><?= number_format($stat_total) ?></p>
                                <p>Total keseluruhan</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4 stretch-card transparent">
                        <div class="card card-dark-blue">
                            <div class="card-body">
                                <p class="mb-4 fw-bold">Sentimen Positif</p>
                                <p class="fs-30 mb-2"><?= number_format($stat_positif) ?></p>
                                <p>Berita bernada baik</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-4 mb-lg-0 stretch-card transparent">
                        <div class="card card-light-danger">
                            <div class="card-body">
                                <p class="mb-4 fw-bold">Sentimen Negatif</p>
                                <p class="fs-30 mb-2"><?= number_format($stat_negatif_num) ?></p>
                                <p>Butuh atensi segera</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 stretch-card transparent">
                        <div class="card card-light-blue">
                            <div class="card-body">
                                <p class="mb-4 fw-bold">Sentimen Netral</p>
                                <p class="fs-30 mb-2"><?= number_format($stat_netral) ?></p>
                                <p>Informasi netral</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Charts Row -->
        <div class="row">
            <div class="col-12 mb-4">
                <div class="card shadow-sm border-0">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap">
                            <div>
                                <p class="card-title fw-bold m-0"><i class="fa-solid fa-building-flag text-danger me-2"></i>Analisis Sentimen Berita Per SKPD</p>
                                <p class="font-weight-500 text-muted small m-0">Perbandingan jumlah berita bernada positif vs berita negatif/peringatan pada tiap Perangkat Daerah.</p>
                            </div>
                            <span class="badge bg-danger bg-opacity-10 text-danger fw-bold rounded-pill px-3 py-2">
                                <i class="fa-solid fa-triangle-exclamation me-1"></i> Warning Indicator
                            </span>
                        </div>
                        <div style="height: 380px;">
                            <div id="skpdSentimentChart" class="apex-charts" dir="ltr"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Chart Isu Publik SP4N LAPOR per SKPD -->
        <div class="row">
            <div class="col-12 mb-4">
                <div class="card shadow-sm border-0">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap">
                            <div>
                                <p class="card-title fw-bold m-0"><i class="fa-solid fa-bullhorn text-warning me-2"></i>Frekuensi Isu Publik SP4N LAPOR! Per SKPD</p>
                                <p class="font-weight-500 text-muted small m-0">Statistik aduan dan keluhan masyarakat yang didisposisikan ke masing-masing SKPD periode ini.</p>
                            </div>
                            <span class="badge bg-warning bg-opacity-10 text-dark fw-bold rounded-pill px-3 py-2">
                                <i class="fa-solid fa-users me-1"></i> Keluhan Masyarakat
                            </span>
                        </div>
                        <div style="height: 350px;">
                            <div id="laporSkpdChart" class="apex-charts" dir="ltr"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12 mb-4">
                <div class="card">
                    <div class="card-body">
                        <p class="card-title">Jumlah Berita Per Media</p>
                        <p class="font-weight-500">Statistik jumlah pemberitaan berdasarkan sumber media (Sales Report Style).</p>
                        <div style="height: 300px;">
                            <div id="mediaBarChart" class="apex-charts" dir="ltr"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mb-4">
            <div class="col-lg-8 mb-4 mb-lg-0">
                <div class="card">
                    <div class="card-body">
                        <p class="card-title">Kategori Topik Berita</p>
                        <p class="font-weight-500">Distribusi berita berdasarkan kategori (Detailed Reports Style).</p>
                        <div style="height: 300px; display:flex; justify-content:center;">
                            <div id="kategoriBarChart" style="width: 100%; height: 100%;"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-body">
                        <p class="card-title">Proporsi Sentimen</p>
                        <p class="font-weight-500">Persentase sentimen (Detailed Reports Style).</p>
                        <div style="height: 300px; display:flex; justify-content:center;">
                            <div id="sentimenPieChart" class="apex-charts" dir="ltr"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Isu Hangat (Trending Clustering) -->
        <?php if(!empty($hot_issues)): 
            $wa_trending_text = "*Laporan Berita Trending*\n\n";
            foreach($hot_issues as $idx => $issue) {
                $judul = $issue['judul_utama'];
                $link = $issue['items'][0]['link'];
                $media_list = implode(', ', $issue['sources']);
                $wa_trending_text .= ($idx + 1) . ". *" . $judul . "*\n";
                $wa_trending_text .= $link . "\n";
                $wa_trending_text .= "_Diliput oleh media berbeda: " . $media_list . "_\n\n";
            }
        ?>
        <div class="card border border-warning" style="background: linear-gradient(135deg, #fffbeb, #fef3c7);">
            <div class="card-body">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <div class="d-flex align-items-center">
                        <div class="me-3" style="font-size: 2rem; color: #ef4444;"><i class="fas fa-fire-alt"></i></div>
                        <div>
                            <h4 class="card-title m-0">Berita Trending</h4>
                            <p class="text-muted small m-0">Berita yang paling banyak diliput media dalam bulan ini.</p>
                        </div>
                    </div>
                    <button type="button" class="btn btn-success btn-sm fw-bold" onclick="kirimWATrending()"><i class="fab fa-whatsapp me-1"></i> Kirim WA</button>
                </div>
            
            <div class="row g-3">
                <?php foreach($hot_issues as $index => $issue): ?>
                <div class="col-md-6 col-lg-4">
                    <div class="card h-100 border-0 shadow-sm" style="border-radius: 10px;">
                        <div class="card-body">
                            <span class="badge bg-danger mb-2">🔥 Trending #<?= $index + 1 ?></span>
                            <h6 class="fw-bold mb-2" style="font-size: 0.95rem; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;" title="<?= htmlspecialchars($issue['judul_utama']) ?>">
                                <?= htmlspecialchars($issue['judul_utama']) ?>
                            </h6>
                            <p class="text-muted small mb-3">
                                Diliput oleh <strong><?= $issue['jumlah_media'] ?> media berbeda</strong> dengan total <?= count($issue['items']) ?> artikel terkait.
                            </p>
                            <div class="d-flex flex-wrap gap-1 mb-3">
                                <?php foreach(array_slice($issue['sources'], 0, 3) as $src): ?>
                                    <span class="badge bg-light text-dark border"><?= htmlspecialchars($src) ?></span>
                                <?php endforeach; ?>
                                <?php if(count($issue['sources']) > 3): ?>
                                    <span class="badge bg-light text-dark border">+<?= count($issue['sources']) - 3 ?> lainnya</span>
                                <?php endif; ?>
                            </div>
                            <button class="btn btn-sm btn-outline-primary w-100" type="button" data-bs-toggle="collapse" data-bs-target="#collapseIssue<?= $index ?>" aria-expanded="false" aria-controls="collapseIssue<?= $index ?>">
                                Lihat Daftar Berita
                            </button>
                            <div class="collapse mt-2" id="collapseIssue<?= $index ?>">
                                <div class="list-group list-group-flush rounded border">
                                    <?php foreach($issue['items'] as $item): ?>
                                        <a href="<?= htmlspecialchars($item['link']) ?>" target="_blank" class="list-group-item list-group-item-action py-2 px-3">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div class="text-truncate" style="max-width: 80%; font-size: 0.8rem;" title="<?= htmlspecialchars($item['judul']) ?>">
                                                    <?= htmlspecialchars($item['judul']) ?>
                                                </div>
                                                <small class="text-muted" style="font-size: 0.7rem;"><i class="fas fa-external-link-alt"></i></small>
                                            </div>
                                            <div class="small text-muted" style="font-size: 0.7rem;"><?= htmlspecialchars($item['sumber']) ?></div>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Control Panel Full Width Above Table -->
        <div class="card">
            <div class="card-body">
                <h4 class="card-title mb-4">Control Panel AI Engine</h4>
                <div class="row align-items-center">
                    <div class="col-md-3">
                        <button class="btn btn-primary w-100 py-3 btn-run" onclick="jalankanEngine()" style="font-size: 1.1rem;">
                            <i class="fas fa-play me-2"></i> Jalankan Engine
                        </button>
                    </div>
                    <div class="col-md-9">
                        <div class="log-box-container">
                            <div class="log-box-header">
                                <div class="log-dot dot-red"></div>
                                <div class="log-dot dot-yellow"></div>
                                <div class="log-dot dot-green"></div>
                                <div class="log-title">cron_engine.php — bash</div>
                            </div>
                            <div class="log-box" id="logBox"><p class="log-info">> Sistem siap dijalankan...</p></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        
        



        <!-- Filter Area -->
        <div class="filter-form mb-4 animate-up delay-4">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-2">
                    <label class="form-label fw-bold text-muted small mb-1">Tanggal</label>
                    <select name="tanggal" class="form-select border-0 shadow-sm">
                        <option value="">Semua</option>
                        <?php for($d=1; $d<=31; $d++) {
                            $val = str_pad($d, 2, "0", STR_PAD_LEFT);
                            echo "<option value=\"$val\" ".(($filter_tanggal == $val) ? 'selected' : '').">$val</option>";
                        } ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-bold text-muted small mb-1">Bulan</label>
                    <select name="bulan" class="form-select border-0 shadow-sm">
                        <?php 
                        $months = ['01'=>'Januari', '02'=>'Februari', '03'=>'Maret', '04'=>'April', '05'=>'Mei', '06'=>'Juni', '07'=>'Juli', '08'=>'Agustus', '09'=>'September', '10'=>'Oktober', '11'=>'November', '12'=>'Desember'];
                        foreach($months as $num => $name) {
                            echo "<option value=\"$num\" ".(($filter_bulan == $num) ? 'selected' : '').">$name</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label fw-bold text-muted small mb-1">Tahun</label>
                    <select name="tahun" class="form-select border-0 shadow-sm">
                        <?php for($y = date('Y')+1; $y >= 2023; $y--) {
                            echo "<option value=\"$y\" ".(($filter_tahun == $y) ? 'selected' : '').">$y</option>";
                        } ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-bold text-muted small mb-1">Pencarian Teks</label>
                    <input type="text" name="search" class="form-control border-0 shadow-sm" placeholder="Ketik kata kunci..." value="<?= htmlspecialchars($filter_search) ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100 shadow-sm"><i class="fas fa-search me-1"></i> Terapkan</button>
                </div>
            </form>
        </div>



    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('show');
            document.getElementById('sidebarOverlay').classList.toggle('show');
        }

        function submitBulk(action) {
            const checked = $('.row-check:checked');
            if(checked.length === 0) {
                alert('Pilih setidaknya satu berita terlebih dahulu!');
                return;
            }
            if(action === 'delete') {
                if(!confirm('Yakin ingin menghapus ' + checked.length + ' berita terpilih?')) return;
            }
            $('#bulkAction').val(action);
            $('#bulkForm').submit();
        }

        function exportExcel() {
            const checked = $('.row-check:checked');
            if(checked.length === 0) {
                alert('Pilih setidaknya satu berita terlebih dahulu!');
                return;
            }
            $('#bulkAction').val('export_excel');
            $('#bulkForm').submit();
        }

        function kirimWA() {
            const checked = $('.row-check:checked');
            if(checked.length === 0) {
                alert('Pilih setidaknya satu berita terlebih dahulu!');
                return;
            }
            
            let text = "*Laporan Berita MonitorDaerah*\n\n";
            checked.each(function(index) {
                let title = $(this).data('title');
                let url = $(this).data('url');
                text += `${index + 1}. ${title}\n${url}\n\n`;
            });
            
            const waUrl = "https://api.whatsapp.com/send?text=" + encodeURIComponent(text);
            window.open(waUrl, '_blank');
        }

        function kirimWATrending() {
            <?php if(!empty($hot_issues)): ?>
            const text = <?= json_encode($wa_trending_text) ?>;
            const waUrl = "https://api.whatsapp.com/send?text=" + encodeURIComponent(text);
            window.open(waUrl, '_blank');
            <?php endif; ?>
        }

        function jalankanEngine() {
            const btn = document.querySelector('.btn-run');
            const logBox = document.getElementById('logBox');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Memproses...';
            logBox.innerHTML += '<p class="log-info">> Memulai proses scraping & analisa Groq AI...</p>';
            
            fetch('rss_engine.php').then(response => {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            btn.disabled = false;
                            btn.innerHTML = '<i class="fas fa-play me-2"></i> Jalankan Engine & AI';
                            logBox.innerHTML += '<p class="log-success">> Proses stream selesai.</p>';
                            logBox.scrollTop = logBox.scrollHeight;
                            setTimeout(() => location.reload(), 3000);
                            return;
                        }
                        const chunk = decoder.decode(value, { stream: true });
                        logBox.innerHTML += chunk;
                        logBox.scrollTop = logBox.scrollHeight;
                        readStream();
                    });
                }
                readStream();
            }).catch(err => {
                logBox.innerHTML += `<p class="log-error">> Error Connection: ${err}</p>`;
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-play me-2"></i> Jalankan Engine & AI';
            });
        }
        $(document).ready(function() {
            // ApexCharts: Sentimen Berita Per SKPD (Positif vs Negatif vs Netral)
            var optionsSKPD = {
                chart: {
                    height: 360,
                    type: "bar",
                    toolbar: { show: true },
                    stacked: false
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '50%',
                        borderRadius: 6
                    }
                },
                dataLabels: {
                    enabled: true,
                    offsetY: -5,
                    style: { fontSize: '11px', colors: ['#475569'] }
                },
                stroke: {
                    show: true,
                    width: 2,
                    colors: ['transparent']
                },
                series: [
                    { name: "Berita Positif", data: <?= json_encode($skpd_pos_data) ?> },
                    { name: "Berita Negatif (Warning)", data: <?= json_encode($skpd_neg_data) ?> },
                    { name: "Berita Netral", data: <?= json_encode($skpd_net_data) ?> }
                ],
                colors: ["#10b981", "#ef4444", "#94a3b8"],
                xaxis: {
                    categories: <?= json_encode($skpd_labels) ?>,
                    labels: {
                        style: { fontSize: '12px', fontWeight: 600 }
                    }
                },
                yaxis: {
                    title: { text: "Jumlah Berita" }
                },
                fill: { opacity: 1 },
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val + " Berita";
                        }
                    }
                },
                legend: {
                    position: 'top',
                    horizontalAlign: 'right'
                }
            };
            var chartSKPD = new ApexCharts(document.querySelector("#skpdSentimentChart"), optionsSKPD);
            chartSKPD.render();

            // ApexCharts: Frekuensi Isu Publik LAPOR Per SKPD
            var optionsLaporSKPD = {
                chart: {
                    height: 330,
                    type: "bar",
                    toolbar: { show: false }
                },
                plotOptions: {
                    bar: {
                        horizontal: false,
                        columnWidth: '45%',
                        borderRadius: 6,
                        dataLabels: { position: 'top' }
                    }
                },
                dataLabels: {
                    enabled: true,
                    offsetY: -20,
                    style: { fontSize: '12px', colors: ['#b45309'] }
                },
                series: [{
                    name: "Jumlah Keluhan Masyarakat",
                    data: <?= json_encode($lapor_chart_data) ?>
                }],
                colors: ["#f59e0b"],
                xaxis: {
                    categories: <?= json_encode($lapor_chart_labels) ?>,
                    labels: {
                        style: { fontSize: '12px', fontWeight: 600 }
                    }
                },
                yaxis: {
                    title: { text: "Jumlah Laporan" }
                },
                tooltip: {
                    y: {
                        formatter: function (val) {
                            return val + " Laporan";
                        }
                    }
                }
            };
            var chartLaporSKPD = new ApexCharts(document.querySelector("#laporSkpdChart"), optionsLaporSKPD);
            chartLaporSKPD.render();

            // ApexCharts: Jumlah Berita Per Media (Column with Data Labels)
            var optionsMedia = {
                chart: { height: 350, type: "bar", toolbar: { show: false } },
                plotOptions: { bar: { dataLabels: { position: "top" } } },
                dataLabels: {
                    enabled: true,
                    offsetY: -20,
                    style: { fontSize: "12px", colors: ["#304758"] }
                },
                series: [{ name: "Jumlah Berita", data: <?= json_encode($bar_data) ?> }],
                colors: ["#5664d2"],
                grid: { borderColor: "#f1f1f1", padding: { bottom: 10 } },
                xaxis: {
                    categories: <?= json_encode($bar_labels) ?>,
                    position: "bottom",
                    axisBorder: { show: false },
                    axisTicks: { show: false },
                    tooltip: { enabled: true, offsetY: -35 }
                },
                yaxis: {
                    axisBorder: { show: false },
                    axisTicks: { show: false },
                    labels: { show: true }
                }
            };
            var chartMedia = new ApexCharts(document.querySelector("#mediaBarChart"), optionsMedia);
            chartMedia.render();

            // Google Charts: Kategori Topik Berita (Donut Chart)
            google.charts.load("current", {packages:["corechart"]});
            google.charts.setOnLoadCallback(drawKatChart);
            function drawKatChart() {
                var data = google.visualization.arrayToDataTable([
                    ['Kategori', 'Jumlah'],
                    <?php
                        for($i=0; $i<count($kat_labels); $i++) {
                            echo "['" . $kat_labels[$i] . "', " . $kat_data[$i] . "],";
                        }
                    ?>
                ]);

                var options = {
                    pieHole: 0.4,
                    legend: { position: 'bottom' },
                    colors: ["#1cbb8c", "#5664d2", "#fcb92c", "#4aa3ff", "#ff3d60", "#22d3ee", "#f43f5e", "#14b8a6", "#6366f1", "#f97316"],
                    chartArea: {width: '100%', height: '80%'},
                    tooltip: { trigger: 'focus' }
                };

                var chart = new google.visualization.PieChart(document.getElementById('kategoriBarChart'));
                chart.draw(data, options);
            }

            // ApexCharts: Proporsi Sentimen (Radial Chart)
            const totalSentimen = <?= $pie_data['positif'] + $pie_data['negatif'] + $pie_data['netral'] ?>;
            const pPositif = totalSentimen > 0 ? Math.round((<?= $pie_data['positif'] ?> / totalSentimen) * 100) : 0;
            const pNegatif = totalSentimen > 0 ? Math.round((<?= $pie_data['negatif'] ?> / totalSentimen) * 100) : 0;
            const pNetral = totalSentimen > 0 ? Math.round((<?= $pie_data['netral'] ?> / totalSentimen) * 100) : 0;
            
            var optionsSentimen = {
                chart: { height: 350, type: "radialBar" },
                plotOptions: {
                    radialBar: {
                        dataLabels: {
                            name: { fontSize: "22px" },
                            value: { fontSize: "16px" },
                            total: {
                                show: true,
                                label: "Total",
                                formatter: function (w) { return totalSentimen }
                            }
                        }
                    }
                },
                series: [pPositif, pNegatif, pNetral],
                labels: ["Positif", "Negatif", "Netral"],
                colors: ["#10b981", "#ef4444", "#94a3b8"],
                legend: { show: true, position: 'bottom', horizontalAlign: 'center' }
            };
            var chartSentimen = new ApexCharts(document.querySelector("#sentimenPieChart"), optionsSentimen);
            chartSentimen.render();
            
            // Sembunyikan loader dan tampilkan konten dashboard setelah halaman siap
            $('#dashboard-loader').hide();
            $('#dashboard-content').fadeIn('slow');
        });

        function exportExcelDashboard() {
            let baseUrl = 'export_dashboard_excel.php?source=utama';
            const urlParams = new URLSearchParams(window.location.search);
            const queryStr = urlParams.toString();
            if (queryStr) {
                baseUrl += '&' + queryStr;
            }
            window.location.href = baseUrl;
        }

        function exportPDF() {
            const dashboard = document.getElementById('dashboard-content');
            const printBtn = event.currentTarget;
            const originalBtnHtml = printBtn.innerHTML;
            
            printBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            printBtn.disabled = true;

            html2canvas(dashboard, {
                scale: 1.5, 
                useCORS: true,
                logging: false,
                backgroundColor: '#f4f7fa'
            }).then(canvas => {
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('l', 'mm', 'a4'); // Landscape A4
                const pdfWidth = pdf.internal.pageSize.getWidth();
                
                // Header: Logo & Title
                pdf.setFont("helvetica", "bold");
                pdf.setFontSize(16);
                pdf.text("LAPORAN UTAMA DASHBOARD BAPINTAR", pdfWidth / 2, 15, { align: "center" });
                
                pdf.setFont("helvetica", "normal");
                pdf.setFontSize(10);
                pdf.text("Instansi: <?= htmlspecialchars($nama_instansi) ?> | Dicetak pada: <?= date('d M Y H:i') ?>", pdfWidth / 2, 22, { align: "center" });
                
                // Calculate Image Dimensions
                const imgData = canvas.toDataURL('image/jpeg', 0.8);
                const imgWidth = pdfWidth - 20; 
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                
                // Jika gambar lebih panjang dari satu halaman A4 landscape (210mm)
                let heightLeft = imgHeight;
                let position = 30; // start y
                
                pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
                heightLeft -= (210 - position);
                
                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight;
                    pdf.addPage();
                    pdf.addImage(imgData, 'JPEG', 10, position, imgWidth, imgHeight);
                    heightLeft -= 210;
                }
                
                pdf.save("Laporan_Utama_Bapintar_<?= date('Ymd_His') ?>.pdf");
                
                printBtn.innerHTML = originalBtnHtml;
                printBtn.disabled = false;
            }).catch(err => {
                console.error(err);
                alert("Gagal memproses PDF. Pastikan semua gambar memiliki akses CORS.");
                printBtn.innerHTML = originalBtnHtml;
                printBtn.disabled = false;
            });
        }
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
</div> <!-- End of dashboard-content -->
<?php require_once 'layout_footer.php'; ?>
