<?php
require_once 'db.php';

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

// Fetch Instansi Info
$stmt_inst = $pdo->prepare("SELECT nama_instansi, logo_path, keyword_global 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'] : '';
$keywords_raw = $inst_data['keyword_global'] ?? '';

$current_page = 'sosmed.php';

// Filter parameters
$bulan_pilihan = isset($_GET['bulan']) ? $_GET['bulan'] : date('Y-m'); // Default YYYY-MM
$platform_filter = isset($_GET['platform']) ? $_GET['platform'] : '';
$sentimen_filter = isset($_GET['sentimen']) ? $_GET['sentimen'] : '';

// Parse year and month
list($year, $month) = explode('-', $bulan_pilihan);

// 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'];
    
    if (!empty($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) . " postingan sosmed 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) . " postingan sosmed 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_Sosmed_" . date('Y-m-d') . ".xls\"");
            header("Pragma: no-cache");
            header("Expires: 0");

            echo "<table border='1'>";
            echo "<tr><th>No</th><th>Judul/Caption</th><th>Platform/Sumber</th><th>Tanggal</th><th>Sentimen</th><th>Urgensi</th><th>Link</th></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['urgensi'] ?? '') . "</td>";
                echo "<td>" . htmlspecialchars($b['link'] ?? '') . "</td>";
                echo "</tr>";
            }
            echo "</table>";
            exit;
        }
    }
}

// Query untuk mengambil berita / postingan bersumber Medsos (Instagram, TikTok, Facebook)
$sosmed_condition = "(sumber LIKE '%Instagram%' OR sumber LIKE '%TikTok%' OR sumber LIKE '%Facebook%' OR sumber LIKE '%Sosmed%' OR link LIKE '%instagram.com%' OR link LIKE '%tiktok.com%' OR link LIKE '%facebook.com%')";

// Base SQL
$where_clauses = ["instansi_id = ?", "YEAR(tanggal) = ?", "MONTH(tanggal) = ?", $sosmed_condition];
$params = [$instansi_id, $year, $month];

if (!empty($platform_filter)) {
    $where_clauses[] = "(sumber LIKE ? OR link LIKE ?)";
    $params[] = "%$platform_filter%";
    $params[] = "%$platform_filter%";
}

if (!empty($sentimen_filter)) {
    if ($sentimen_filter === 'positif') {
        $where_clauses[] = "(sentimen = 'positif' OR sentimen = 'baik')";
    } elseif ($sentimen_filter === 'negatif') {
        $where_clauses[] = "(sentimen = 'negatif' OR sentimen = 'buruk')";
    } else {
        $where_clauses[] = "sentimen = ?";
        $params[] = $sentimen_filter;
    }
}

$where_sql = implode(" AND ", $where_clauses);

// Metrics Counter
$stmt_metrics = $pdo->prepare("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN sentimen IN ('positif', 'baik') THEN 1 ELSE 0 END) as positif,
    SUM(CASE WHEN sentimen = 'netral' THEN 1 ELSE 0 END) as netral,
    SUM(CASE WHEN sentimen IN ('negatif', 'buruk') THEN 1 ELSE 0 END) as negatif
    FROM berita WHERE instansi_id = ? AND YEAR(tanggal) = ? AND MONTH(tanggal) = ? AND $sosmed_condition");
$stmt_metrics->execute([$instansi_id, $year, $month]);
$metrics = $stmt_metrics->fetch(PDO::FETCH_ASSOC);

// Fetch Posting List
$stmt_list = $pdo->prepare("SELECT * FROM berita WHERE $where_sql ORDER BY tanggal DESC");
$stmt_list->execute($params);
$sosmed_list = $stmt_list->fetchAll(PDO::FETCH_ASSOC);

// Helper fungsi badge platform
function getPlatformBadge($sumber, $link) {
    $src = strtolower($sumber . ' ' . $link);
    if (strpos($src, 'instagram') !== false) {
        return '<span class="badge" style="background: linear-gradient(45deg, #f09433, #e6683c, #dc2743, #cc2366, #bc1888); color:#fff;"><i class="fab fa-instagram me-1"></i> Instagram</span>';
    } elseif (strpos($src, 'tiktok') !== false) {
        return '<span class="badge bg-dark text-white"><i class="fab fa-tiktok me-1"></i> TikTok</span>';
    } elseif (strpos($src, 'facebook') !== false) {
        return '<span class="badge" style="background-color: #1877f2; color:#fff;"><i class="fab fa-facebook me-1"></i> Facebook</span>';
    } else {
        return '<span class="badge bg-info text-white"><i class="fas fa-share-alt me-1"></i> ' . htmlspecialchars($sumber) . '</span>';
    }
}

require_once 'layout_header.php';
?>

        <!-- Header Page (Disamakan persis dengan layout semua_berita.php) -->
        <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"><i class="fas fa-hashtag text-primary me-2"></i>Pemantauan Media Sosial</h4>
                <p class="text-muted mb-0 small">Monitoring isu & keluhan publik dari Instagram, TikTok, dan Facebook — <strong>Bulan <?= date('F Y', strtotime($bulan_pilihan . '-01')) ?></strong></p>
            </div>
            <div class="d-flex align-items-center gap-2">
                <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>
                <button type="button" class="btn btn-primary btn-sm fw-bold shadow-sm" onclick="tarikMedsosBulanIni()">
                    <i class="fas fa-sync-alt me-1"></i> Tarik Postingan Medsos Bulan Ini
                </button>
            </div>
        </div>

        <?= $bulk_msg ?>

        <!-- Cards Statistics -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3 mb-md-0">
                <div class="card border-0 shadow-sm rounded-3 bg-white">
                    <div class="card-body p-3 d-flex align-items-center justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small fw-bold text-uppercase">Total Post Medsos</p>
                            <h3 class="fw-bold mb-0 text-dark"><?= number_format($metrics['total'] ?? 0) ?></h3>
                        </div>
                        <div class="rounded-circle bg-primary bg-opacity-10 p-3 text-primary fs-4">
                            <i class="fas fa-comments"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3 mb-md-0">
                <div class="card border-0 shadow-sm rounded-3 bg-white">
                    <div class="card-body p-3 d-flex align-items-center justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small fw-bold text-uppercase">Postingan Positif</p>
                            <h3 class="fw-bold mb-0 text-success"><?= number_format($metrics['positif'] ?? 0) ?></h3>
                        </div>
                        <div class="rounded-circle bg-success bg-opacity-10 p-3 text-success fs-4">
                            <i class="fas fa-smile"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3 mb-md-0">
                <div class="card border-0 shadow-sm rounded-3 bg-white">
                    <div class="card-body p-3 d-flex align-items-center justify-content-between">
                        <div>
                            <p class="text-muted mb-1 small fw-bold text-uppercase">Postingan Netral</p>
                            <h3 class="fw-bold mb-0 text-secondary"><?= number_format($metrics['netral'] ?? 0) ?></h3>
                        </div>
                        <div class="rounded-circle bg-secondary bg-opacity-10 p-3 text-secondary fs-4">
                            <i class="fas fa-meh"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card border-0 shadow-sm rounded-3 bg-white border-start border-4 border-danger">
                    <div class="card-body p-3 d-flex align-items-center justify-content-between">
                        <div>
                            <p class="text-danger mb-1 small fw-bold text-uppercase">Isu Negatif / Keluhan</p>
                            <h3 class="fw-bold mb-0 text-danger"><?= number_format($metrics['negatif'] ?? 0) ?></h3>
                        </div>
                        <div class="rounded-circle bg-danger bg-opacity-10 p-3 text-danger fs-4">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Bar -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-3">
                <form method="GET" action="sosmed.php" class="row g-2 align-items-center">
                    <div class="col-md-3">
                        <label class="form-label small fw-bold text-muted mb-1">Pilih Bulan</label>
                        <input type="month" name="bulan" class="form-control form-control-sm" value="<?= htmlspecialchars($bulan_pilihan) ?>" onchange="this.form.submit()">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small fw-bold text-muted mb-1">Platform Medsos</label>
                        <select name="platform" class="form-select form-select-sm" onchange="this.form.submit()">
                            <option value="">-- Semua Platform --</option>
                            <option value="instagram" <?= $platform_filter === 'instagram' ? 'selected' : '' ?>>Instagram</option>
                            <option value="tiktok" <?= $platform_filter === 'tiktok' ? 'selected' : '' ?>>TikTok</option>
                            <option value="facebook" <?= $platform_filter === 'facebook' ? 'selected' : '' ?>>Facebook</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small fw-bold text-muted mb-1">Sentimen</label>
                        <select name="sentimen" class="form-select form-select-sm" onchange="this.form.submit()">
                            <option value="">-- Semua Sentimen --</option>
                            <option value="negatif" <?= $sentimen_filter === 'negatif' ? 'selected' : '' ?>>Negatif / Keluhan</option>
                            <option value="positif" <?= $sentimen_filter === 'positif' ? 'selected' : '' ?>>Positif</option>
                            <option value="netral" <?= $sentimen_filter === 'netral' ? 'selected' : '' ?>>Netral</option>
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end gap-2">
                        <button type="submit" class="btn btn-dark btn-sm w-100 mt-4"><i class="fas fa-filter me-1"></i> Filter Data</button>
                        <a href="sosmed.php" class="btn btn-outline-secondary btn-sm mt-4"><i class="fas fa-undo"></i></a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Tabel Postingan Medsos -->
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <form method="POST" id="bulkForm_sosmed">
                    <input type="hidden" name="bulk_action" id="bulkAction_sosmed" value="">
                    
                    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4">
                        <h4 class="card-title text-dark m-0 fw-bold"><i class="fas fa-list me-2"></i>Daftar Postingan Media Sosial</h4>
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn btn-warning text-dark fw-bold btn-sm" onclick="analisisAISosmed()"><i class="fas fa-robot me-1"></i> Analisis & Saran AI</button>
                            <button type="button" class="btn btn-success btn-sm" onclick="kirimWASosmed()"><i class="fab fa-whatsapp me-1"></i> Kirim WA</button>
                            <button type="button" class="btn btn-primary btn-sm" onclick="exportExcelSosmed()"><i class="fas fa-file-excel me-1"></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 me-1"></i> Set Sentimen
                                </button>
                                <ul class="dropdown-menu shadow-sm border-0">
                                    <li><a class="dropdown-item text-success fw-bold" href="#" onclick="submitBulkSosmed('positif')">Set Positif</a></li>
                                    <li><a class="dropdown-item text-danger fw-bold" href="#" onclick="submitBulkSosmed('negatif')">Set Negatif</a></li>
                                    <li><a class="dropdown-item text-secondary fw-bold" href="#" onclick="submitBulkSosmed('netral')">Set Netral</a></li>
                                </ul>
                            </div>
                            <button type="button" class="btn btn-danger btn-sm" onclick="submitBulkSosmed('delete')"><i class="fas fa-trash me-1"></i> Hapus</button>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-hover align-middle" id="sosmedTable">
                            <thead class="table-dark">
                                <tr>
                                    <th style="width: 40px; text-align: center;"><input class="form-check-input" type="checkbox" id="checkAll_sosmed"></th>
                                    <th>Platform</th>
                                    <th>Judul / Caption Postingan</th>
                                    <th>Tanggal</th>
                                    <th>Sentimen</th>
                                    <th>Urgensi</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($sosmed_list)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-4 text-muted">
                                            <i class="fas fa-info-circle fs-4 mb-2 d-block"></i> Belum ada data postingan media sosial untuk periode ini. Klik tombol <strong>"Tarik Postingan Medsos Bulan Ini"</strong> untuk menscan data terbaru.
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($sosmed_list as $b): 
                                        $urgensi = strtolower($b['urgensi'] ?: 'rendah');
                                        $sentimen_raw = strtolower($b['sentimen'] ?: 'netral');
                                        $sentimen = ($sentimen_raw === 'baik') ? 'positif' : (($sentimen_raw === 'buruk') ? 'negatif' : $sentimen_raw);
                                        $badge_sentimen = 'bg-secondary';
                                        if ($sentimen === 'positif') $badge_sentimen = 'bg-success';
                                        if ($sentimen === 'negatif') $badge_sentimen = 'bg-danger';
                                    ?>
                                    <tr>
                                        <td class="text-center">
                                            <input class="form-check-input row-check-sosmed" type="checkbox" name="selected_ids[]" value="<?= $b['id'] ?>" data-title="<?= htmlspecialchars($b['judul']) ?>" data-url="<?= htmlspecialchars($b['link']) ?>">
                                        </td>
                                        <td><?= getPlatformBadge($b['sumber'], $b['link']) ?></td>
                                        <td>
                                            <div class="fw-bold text-wrap" style="color: #1e293b; max-width: 450px;">
                                                <?= htmlspecialchars($b['judul']) ?>
                                            </div>
                                            <?php if (!empty($b['cuplikan'])): ?>
                                                <small class="text-muted d-block text-truncate" style="max-width: 450px;"><?= htmlspecialchars(mb_strimwidth($b['cuplikan'], 0, 120, '...')) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="d-none"><?= strtotime($b['tanggal']) ?></span><?= date('d/m/Y H:i', strtotime($b['tanggal'])) ?></td>
                                        <td><span class="badge <?= $badge_sentimen ?>"><?= strtoupper($sentimen) ?></span></td>
                                        <td><span class="badge bg-<?= $urgensi ?> text-uppercase"><?= $urgensi ?></span></td>
                                        <td>
                                            <div class="btn-group">
                                                <a href="<?= htmlspecialchars($b['link']) ?>" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-external-link-alt"></i> Lihat</a>
                                                <a href="delete_berita.php?id=<?= $b['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus postingan ini?');"><i class="fas fa-trash"></i></a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </form>
            </div>
        </div>

<!-- Modal Log Fetch Medsos -->
<div class="modal fade" id="modalFetchMedsos" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-dark text-white">
                <h5 class="modal-title fw-bold"><i class="fas fa-sync-alt me-2"></i>Scraping Postingan Medsos Bulan Ini</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 bg-dark text-light" style="font-family: monospace; max-height: 400px; overflow-y: auto;" id="fetchLogBox">
                <p class="text-info">> Siap menjalankan pencarian medsos bulan ini...</p>
            </div>
            <div class="modal-footer bg-secondary">
                <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal" onclick="location.reload()">Tutup & Refresh</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal AI Executive Briefing Medsos -->
<div class="modal fade" id="modalSaranAISosmed" tabindex="-1" 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"><i class="fas fa-robot me-2"></i>Executive Briefing & Rekomendasi Aksi AI (Medsos)</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="modalSaranAIBodySosmed">
                <div class="text-center py-5" id="aiLoadingSosmed">
                    <div class="spinner-border text-danger" role="status" style="width: 3rem; height: 3rem;"></div>
                    <p class="mt-3 fw-bold text-muted">Sedang menganalisis postingan medsos negatif dan merumuskan saran pimpinan...</p>
                </div>
                <div id="aiContentSosmed" 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="copySaranAISosmed()"><i class="fas fa-copy me-1"></i> Salin Teks</button>
                <button type="button" class="btn btn-success btn-sm" onclick="kirimWASaranAISosmed()"><i class="fab fa-whatsapp me-1"></i> Kirim WA Briefing Pimpinan</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let currentAISaranTextSosmed = '';

function submitBulkSosmed(action) {
    const checked = $('.row-check-sosmed:checked');
    if (checked.length === 0) {
        alert('Pilih setidaknya satu postingan medsos terlebih dahulu!');
        return;
    }
    if (action === 'delete') {
        if (!confirm('Yakin ingin menghapus ' + checked.length + ' postingan terpilih?')) return;
    }
    $('#bulkAction_sosmed').val(action);
    $('#bulkForm_sosmed').submit();
}

function exportExcelSosmed() {
    const checked = $('.row-check-sosmed:checked');
    if (checked.length === 0) {
        alert('Pilih setidaknya satu postingan medsos terlebih dahulu!');
        return;
    }
    $('#bulkAction_sosmed').val('export_excel');
    $('#bulkForm_sosmed').submit();
}

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

function analisisAISosmed() {
    let checked = $('.row-check-sosmed: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(3)').text().trim();
            beritaData.push({ judul: judul, cuplikan: judul });
        });
    } else {
        $('#sosmedTable tbody tr').slice(0, 10).each(function() {
            let chk = $(this).find('.row-check-sosmed');
            if (chk.length > 0) {
                let judul = chk.data('title') || $(this).find('td:nth-child(3)').text().trim();
                beritaData.push({ judul: judul, cuplikan: judul });
            }
        });
    }

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

    $('#modalSaranAISosmed').modal('show');
    $('#aiLoadingSosmed').show();
    $('#aiContentSosmed').hide().html('');
    currentAISaranTextSosmed = '';

    fetch('ajax_saran_ai.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ berita: beritaData })
    })
    .then(res => res.json())
    .then(data => {
        $('#aiLoadingSosmed').hide();
        if (data.status === 'success') {
            currentAISaranTextSosmed = 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>');

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

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

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

function tarikMedsosBulanIni() {
    $('#modalFetchMedsos').modal('show');
    const logBox = document.getElementById('fetchLogBox');
    logBox.innerHTML = '<p class="text-info">> Memulai scanning postingan medsos bulan ini (Instagram, TikTok, FB)...</p>';
    
    fetch('rss_engine.php?kategori=sosmed').then(response => {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        function readStream() {
            reader.read().then(({ done, value }) => {
                if (done) {
                    logBox.innerHTML += '<p class="text-success fw-bold">> Scanning medsos selesai.</p>';
                    logBox.scrollTop = logBox.scrollHeight;
                    return;
                }
                const chunk = decoder.decode(value, { stream: true });
                logBox.innerHTML += chunk;
                logBox.scrollTop = logBox.scrollHeight;
                readStream();
            });
        }
        readStream();
    }).catch(err => {
        logBox.innerHTML += `<p class="text-danger">> Error Connection: ${err}</p>`;
    });
}

$(document).ready(function() {
    $('#checkAll_sosmed').on('change', function() {
        $('.row-check-sosmed').prop('checked', $(this).prop('checked'));
    });

    if ($.fn.DataTable) {
        $('#sosmedTable').DataTable({
            "pageLength": 25,
            "order": [[3, "desc"]],
            "columnDefs": [
                { "orderable": false, "targets": [0, 6] }
            ],
            "language": {
                "search": "Cari Postingan Medsos:",
                "lengthMenu": "Tampilkan _MENU_ data",
                "info": "Menampilkan _START_ s/d _END_ dari _TOTAL_ postingan",
                "zeroRecords": "Tidak ada data postingan media sosial yang ditemukan"
            }
        });
    }
});
</script>

<?php require_once 'layout_footer.php'; ?>
