<?php
require_once 'db.php';
session_start();

if(!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'pimpinan') {
    header("Location: index.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'] : '';

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 Executive Dashboard...</h4>
</div>
<div id="dashboard-content" style="display: none;">
<?php
if (ob_get_level() > 0) { @ob_flush(); } @flush();

// Filter: Hari ini
$hari_ini = date('Y-m-d');
$start_date_hari_ini = "$hari_ini 00:00:00";
$end_date_hari_ini = "$hari_ini 23:59:59";
$where_hari_ini = "b.instansi_id = :instansi_id AND b.tanggal >= :start_date AND b.tanggal <= :end_date";
$params_hari_ini = [
    ':instansi_id' => $instansi_id,
    ':start_date' => $start_date_hari_ini,
    ':end_date' => $end_date_hari_ini
];

// Statistik Hari Ini
$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,
    COUNT(DISTINCT b.sumber) as jml_media
    FROM berita b WHERE $where_hari_ini");
$stmt_stat->execute($params_hari_ini);
$stat_data = $stmt_stat->fetch(PDO::FETCH_ASSOC);

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

// Total OPD
$stmt_opd = $pdo->prepare("SELECT COUNT(*) FROM skpd WHERE instansi_id = ? AND status = 'aktif'");
$stmt_opd->execute([$instansi_id]);
$jml_opd = $stmt_opd->fetchColumn();

// 1. Top 5 Isu Strategis (Bulan Ini untuk konteks lebih luas)
$filter_bulan = date('m');
$filter_tahun = date('Y');
$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);

// Algorithm clustering
$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']));
    $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;
        foreach ($c['items'] as $item) {
            $item_clean = strtolower(preg_replace('/[^a-zA-Z0-9\s]/', ' ', $item['judul']));
            $sim = 0;
            similar_text(str_replace(' ', '', $judul_clean), str_replace(' ', '', $item_clean), $sim);
            if ($sim > 60) { $is_similar = true; break; }
            
            $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));
            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) {
    $sources = array_unique(array_column($c['items'], 'sumber'));
    if (count($sources) >= 3) {
        $c['jumlah_media'] = count($sources);
        $c['sources'] = $sources;
        $hot_issues[] = $c;
    }
}
usort($hot_issues, function($a, $b) { return count($b['items']) <=> count($a['items']); });
$hot_issues = array_slice($hot_issues, 0, 5);

// 2. Top 5 SKPD Sentimen 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, 'negatif' => 0
    ];
}

$stmt_berita_skpd = $pdo->prepare("SELECT b.id, b.judul, b.cuplikan, b.sentimen, b.skpd_id FROM berita b WHERE $where_cluster");
$stmt_berita_skpd->execute([':instansi_id' => $instansi_id, ':bulan' => $filter_bulan, ':tahun' => $filter_tahun]);
$berita_for_skpd = $stmt_berita_skpd->fetchAll(PDO::FETCH_ASSOC);

foreach ($berita_for_skpd as $b) {
    $s_type = strtolower($b['sentimen'] ?? 'netral');
    if ($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) {
            $skpd_stats[$matched_skpd_id]['negatif']++;
        }
    }
}

usort($skpd_stats, function($a, $b) { return $b['negatif'] <=> $a['negatif']; });
$top_negatif_skpd = array_slice(array_filter($skpd_stats, fn($s) => $s['negatif'] > 0), 0, 5);

// 3. Top 5 Berita Terbaru
$stmt_terbaru = $pdo->prepare("SELECT b.judul, b.tanggal, b.link, m.nama as sumber, b.sentimen FROM berita b LEFT 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_terbaru->execute([$instansi_id]);
$top_berita = $stmt_terbaru->fetchAll(PDO::FETCH_ASSOC);

?>
<div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
    <div>
        <h4 class="fw-bold m-0 text-slate-800">Executive Dashboard</h4>
        <p class="text-muted small m-0">Ringkasan strategis opini publik untuk pimpinan</p>
    </div>
    <div>
        <button type="button" class="btn btn-primary btn-sm fw-bold shadow-sm" onclick="showAIBriefing()">
            <i class="fas fa-robot me-1"></i> Generate Rekomendasi AI
        </button>
        <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="exportExcel()">
            <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>

<!-- KPI Cards -->
<div class="row">
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card card-tale">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small">Berita Hari Ini</p>
                <p class="fs-30 mb-0"><?= number_format($stat_total) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card card-dark-blue">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small">Positif</p>
                <p class="fs-30 mb-0"><?= number_format($stat_positif) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card card-light-danger">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small">Negatif</p>
                <p class="fs-30 mb-0"><?= number_format($stat_negatif) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card card-light-blue">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small">Netral</p>
                <p class="fs-30 mb-0"><?= number_format($stat_netral) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card bg-white border">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small text-muted">Jumlah Media</p>
                <p class="fs-30 mb-0 text-dark"><?= number_format($stat_media) ?></p>
            </div>
        </div>
    </div>
    <div class="col-md-2 mb-4 stretch-card transparent">
        <div class="card bg-white border">
            <div class="card-body p-3 text-center">
                <p class="mb-2 fw-bold small text-muted">Jumlah OPD</p>
                <p class="fs-30 mb-0 text-dark"><?= number_format($jml_opd) ?></p>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Top 5 Isu Strategis -->
    <div class="col-lg-6 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <h5 class="fw-bold text-danger mb-3"><i class="fas fa-fire me-2"></i> Top 5 Isu Strategis (Bulan Ini)</h5>
                <?php if(empty($hot_issues)): ?>
                    <p class="text-muted text-center mt-4">Belum ada isu yang trending.</p>
                <?php else: ?>
                    <ul class="list-group list-group-flush">
                        <?php foreach($hot_issues as $idx => $isu): ?>
                            <li class="list-group-item px-0">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="me-auto">
                                        <div class="fw-bold text-dark" style="font-size:0.95rem; line-height:1.4;">
                                            <?= htmlspecialchars($isu['judul_utama']) ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            Diliput <?= $isu['jumlah_media'] ?> media (Total <?= count($isu['items']) ?> artikel)
                                        </div>
                                    </div>
                                    <span class="badge bg-danger rounded-pill">#<?= $idx+1 ?></span>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-6 mb-4">
        <div class="row h-100">
            <!-- Top 5 SKPD -->
            <div class="col-12 mb-4 h-50">
                <div class="card shadow-sm border-0 h-100">
                    <div class="card-body">
                        <h5 class="fw-bold text-warning mb-3"><i class="fas fa-exclamation-triangle me-2"></i> Top 5 OPD Atensi Tinggi</h5>
                        <?php if(empty($top_negatif_skpd)): ?>
                            <p class="text-muted text-center mt-2">Tidak ada keluhan pada OPD bulan ini.</p>
                        <?php else: ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach($top_negatif_skpd as $skpd): ?>
                                    <li class="list-group-item px-0 py-2 d-flex justify-content-between align-items-center">
                                        <span class="fw-bold text-dark"><?= htmlspecialchars($skpd['name']) ?></span>
                                        <span class="badge bg-danger rounded-pill"><?= $skpd['negatif'] ?> Berita Negatif</span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Top 5 Berita Terbaru -->
            <div class="col-12 h-50">
                <div class="card shadow-sm border-0 h-100">
                    <div class="card-body">
                        <h5 class="fw-bold text-primary mb-3"><i class="fas fa-newspaper me-2"></i> Top 5 Berita Terbaru</h5>
                        <ul class="list-group list-group-flush">
                            <?php foreach($top_berita as $tb): 
                                $s_badge = 'bg-secondary';
                                if(strtolower($tb['sentimen']) == 'positif' || strtolower($tb['sentimen']) == 'baik') $s_badge = 'bg-success';
                                if(strtolower($tb['sentimen']) == 'negatif' || strtolower($tb['sentimen']) == 'buruk') $s_badge = 'bg-danger';
                            ?>
                                <li class="list-group-item px-0 py-2">
                                    <div class="fw-bold" style="font-size:0.9rem;">
                                        <a href="<?= htmlspecialchars($tb['link']) ?>" target="_blank" class="text-dark text-decoration-none">
                                            <?= htmlspecialchars($tb['judul']) ?>
                                        </a>
                                    </div>
                                    <div class="d-flex justify-content-between mt-1 small">
                                        <span class="text-muted"><?= htmlspecialchars($tb['sumber']) ?> &bull; <?= date('d M H:i', strtotime($tb['tanggal'])) ?></span>
                                        <span class="badge <?= $s_badge ?>"><?= ucfirst(htmlspecialchars($tb['sentimen'])) ?></span>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal AI Executive Summary & Saran -->
<div class="modal fade" id="modalSaranAI" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-dark text-white border-0">
                <h5 class="modal-title fw-bold"><i class="fas fa-robot me-2"></i>Executive Briefing & Rekomendasi Aksi AI</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div id="ai-loading" class="text-center py-5">
                    <div class="spinner-grow text-primary" role="status" style="width: 3rem; height: 3rem;">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-3 fw-bold text-muted">Sedang menganalisis sentimen negatif hari ini dan merumuskan rekomendasi pimpinan...</p>
                </div>
                <div id="ai-result" style="display:none;">
                    <div class="p-3 bg-light rounded" style="white-space: pre-wrap; font-family: 'Inter', sans-serif; font-size:0.95rem; line-height: 1.6;" id="ai-content"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        $('#dashboard-loader').hide();
        $('#dashboard-content').fadeIn('slow');
    });

    function showAIBriefing() {
        $('#modalSaranAI').modal('show');
        $('#ai-result').hide();
        $('#ai-loading').show();
        
        // Kita kumpulkan ID berita negatif terbaru
        let berita_ids = [];
        <?php
            $negatif_ids = [];
            foreach($berita_for_skpd as $b) {
                if(strtolower($b['sentimen']) == 'negatif' || strtolower($b['sentimen']) == 'buruk') {
                    $negatif_ids[] = $b['id'];
                }
            }
            $negatif_ids = array_slice($negatif_ids, 0, 20);
            echo "berita_ids = " . json_encode($negatif_ids) . ";";
        ?>

        if(berita_ids.length === 0) {
            $('#ai-loading').hide();
            $('#ai-content').html("<i>Tidak ada berita bersentimen negatif yang perlu direkomendasikan saat ini. Kondisi aman.</i>");
            $('#ai-result').show();
            return;
        }

        $.ajax({
            url: 'ajax_saran_ai.php',
            type: 'POST',
            data: { berita_ids: berita_ids },
            dataType: 'json',
            success: function(res) {
                $('#ai-loading').hide();
                if(res.status == 'success') {
                    $('#ai-content').html(res.data);
                    $('#ai-result').fadeIn();
                } else {
                    $('#ai-content').html('<span class="text-danger">Gagal mengambil saran AI: ' + res.message + '</span>');
                    $('#ai-result').show();
                }
            },
            error: function() {
                $('#ai-loading').hide();
                $('#ai-content').html('<span class="text-danger">Terjadi kesalahan koneksi saat menghubungi server AI.</span>');
                $('#ai-result').show();
            }
        });
    }

    function exportExcel() {
        window.location.href = 'export_dashboard_excel.php?source=executive';
    }

    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: 2, 
            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();
            const pdfHeight = pdf.internal.pageSize.getHeight();
            
            // Header: Logo & Title
            pdf.setFont("helvetica", "bold");
            pdf.setFontSize(16);
            pdf.text("LAPORAN EXECUTIVE 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/png');
            // Margin top 30mm, left/right 10mm
            const imgWidth = pdfWidth - 20; 
            const imgHeight = (canvas.height * imgWidth) / canvas.width;
            
            pdf.addImage(imgData, 'PNG', 10, 30, imgWidth, imgHeight);
            pdf.save("Laporan_Executive_Bapintar_<?= date('Ymd_His') ?>.pdf");
            
            printBtn.innerHTML = originalBtnHtml;
            printBtn.disabled = false;
        }).catch(err => {
            console.error(err);
            alert("Gagal memproses PDF.");
            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>
<?php require_once 'layout_footer.php'; ?>
