<?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'] : '';

// Handle CRUD Operations
$msg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action']) && $_POST['action'] == 'add') {
        $nama = $_POST['nama'];
        $url = $_POST['url'];
        $html_thumbnail = $_POST['html_thumbnail'];
        $kategori = $_POST['kategori'] ?? 'umum';

        $stmt = $pdo->prepare("INSERT INTO media (instansi_id, nama, url, html_thumbnail, kategori) VALUES (?, ?, ?, ?, ?)");
        if ($stmt->execute([$instansi_id, $nama, $url, $html_thumbnail, $kategori])) {
            $msg = "<div class='alert alert-success'>Media berhasil ditambahkan.</div>";
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'edit') {
        $id = $_POST['id'];
        $nama = $_POST['nama'];
        $url = $_POST['url'];
        $html_thumbnail = $_POST['html_thumbnail'];
        $kategori = $_POST['kategori'];

        $stmt = $pdo->prepare("UPDATE media SET nama = ?, url = ?, html_thumbnail = ?, kategori = ? WHERE id = ? AND instansi_id = ?");
        if ($stmt->execute([$nama, $url, $html_thumbnail, $kategori, $id, $instansi_id])) {
            $msg = "<div class='alert alert-success'>Media berhasil diperbarui.</div>";
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'delete') {
        $id = (int) $_POST['id'];
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM media WHERE id = ? AND instansi_id = ?");
            if ($stmt->execute([$id, $instansi_id])) {
                $msg = "<div class='alert alert-success'>Media berhasil dihapus.</div>";
            }
        } else {
            $msg = "<div class='alert alert-danger'>Gagal menghapus: ID media tidak valid (kemungkinan struktur database belum AUTO_INCREMENT).</div>";
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'import_xml') {
        if (isset($_FILES['xml_file']) && $_FILES['xml_file']['error'] == UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['xml_file']['tmp_name'];
            $fileName = $_FILES['xml_file']['name'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            if ($fileExtension === 'xml') {
                $xml = simplexml_load_file($fileTmpPath);
                if ($xml && isset($xml->item)) {
                    $imported_count = 0;
                    $stmt_import = $pdo->prepare("INSERT INTO media (instansi_id, nama, url, kategori, html_thumbnail) VALUES (?, ?, ?, ?, ?)");
                    
                    foreach ($xml->item as $item) {
                        $nama = trim((string)$item->nama);
                        $url = trim((string)$item->url);
                        $kategori = trim((string)$item->kategori);
                        if (empty($kategori)) $kategori = 'umum';
                        $html_thumbnail = trim((string)$item->html_thumbnail);
                        
                        $stmt_check = $pdo->prepare("SELECT id FROM media WHERE instansi_id = ? AND url = ?");
                        $stmt_check->execute([$instansi_id, $url]);
                        
                        if ($stmt_check->rowCount() == 0 && !empty($nama) && !empty($url)) {
                            $stmt_import->execute([$instansi_id, $nama, $url, $kategori, $html_thumbnail]);
                            $imported_count++;
                        }
                    }
                    $msg = "<div class='alert alert-success'>$imported_count media berhasil diimport dari file XML.</div>";
                } else {
                    $msg = "<div class='alert alert-danger'>Format XML tidak valid atau tidak memiliki tag &lt;item&gt;.</div>";
                }
            } else {
                $msg = "<div class='alert alert-danger'>Harap unggah file berekstensi .xml</div>";
            }
        } else {
            $msg = "<div class='alert alert-danger'>Terjadi kesalahan saat mengunggah file.</div>";
        }
    }
}

if (isset($_GET['action']) && $_GET['action'] == 'export_xml') {
    $stmt = $pdo->prepare("SELECT * FROM media WHERE instansi_id = ?");
    $stmt->execute([$instansi_id]);
    $media_export = $stmt->fetchAll(PDO::FETCH_ASSOC);

    header('Content-Type: text/xml');
    header('Content-Disposition: attachment; filename="export_media_' . date('Ymd_His') . '.xml"');

    $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><media_list></media_list>');
    foreach ($media_export as $m) {
        $item = $xml->addChild('item');
        $item->addChild('nama', htmlspecialchars($m['nama']));
        $item->addChild('url', htmlspecialchars($m['url']));
        $item->addChild('kategori', htmlspecialchars($m['kategori']));
        if (!empty($m['html_thumbnail'])) {
            $item->addChild('html_thumbnail', htmlspecialchars($m['html_thumbnail']));
        }
    }
    echo $xml->asXML();
    exit;
}

// Ambil data media beserta jumlah berita bulan ini
$stmt = $pdo->prepare("
    SELECT m.*, 
           (SELECT COUNT(b.id) FROM berita b 
            WHERE b.sumber = m.nama 
            AND b.instansi_id = m.instansi_id 
            AND MONTH(b.tanggal) = MONTH(CURRENT_DATE()) 
            AND YEAR(b.tanggal) = YEAR(CURRENT_DATE())) as jumlah_berita 
    FROM media m 
    WHERE m.instansi_id = ? 
    ORDER BY m.kategori ASC, m.id DESC
");
$stmt->execute([$instansi_id]);
$media_list = $stmt->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">Manajemen Media Sumber</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>

        <?= $msg ?>

        <div class="card card-body">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h5 class="fw-bold m-0"><i class="fas fa-database text-primary me-2"></i> Daftar Sumber Scraping</h5>
                <div>
                    <a href="media.php?action=export_xml" class="btn btn-warning btn-sm me-2"><i class="fas fa-file-export"></i> Export XML</a>
                    <button class="btn btn-success btn-sm me-2" data-bs-toggle="modal" data-bs-target="#modalImport"><i class="fas fa-file-import"></i> Import XML</button>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalMedia" onclick="resetForm()"><i class="fas fa-plus"></i> Tambah Media Baru</button>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-hover align-middle nowrap" id="mediaTable" style="width:100%">
                    <thead class="table-light">
                        <tr>
                            <th>Logo</th>
                            <th>Nama Media</th>
                            <th>Kategori</th>
                            <th>URL RSS / XML</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($media_list as $m): 
                            $kat = strtolower($m['kategori'] ?? 'umum');
                            $badge_class = 'bg-' . $kat;
                            if(!in_array($kat, ['umum', 'oposisi', 'google_alert', 'pro'])) $badge_class = 'bg-secondary text-white';
                        ?>
                        <tr>
                            <td>
                                <?php if($m['html_thumbnail']): ?>
                                    <img src="<?= htmlspecialchars($m['html_thumbnail']) ?>" style="width:40px; height:40px; object-fit:contain; border-radius:4px; background:#f1f5f9; padding:2px;">
                                <?php else: ?>
                                    <div style="width:40px; height:40px; background:#e2e8f0; border-radius:4px; display:flex; align-items:center; justify-content:center; color:#94a3b8;"><i class="fas fa-image"></i></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-bold text-slate-800"><?= htmlspecialchars($m['nama']) ?></div>
                                <div class="small text-muted" style="margin-top: 4px;"><i class="fas fa-newspaper me-1"></i><?= (int)$m['jumlah_berita'] ?> berita (bulan ini)</div>
                            </td>
                            <td>
                                <span class="d-none"><?= $kat ?></span>
                                <span class="badge-custom <?= $badge_class ?>"><?= strtoupper(str_replace('_', ' ', $kat)) ?></span>
                            </td>
                            <td>
                                <a href="<?= htmlspecialchars($m['url'] ?? $m['xml_link'] ?? '#') ?>" target="_blank" class="text-truncate d-inline-block" style="max-width: 250px;" title="<?= htmlspecialchars($m['url'] ?? $m['xml_link'] ?? '') ?>">
                                    <?= htmlspecialchars($m['url'] ?? $m['xml_link'] ?? '-') ?>
                                </a>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-light text-primary" title="Edit Media" onclick="editMedia(<?= htmlspecialchars(json_encode($m)) ?>)">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus media ini?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $m['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-light text-danger" title="Hapus Media">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal Form Media -->
    <div class="modal fade" id="modalMedia" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-primary text-white border-0">
                    <h5 class="modal-title" id="modalTitle">Tambah Media Baru</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="formMedia">
                    <div class="modal-body p-4">
                        <input type="hidden" name="action" id="formAction" value="add">
                        <input type="hidden" name="id" id="formId" value="">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Nama Media</label>
                            <input type="text" name="nama" id="formNama" class="form-control" required placeholder="Contoh: Detik News">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Kategori Media</label>
                            <select name="kategori" id="formKategori" class="form-select">
                                <option value="umum">Umum</option>
                                <option value="oposisi">Oposisi</option>
                                <option value="pro">Pro Pemerintah</option>
                                <option value="google_alert">Google Alert</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Link RSS (URL)</label>
                            <input type="url" name="url" id="formUrl" class="form-control" required placeholder="https://example.com/rss">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Logo Media (URL Gambar)</label>
                            <input type="url" name="html_thumbnail" id="formLogo" class="form-control" placeholder="https://example.com/logo.png">
                            <small class="text-muted">Masukkan URL gambar (JPG/PNG). Akan disimpan di html_thumbnail.</small>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pb-4 pe-4">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Data</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Form Import XML -->
    <div class="modal fade" id="modalImport" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-success text-white border-0">
                    <h5 class="modal-title"><i class="fas fa-file-import me-2"></i>Import Media via XML</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" enctype="multipart/form-data">
                    <div class="modal-body p-4">
                        <input type="hidden" name="action" value="import_xml">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Upload File XML</label>
                            <input type="file" name="xml_file" class="form-control" accept=".xml" required>
                            <small class="text-muted d-block mt-2">Pastikan format XML sesuai. Media dengan URL yang sudah ada tidak akan diduplikat.</small>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pb-4 pe-4">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-success px-4">Mulai Import</button>
                    </div>
                </form>
            </div>
        </div>
    
    
    
    
    
    
    
    
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('show');
            document.getElementById('sidebarOverlay').classList.toggle('show');
        }

        function resetForm() {
            document.getElementById('modalTitle').innerText = 'Tambah Media Baru';
            document.getElementById('formAction').value = 'add';
            document.getElementById('formId').value = '';
            document.getElementById('formNama').value = '';
            document.getElementById('formKategori').value = 'umum';
            document.getElementById('formUrl').value = '';
            document.getElementById('formLogo').value = '';
        }

        function editMedia(data) {
            document.getElementById('modalTitle').innerText = 'Edit Media';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('formId').value = data.id;
            document.getElementById('formNama').value = data.nama;
            
            // Set Kategori if exists in options
            if (data.kategori) {
                document.getElementById('formKategori').value = data.kategori.toLowerCase();
            } else {
                document.getElementById('formKategori').value = 'umum';
            }
            
            document.getElementById('formUrl').value = data.url || data.xml_link || '';
            document.getElementById('formLogo').value = data.html_thumbnail || '';
            
            new bootstrap.Modal(document.getElementById('modalMedia')).show();
        }

        $(document).ready(function() {
            $('#mediaTable').DataTable({
                "pageLength": 50,
                "order": [[2, "asc"]],
                "responsive": true,
                "language": {
                    "search": "Cari Media:",
                    "lengthMenu": "Tampilkan _MENU_ media",
                    "info": "Menampilkan _START_ s/d _END_ dari _TOTAL_ media",
                    "infoEmpty": "Data media kosong",
                    "zeroRecords": "Tidak ditemukan media yang sesuai",
                    "paginate": { "first": "Awal", "last": "Akhir", "next": ">>", "previous": "<<" }
                }
            });
        });
    </script>
<?php require_once 'layout_footer.php'; ?>
