<?php
// get_station_info.php
require_once '../includes/auth.php';

if (!isPenguji()) {
    header('HTTP/1.1 403 Forbidden');
    exit(json_encode(['success' => false, 'error' => 'Unauthorized']));
}

header('Content-Type: application/json; charset=utf-8');

$station_id = $_POST['station_id'] ?? null;

if (!$station_id) {
    echo json_encode(['success' => false, 'error' => 'Station ID required']);
    exit;
}

try {
    // Ambil data station
    $stmt = $pdo->prepare("SELECT * FROM stations WHERE id = ?");
    $stmt->execute([$station_id]);
    $station = $stmt->fetch();

    if (!$station) {
        echo json_encode(['success' => false, 'error' => 'Station tidak ditemukan']);
        exit;
    }

    // Function untuk render HTML content dengan gambar
    function renderHTMLContent($content) {
        if (empty($content)) return '';
        
        // Decode HTML entities
        $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
        
        // Security: Remove potentially dangerous tags and attributes
        $content = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $content);
        $content = preg_replace('/on\w+=\s*"[^"]*"\s*/i', '', $content);
        $content = preg_replace('/on\w+=\s*\'[^\']*\'\s*/i', '', $content);
        
        return $content;
    }

    // Render content dengan HTML
    $deskripsi_html = renderHTMLContent($station['deskripsi']);
    $instruksi_peserta_html = renderHTMLContent($station['instruksi_peserta']);
    $instruksi_penguji_html = renderHTMLContent($station['instruksi_penguji']);

    echo json_encode([
        'success' => true,
        'deskripsi' => $deskripsi_html ?: '<em>Tidak ada deskripsi</em>',
        'instruksi_peserta' => $instruksi_peserta_html ?: '<em>Tidak ada instruksi untuk peserta</em>',
        'instruksi_penguji' => $instruksi_penguji_html ?: '<em>Tidak ada instruksi untuk penguji</em>'
    ]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>