<?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;
        }
    }
}

// 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']) : '';
$filter_media = isset($_GET['media']) ? $_GET['media'] : '';

// Ambil list media untuk dropdown
$stmt_media = $pdo->prepare("SELECT DISTINCT nama FROM media WHERE instansi_id = ? ORDER BY nama ASC");
$stmt_media->execute([$instansi_id]);
$list_media_dropdown = $stmt_media->fetchAll(PDO::FETCH_ASSOC);

// Base query parts
$where_clause = "b.instansi_id = :instansi_id AND MONTH(b.tanggal) = :bulan AND YEAR(b.tanggal) = :tahun";
$params = [
    ':instansi_id' => $instansi_id,
    ':bulan' => $filter_bulan,
    ':tahun' => $filter_tahun
];

if ($filter_tanggal != '') {
    $where_clause .= " AND DAY(b.tanggal) = :tanggal";
    $params[':tanggal'] = $filter_tanggal;
}

if ($filter_media != '') {
    $where_clause .= " AND b.sumber = :media";
    $params[':media'] = $filter_media;
}

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 = ? AND m.kategori = 'umum' 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.*, m.kategori as media_kategori 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.*, m.kategori as media_kategori 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);
?>
<?php require_once 'layout_header.php'; ?>

        <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">Semua Berita</h4>
            <div>
                <span class="badge bg-primary rounded-pill px-3 py-2" style="font-size: 0.9rem;">
                    <i class="fas fa-building me-1"></i> <?= htmlspecialchars($nama_instansi) ?>
                </span>
            </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-2">
                    <label class="form-label fw-bold text-muted small mb-1">Media</label>
                    <select name="media" class="form-select border-0 shadow-sm">
                        <option value="">Semua Media</option>
                        <?php foreach($list_media_dropdown as $md): ?>
                            <option value="<?= htmlspecialchars($md['nama']) ?>" <?= ($filter_media === $md['nama']) ? 'selected' : '' ?>><?= htmlspecialchars($md['nama']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <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="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>

        <div class="row g-4 mb-5 animate-up delay-4">
            <!-- Table Full Width -->
            <div class="col-12">
                <div class="content-box">
                    <?= $bulk_msg ?>
                    <form method="POST" id="bulkForm_umum">
                        <input type="hidden" name="bulk_action" id="bulkAction_umum" value="">
                        <div class="d-flex flex-wrap justify-content-between align-items-center mb-4">
                            <h5 class="fw-bold m-0"><i class="fas fa-list-alt text-primary me-2"></i> Semua Berita</h5>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-success btn-sm" onclick="kirimWA('umum')"><i class="fab fa-whatsapp"></i> Kirim WA</button>
                                <button type="button" class="btn btn-primary btn-sm" onclick="exportExcel('umum')"><i class="fas fa-file-excel"></i> Export Excel</button>
                                <div class="dropdown">
                                    <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        <i class="fas fa-tags"></i> Ubah Sentimen
                                    </button>
                                    <ul class="dropdown-menu shadow-sm border-0">
                                        <li><a class="dropdown-item text-success fw-bold" href="#" onclick="submitBulk('positif', 'umum')">Set Positif</a></li>
                                        <li><a class="dropdown-item text-danger fw-bold" href="#" onclick="submitBulk('negatif', 'umum')">Set Negatif</a></li>
                                        <li><a class="dropdown-item text-secondary fw-bold" href="#" onclick="submitBulk('netral', 'umum')">Set Netral</a></li>
                                    </ul>
                                </div>
                                <button type="button" class="btn btn-danger btn-sm" onclick="submitBulk('delete', 'umum')"><i class="fas fa-trash"></i> Hapus</button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped table-borderless report-table align-middle" id="beritaTable">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width: 40px; text-align: center;"><input class="form-check-input" type="checkbox" id="checkAll_umum"></th>
                                        <th>Thumb</th>
                                        <th>Judul Berita</th>
                                        <th>Kategori</th>
                                        <th>Tanggal</th>
                                        <th>Sentimen</th>
                                        <th>Urgensi</th>
                                        <th>Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($berita as $b): 
                                        $sentimen = strtolower($b['sentimen'] ?: 'netral');
                                        $urgensi = strtolower($b['urgensi'] ?: 'rendah');
                                        $sentimen_label = ($sentimen == 'baik') ? 'positif' : (($sentimen == 'buruk') ? 'negatif' : $sentimen);
                                        
                                        $display_kategori = 'UMUM';
                                        if ($b['media_kategori'] === 'google_alert') $display_kategori = 'GOOGLE ALERT';
                                        else if ($b['media_kategori'] === 'pro_pemerintah') $display_kategori = 'PRO PEMERINTAH';
                                    ?>
                                    <tr>
                                        <td class="text-center"><input class="form-check-input row-check-umum" type="checkbox" name="selected_ids[]" value="<?= $b['id'] ?>" data-title="<?= htmlspecialchars($b['judul']) ?>" data-url="<?= htmlspecialchars($b['link']) ?>"></td>
                                        <td>
                                        <?php if($b['thumbnail']): ?>
                                            <img src="<?= htmlspecialchars($b['thumbnail']) ?>" class="news-thumbnail" alt="Thumb">
                                        <?php else: ?>
                                            <div class="news-placeholder"><i class="fas fa-image"></i></div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-wrap" title="<?= htmlspecialchars($b['judul']) ?>">
                                            <a href="<?= htmlspecialchars($b['link']) ?>" target="_blank" class="text-decoration-none text-dark"><?= htmlspecialchars($b['judul']) ?></a>
                                        </div>
                                        <small class="text-muted"><?= htmlspecialchars($b['sumber']) ?></small>
                                    </td>
                                    <td><span class="badge bg-info text-dark"><?= htmlspecialchars($display_kategori) ?></span></td>
                                    <td>
                                        <!-- Sortable format -->
                                        <span class="d-none"><?= strtotime($b['tanggal']) ?></span>
                                        <?= date('d/m/Y', strtotime($b['tanggal'])) ?>
                                    </td>
                                    <td><span class="badge-custom bg-<?= $sentimen ?>"><?= strtoupper($sentimen_label) ?></span></td>
                                    <td><span class="badge-custom bg-<?= $urgensi ?>"><?= strtoupper($urgensi) ?></span></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="<?= htmlspecialchars($b['link']) ?>" target="_blank" class="btn btn-sm btn-light text-primary" title="Cek"><i class="fas fa-external-link-alt"></i></a>
                                            <a href="delete_berita.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-light text-danger" title="Hapus" onclick="return confirm('Hapus berita ini?');"><i class="fas fa-trash"></i></a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Tabel Khusus Berita Negatif -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card" id="tabel-negatif">
            <div class="card-body">
                <form method="POST" id="bulkForm_negatif">
                    <input type="hidden" name="bulk_action" id="bulkAction_negatif" value="">
                    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4">
                        <h4 class="card-title text-danger m-0">Tabel Evaluasi Berita Negatif</h4>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-warning text-dark fw-bold btn-sm" onclick="analisisAISaran()"><i class="fas fa-robot me-1"></i> Analisis & Saran AI</button>
                            <button type="button" class="btn btn-success btn-sm" onclick="kirimWA('negatif')"><i class="fab fa-whatsapp"></i> Kirim WA</button>
                            <button type="button" class="btn btn-primary btn-sm" onclick="exportExcel('negatif')"><i class="fas fa-file-excel"></i> Export Excel</button>
                            <div class="dropdown">
                                <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                    <i class="fas fa-tags"></i> Ubah Sentimen
                                </button>
                                <ul class="dropdown-menu shadow-sm border-0">
                                    <li><a class="dropdown-item text-success fw-bold" href="#" onclick="submitBulk('positif', 'negatif')">Set Positif</a></li>
                                    <li><a class="dropdown-item text-danger fw-bold" href="#" onclick="submitBulk('negatif', 'negatif')">Set Negatif</a></li>
                                    <li><a class="dropdown-item text-secondary fw-bold" href="#" onclick="submitBulk('netral', 'negatif')">Set Netral</a></li>
                                </ul>
                            </div>
                            <button type="button" class="btn btn-danger btn-sm" onclick="submitBulk('delete', 'negatif')"><i class="fas fa-trash"></i> Hapus</button>
                        </div>
                    </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle" id="negatifTable">
                    <thead class="table-danger">
                        <tr>
                            <th style="width: 40px; text-align: center;"><input class="form-check-input" type="checkbox" id="checkAll_negatif"></th>
                            <th>Judul Berita</th>
                            <th>Tanggal</th>
                            <th>Sumber Media</th>
                            <th>Urgensi</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($berita_negatif as $b): 
                            $urgensi = strtolower($b['urgensi'] ?: 'rendah');
                        ?>
                        <tr>
                            <td class="text-center"><input class="form-check-input row-check-negatif" type="checkbox" name="selected_ids[]" value="<?= $b['id'] ?>" data-title="<?= htmlspecialchars($b['judul']) ?>" data-url="<?= htmlspecialchars($b['link']) ?>"></td>
                            <td>
                                <div class="fw-bold text-wrap" style="color: #1e293b;" title="<?= htmlspecialchars($b['judul']) ?>">
                                    <?= htmlspecialchars($b['judul']) ?>
                                </div>
                            </td>
                            <td><span class="d-none"><?= strtotime($b['tanggal']) ?></span><?= date('d/m/Y H:i', strtotime($b['tanggal'])) ?></td>
                            <td><span class="badge bg-secondary"><?= htmlspecialchars($b['sumber']) ?></span></td>
                            <td><span class="badge-custom bg-<?= $urgensi ?>"><?= strtoupper($urgensi) ?></span></td>
                            <td><div class="btn-group">
                                <a href="<?= htmlspecialchars($b['link']) ?>" target="_blank" class="btn btn-sm btn-danger"><i class="fas fa-external-link-alt"></i> Cek</a>
                                <a href="delete_berita.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-outline-danger" title="Hapus" onclick="return confirm('Hapus berita ini?');"><i class="fas fa-trash"></i></a>
                            </div></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal AI Executive Summary & Saran -->
<div class="modal fade" id="modalSaranAI" tabindex="-1" aria-labelledby="modalSaranAILabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title fw-bold" id="modalSaranAILabel"><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" id="modalSaranAIBody">
                <div class="text-center py-5" id="aiLoading">
                    <div class="spinner-border text-danger" role="status" style="width: 3rem; height: 3rem;"></div>
                    <p class="mt-3 fw-bold text-muted">Sedang menganalisis berita negatif dan merumuskan rekomendasi pimpinan...</p>
                </div>
                <div id="aiContent" style="display:none;" class="lh-base"></div>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Tutup</button>
                <button type="button" class="btn btn-outline-dark btn-sm" onclick="copySaranAI()"><i class="fas fa-copy me-1"></i> Salin Teks</button>
                <button type="button" class="btn btn-success btn-sm" onclick="kirimWASaranAI()"><i class="fab fa-whatsapp me-1"></i> Kirim WA Briefing Pimpinan</button>
            </div>
        </div>
    </div>
</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>
        let currentAISaranText = '';

        function analisisAISaran() {
            let checked = $('.row-check-negatif:checked');
            let beritaData = [];

            if (checked.length > 0) {
                checked.each(function() {
                    let row = $(this).closest('tr');
                    let judul = $(this).data('title') || row.find('td:nth-child(2)').text().trim();
                    beritaData.push({ judul: judul, cuplikan: judul });
                });
            } else {
                $('#negatifTable tbody tr').slice(0, 10).each(function() {
                    let chk = $(this).find('.row-check-negatif');
                    if (chk.length > 0) {
                        let judul = chk.data('title') || $(this).find('td:nth-child(2)').text().trim();
                        beritaData.push({ judul: judul, cuplikan: judul });
                    }
                });
            }

            if (beritaData.length === 0) {
                alert('Tidak ada berita negatif yang tersedia untuk dianalisis!');
                return;
            }

            $('#modalSaranAI').modal('show');
            $('#aiLoading').show();
            $('#aiContent').hide().html('');
            currentAISaranText = '';

            fetch('ajax_saran_ai.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ berita: beritaData })
            })
            .then(res => res.json())
            .then(data => {
                $('#aiLoading').hide();
                if (data.status === 'success') {
                    currentAISaranText = data.saran;
                    let formattedContent = data.saran
                        .replace(/### (.*?)\n/g, '<h5 class="fw-bold text-dark mt-4 border-bottom pb-2">$1</h5>')
                        .replace(/🔴 \*\*\[PERLU DITANGGAPI SEGERA\]\*\*/g, '<span class="badge bg-danger fs-6 p-2 mb-2"><i class="fas fa-exclamation-circle me-1"></i> PERLU DITANGGAPI SEGERA</span>')
                        .replace(/🟡 \*\*\[CUKUP DIPANTAU \/ EVALUASI INTERNAL\]\*\*/g, '<span class="badge bg-warning text-dark fs-6 p-2 mb-2"><i class="fas fa-eye me-1"></i> CUKUP DIPANTAU / EVALUASI INTERNAL</span>')
                        .replace(/🟢 \*\*\[TIDAK PERLU DITANGGAPI \/ ABAIKAN\]\*\*/g, '<span class="badge bg-success fs-6 p-2 mb-2"><i class="fas fa-check-circle me-1"></i> TIDAK PERLU DITANGGAPI / ABAIKAN</span>')
                        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                        .replace(/\n/g, '<br>');

                    $('#aiContent').html('<div class="p-3 bg-white rounded shadow-sm border border-1">' + formattedContent + '</div>').show();
                } else {
                    $('#aiContent').html('<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i> ' + (data.message || 'Gagal memproses data.') + '</div>').show();
                }
            })
            .catch(err => {
                $('#aiLoading').hide();
                $('#aiContent').html('<div class="alert alert-danger"><i class="fas fa-exclamation-triangle me-2"></i> Terjadi kesalahan koneksi: ' + err + '</div>').show();
            });
        }

        function copySaranAI() {
            if (!currentAISaranText) return;
            navigator.clipboard.writeText(currentAISaranText).then(() => {
                alert('Hasil Executive Briefing berhasil disalin ke clipboard!');
            }).catch(err => {
                alert('Gagal menyalin: ' + err);
            });
        }

        function kirimWASaranAI() {
            if (!currentAISaranText) return;
            let text = "*EXECUTIVE BRIEFING & REKOMENDASI ISU PUBLIK*\n" +
                       "_Diprosesk oleh MonitorDaerah AI_\n\n" +
                       currentAISaranText;
            const waUrl = "https://api.whatsapp.com/send?text=" + encodeURIComponent(text);
            window.open(waUrl, '_blank');
        }

        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('show');
            document.getElementById('sidebarOverlay').classList.toggle('show');
        }

        function submitBulk(action, type) {
            const checked = $('.row-check-' + type + ':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_' + type).val(action);
            $('#bulkForm_' + type).submit();
        }

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

        function kirimWA(type) {
            const checked = $('.row-check-' + type + ':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() {
            // Check All Logic
            $('#checkAll_umum').on('change', function() {
                $('.row-check-umum').prop('checked', $(this).prop('checked'));
            });
            $('#checkAll_negatif').on('change', function() {
                $('.row-check-negatif').prop('checked', $(this).prop('checked'));
            });

            // DataTables
            $('#beritaTable').DataTable({
                "pageLength": 50,
                "order": [[4, "desc"]], // Sort by Tanggal column (now index 4)
                "columnDefs": [
                    { "orderable": false, "targets": [0, 1] } // Disable sorting for checkbox, thumb
                ],
                "language": { "search": "Pencarian:", "lengthMenu": "Tampilkan _MENU_ data", "info": "Menampilkan _START_ s/d _END_ dari _TOTAL_ berita", "infoEmpty": "Data kosong", "zeroRecords": "Tidak ada data yang ditemukan", "paginate": { "first": "Awal", "last": "Akhir", "next": ">>", "previous": "<<" } }
            });

            $('#negatifTable').DataTable({
                "pageLength": 50,
                "order": [[2, "desc"]], 
                "columnDefs": [
                    { "orderable": false, "targets": [0] } // Disable sorting for checkbox
                ],
                "language": { "search": "Cari Berita Negatif:", "lengthMenu": "Tampilkan _MENU_ data", "info": "Menampilkan _START_ s/d _END_ dari _TOTAL_ berita", "infoEmpty": "Aman, tidak ada berita negatif", "zeroRecords": "Tidak ada data yang ditemukan", "paginate": { "first": "Awal", "last": "Akhir", "next": ">>", "previous": "<<" } }
            });

        });
    </script>
<?php require_once 'layout_footer.php'; ?>
