<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/functions.php';

// Cek apakah user sudah login dan memiliki akses admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../login.php');
    exit;
}

$error = '';
$success = '';
$edit_mode = false;
$editing_soal = null;

// Handle edit mode
if (isset($_GET['edit_id']) && !empty($_GET['edit_id'])) {
    $edit_mode = true;
    try {
        $stmt = $pdo->prepare("SELECT * FROM bank_soal_teori WHERE id = ?");
        $stmt->execute([$_GET['edit_id']]);
        $editing_soal = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$editing_soal) {
            $error = 'Soal tidak ditemukan!';
            $edit_mode = false;
        }
    } catch (PDOException $e) {
        $error = 'Gagal mengambil data soal: ' . $e->getMessage();
        $edit_mode = false;
    }
}

// Handle update soal
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_soal'])) {
    $soal_id = $_POST['soal_id'] ?? '';
    $nomor_registrasi = $_POST['nomor_registrasi'] ?? '';
    $tinjauan1 = $_POST['tinjauan1'] ?? '';
    $tinjauan2 = $_POST['tinjauan2'] ?? '';
    $tinjauan3 = $_POST['tinjauan3'] ?? '';
    $vignette = $_POST['vignette'] ?? '';
    $pertanyaan = $_POST['pertanyaan'] ?? '';
    $pilihan_a = $_POST['pilihan_a'] ?? '';
    $pilihan_b = $_POST['pilihan_b'] ?? '';
    $pilihan_c = $_POST['pilihan_c'] ?? '';
    $pilihan_d = $_POST['pilihan_d'] ?? '';
    $pilihan_e = $_POST['pilihan_e'] ?? '';
    $kunci = $_POST['kunci'] ?? '';
    $department = $_POST['department'] ?? '';
    $alasan_singkat = $_POST['alasan_singkat'] ?? '';
    $referensi = $_POST['referensi'] ?? '';
    $penulis = $_POST['penulis'] ?? '';
    
    // Validasi data
    if (empty($nomor_registrasi) || empty($tinjauan1) || empty($pertanyaan)) {
        $error = 'Nomor Registrasi, Tinjauan 1, dan Pertanyaan harus diisi!';
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE bank_soal_teori SET 
                nomor_registrasi = ?, tinjauan1 = ?, tinjauan2 = ?, tinjauan3 = ?, 
                vignette = ?, pertanyaan = ?, pilihan_a = ?, pilihan_b = ?, 
                pilihan_c = ?, pilihan_d = ?, pilihan_e = ?, kunci = ?, 
                department = ?, alasan_singkat = ?, referensi = ?, penulis = ?
                WHERE id = ?");
            
            $stmt->execute([
                $nomor_registrasi, $tinjauan1, $tinjauan2, $tinjauan3,
                $vignette, $pertanyaan, $pilihan_a, $pilihan_b,
                $pilihan_c, $pilihan_d, $pilihan_e, $kunci,
                $department, $alasan_singkat, $referensi, $penulis, $soal_id
            ]);
            
            $success = 'Soal berhasil diperbarui!';
            $edit_mode = false;
            
            // Redirect ke preview mode setelah update
            header('Location: ?preview_id=' . $soal_id);
            exit;
            
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan: ' . $e->getMessage();
        }
    }
}

// Handle cancel edit
if (isset($_GET['cancel_edit']) && isset($_GET['preview_id'])) {
    $edit_mode = false;
    header('Location: ?preview_id=' . $_GET['preview_id']);
    exit;
}

// Ambil data soal dari database
$soal_teori = [];
$search = '';

try {
    if (isset($_GET['search']) && !empty($_GET['search'])) {
        $search = $_GET['search'];
        $stmt = $pdo->prepare("SELECT * FROM bank_soal_teori 
                              WHERE nomor_registrasi LIKE ? OR pertanyaan LIKE ? OR tinjauan1 LIKE ?
                              ORDER BY created_at DESC");
        $searchTerm = "%$search%";
        $stmt->execute([$searchTerm, $searchTerm, $searchTerm]);
    } else {
        $stmt = $pdo->query("SELECT * FROM bank_soal_teori ORDER BY created_at DESC");
    }
    $soal_teori = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $error = 'Gagal mengambil data soal: ' . $e->getMessage();
}

// Ambil soal tertentu untuk preview
$preview_soal = null;
if (isset($_GET['preview_id']) && !empty($_GET['preview_id'])) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM bank_soal_teori WHERE id = ?");
        $stmt->execute([$_GET['preview_id']]);
        $preview_soal = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $error = 'Gagal mengambil data preview: ' . $e->getMessage();
    }
}

// Jika dalam mode edit, gunakan data yang sedang diedit
if ($edit_mode && $editing_soal) {
    $preview_soal = $editing_soal;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lihat Soal Teori - SOCA OSCE System</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/list_soal_teori.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>SOCA/OSCE System</h2>
                <p>Admin Panel</p>
            </div>
            <ul class="sidebar-menu">
                <li><a href="dashboard.php" class="<?php echo basename($_SERVER['PHP_SELF']) == 'dashboard.php' ? 'active' : ''; ?>">
                    <i class="fas fa-tachometer-alt"></i> Dashboard
                </a></li>
                <li><a href="bank_soal_teori.php" class="<?php echo basename($_SERVER['PHP_SELF']) == 'bank_soal_teori.php' ? 'active' : ''; ?>">
                    <i class="fas fa-plus-circle"></i> Tambah Soal Teori
                </a></li>
                <li><a href="list_soal_teori.php" class="<?php echo basename($_SERVER['PHP_SELF']) == 'list_soal_teori.php' ? 'active' : ''; ?>">
                    <i class="fas fa-eye"></i> Lihat Soal Teori
                </a></li>
                <li><a href="soal.php">
                    <i class="fas fa-question-circle"></i> Kelola Soal
                </a></li>
                <li><a href="ujian.php">
                    <i class="fas fa-clipboard-list"></i> Kelola Ujian
                </a></li>
                <li><a href="peserta.php">
                    <i class="fas fa-users"></i> Kelola Peserta
                </a></li>
                <li><a href="penguji.php">
                    <i class="fas fa-user-check"></i> Kelola Penguji
                </a></li>
                <li><a href="nilai.php">
                    <i class="fas fa-chart-bar"></i> Lihat Nilai
                </a></li>
                <li><a href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </a></li>
            </ul>
        </div>

        <div class="main-content">
            <div class="header">
                <h1>Lihat Soal Uji Teori <?php echo $edit_mode ? '- Edit Mode' : ''; ?></h1>
                <div class="user-info">
                    <span><i class="fas fa-user"></i> Halo, <?php echo $_SESSION['user_name'] ?? 'Admin'; ?></span>
                    <a href="../logout.php" class="btn btn-danger btn-sm">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>

            <div class="content">
                <!-- Search Box -->
                <div class="search-box">
                    <form method="GET" action="">
                        <div class="search-input-group">
                            <input type="text" name="search" placeholder="Cari berdasarkan nomor registrasi, pertanyaan, atau kompetensi..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i> Cari
                            </button>
                            <?php if (!empty($search)): ?>
                                <a href="list_soal_teori.php" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Clear
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>

                <div class="layout-container">
                    <!-- List Soal -->
                    <div class="soal-list-container">
                        <div class="section-header">
                            <h2><i class="fas fa-list"></i> Daftar Soal Teori</h2>
                            <span class="badge"><?php echo count($soal_teori); ?> soal</span>
                        </div>

                        <?php if (empty($soal_teori)): ?>
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <h3>Belum ada soal teori</h3>
                                <p>Silakan tambah soal teori terlebih dahulu</p>
                                <a href="bank_soal_teori.php" class="btn btn-primary">
                                    <i class="fas fa-plus"></i> Tambah Soal Teori
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="soal-items">
                                <?php foreach ($soal_teori as $soal): ?>
                                    <div class="soal-item <?php echo ($preview_soal && $preview_soal['id'] == $soal['id']) ? 'active' : ''; ?>"
                                         onclick="window.location.href='?preview_id=<?php echo $soal['id']; ?>'">
                                        <div class="soal-header">
                                            <h4><?php echo htmlspecialchars($soal['nomor_registrasi']); ?></h4>
                                            <span class="kunci-badge">Kunci: <?php echo htmlspecialchars($soal['kunci'] ?? '-'); ?></span>
                                        </div>
                                        <div class="soal-preview">
                                            <?php echo strip_tags(substr($soal['pertanyaan'], 0, 150)); ?>...
                                        </div>
                                        <div class="soal-meta">
                                            <span class="department"><?php echo htmlspecialchars($soal['department'] ?? '-'); ?></span>
                                            <span class="date"><?php echo date('d/m/Y', strtotime($soal['created_at'])); ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Preview/Edit Container -->
                    <div class="preview-container">
                        <?php if ($preview_soal): ?>
                            <div class="preview-content">
                                <div class="preview-header">
                                    <h2>
                                        <i class="fas fa-<?php echo $edit_mode ? 'edit' : 'eye'; ?>"></i> 
                                        <?php echo $edit_mode ? 'Edit Soal' : 'Preview Soal'; ?>
                                    </h2>
                                    <div class="preview-actions">
                                        <?php if ($edit_mode): ?>
                                            <button type="submit" form="editSoalForm" class="btn btn-success">
                                                <i class="fas fa-save"></i> Simpan
                                            </button>
                                            <a href="?cancel_edit=1&preview_id=<?php echo $preview_soal['id']; ?>" class="btn btn-secondary">
                                                <i class="fas fa-times"></i> Batal
                                            </a>
                                        <?php else: ?>
                                            <a href="?edit_id=<?php echo $preview_soal['id']; ?>" class="btn btn-edit">
                                                <i class="fas fa-edit"></i> Edit
                                            </a>
                                            <a href="hapus_soal_teori.php?id=<?php echo $preview_soal['id']; ?>" 
                                               class="btn btn-delete" 
                                               onclick="return confirm('Yakin hapus soal ini?')">
                                                <i class="fas fa-trash"></i> Hapus
                                            </a>
                                            <button onclick="printPreview()" class="btn btn-primary">
                                                <i class="fas fa-print"></i> Print
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <?php if ($edit_mode): ?>
                                    <!-- EDIT FORM -->
                                    <form method="POST" action="" id="editSoalForm" class="edit-form">
                                        <input type="hidden" name="soal_id" value="<?php echo $preview_soal['id']; ?>">
                                        <input type="hidden" name="update_soal" value="1">
                                        
                                        <div class="form-section">
                                            <h3 class="section-title">Informasi Dasar</h3>
                                            
                                            <div class="form-group">
                                                <label for="nomor_registrasi">Nomor Registrasi Soal *</label>
                                                <input type="text" id="nomor_registrasi" name="nomor_registrasi" 
                                                       value="<?php echo htmlspecialchars($preview_soal['nomor_registrasi']); ?>" required>
                                            </div>
                                            
                                            <div class="form-row">
                                                <div class="form-group">
                                                    <label for="tinjauan1">Kompetensi Utama *</label>
                                                    <input type="text" id="tinjauan1" name="tinjauan1" 
                                                           value="<?php echo htmlspecialchars($preview_soal['tinjauan1']); ?>" required>
                                                </div>
                                                
                                                <div class="form-group">
                                                    <label for="tinjauan2">Penyakit/Kelainan</label>
                                                    <input type="text" id="tinjauan2" name="tinjauan2" 
                                                           value="<?php echo htmlspecialchars($preview_soal['tinjauan2'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="tinjauan3">Bidang Ilmu & Keterampilan KG</label>
                                                <input type="text" id="tinjauan3" name="tinjauan3" 
                                                       value="<?php echo htmlspecialchars($preview_soal['tinjauan3'] ?? ''); ?>">
                                            </div>
                                        </div>

                                        <div class="form-section">
                                            <h3 class="section-title">Konten Soal</h3>
                                            
                                            <div class="form-group">
                                                <label for="vignette">Vignette</label>
                                                <div class="text-editor">
                                                    <div class="toolbar">
                                                        <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                                                        <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                                                        <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                                                        <button type="button" data-command="insertUnorderedList" title="Bullet List">• List</button>
                                                        <button type="button" data-command="insertOrderedList" title="Numbered List">1. List</button>
                                                    </div>
                                                    <textarea id="vignette" name="vignette" class="rich-text"><?php echo htmlspecialchars($preview_soal['vignette'] ?? ''); ?></textarea>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="pertanyaan">Pertanyaan/Instruksi *</label>
                                                <div class="text-editor">
                                                    <div class="toolbar">
                                                        <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                                                        <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                                                        <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                                                        <button type="button" data-command="insertUnorderedList" title="Bullet List">• List</button>
                                                        <button type="button" data-command="insertOrderedList" title="Numbered List">1. List</button>
                                                    </div>
                                                    <textarea id="pertanyaan" name="pertanyaan" class="rich-text" required><?php echo htmlspecialchars($preview_soal['pertanyaan']); ?></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-section">
                                            <h3 class="section-title">Pilihan Jawaban</h3>
                                            
                                            <div class="form-row">
                                                <div class="form-group">
                                                    <label for="pilihan_a">Pilihan A</label>
                                                    <input type="text" id="pilihan_a" name="pilihan_a" 
                                                           value="<?php echo htmlspecialchars($preview_soal['pilihan_a'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="form-group">
                                                    <label for="pilihan_b">Pilihan B</label>
                                                    <input type="text" id="pilihan_b" name="pilihan_b" 
                                                           value="<?php echo htmlspecialchars($preview_soal['pilihan_b'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="form-row">
                                                <div class="form-group">
                                                    <label for="pilihan_c">Pilihan C</label>
                                                    <input type="text" id="pilihan_c" name="pilihan_c" 
                                                           value="<?php echo htmlspecialchars($preview_soal['pilihan_c'] ?? ''); ?>">
                                                </div>
                                                
                                                <div class="form-group">
                                                    <label for="pilihan_d">Pilihan D</label>
                                                    <input type="text" id="pilihan_d" name="pilihan_d" 
                                                           value="<?php echo htmlspecialchars($preview_soal['pilihan_d'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="pilihan_e">Pilihan E</label>
                                                <input type="text" id="pilihan_e" name="pilihan_e" 
                                                       value="<?php echo htmlspecialchars($preview_soal['pilihan_e'] ?? ''); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="kunci">Kunci Jawaban</label>
                                                <select id="kunci" name="kunci">
                                                    <option value="">-- Pilih Kunci Jawaban --</option>
                                                    <option value="A" <?php echo ($preview_soal['kunci'] ?? '') == 'A' ? 'selected' : ''; ?>>A</option>
                                                    <option value="B" <?php echo ($preview_soal['kunci'] ?? '') == 'B' ? 'selected' : ''; ?>>B</option>
                                                    <option value="C" <?php echo ($preview_soal['kunci'] ?? '') == 'C' ? 'selected' : ''; ?>>C</option>
                                                    <option value="D" <?php echo ($preview_soal['kunci'] ?? '') == 'D' ? 'selected' : ''; ?>>D</option>
                                                    <option value="E" <?php echo ($preview_soal['kunci'] ?? '') == 'E' ? 'selected' : ''; ?>>E</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-section">
                                            <h3 class="section-title">Informasi Tambahan</h3>
                                            
                                            <div class="form-group">
                                                <label for="department">Department</label>
                                                <input type="text" id="department" name="department" 
                                                       value="<?php echo htmlspecialchars($preview_soal['department'] ?? ''); ?>">
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="alasan_singkat">Alasan Singkat</label>
                                                <div class="text-editor">
                                                    <div class="toolbar">
                                                        <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                                                        <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                                                        <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                                                    </div>
                                                    <textarea id="alasan_singkat" name="alasan_singkat" class="rich-text"><?php echo htmlspecialchars($preview_soal['alasan_singkat'] ?? ''); ?></textarea>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="referensi">Referensi</label>
                                                <div class="text-editor">
                                                    <div class="toolbar">
                                                        <button type="button" data-command="bold" title="Bold"><b>B</b></button>
                                                        <button type="button" data-command="italic" title="Italic"><i>I</i></button>
                                                        <button type="button" data-command="underline" title="Underline"><u>U</u></button>
                                                    </div>
                                                    <textarea id="referensi" name="referensi" class="rich-text"><?php echo htmlspecialchars($preview_soal['referensi'] ?? ''); ?></textarea>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="penulis">Penulis</label>
                                                <input type="text" id="penulis" name="penulis" 
                                                       value="<?php echo htmlspecialchars($preview_soal['penulis'] ?? ''); ?>">
                                            </div>
                                        </div>
                                    </form>
                                <?php else: ?>
                                    <!-- PREVIEW CONTENT -->
                                    <div class="soal-preview-content" id="printableArea">
                                        <!-- Konten preview sama seperti sebelumnya -->
                                        <div class="preview-section header-section">
                                            <div class="registrasi-info">
                                                <strong>No. Registrasi Soal:</strong> 
                                                <?php echo htmlspecialchars($preview_soal['nomor_registrasi']); ?>
                                            </div>
                                        </div>

                                        <?php if (!empty($preview_soal['vignette'])): ?>
                                            <div class="preview-section vignette-section">
                                                <h3>Vignette:</h3>
                                                <div class="vignette-content">
                                                    <?php echo nl2br(htmlspecialchars($preview_soal['vignette'])); ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <div class="preview-section pertanyaan-section">
                                            <h3>Pertanyaan / Instruksi:</h3>
                                            <div class="pertanyaan-content">
                                                <?php echo nl2br(htmlspecialchars($preview_soal['pertanyaan'])); ?>
                                            </div>
                                        </div>

                                        <!-- ... (sisa konten preview sama seperti sebelumnya) ... -->
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="preview-placeholder">
                                <i class="fas fa-file-alt"></i>
                                <h3>Pilih soal untuk melihat preview</h3>
                                <p>Klik pada salah satu soal di daftar sebelah kiri untuk melihat detail lengkap</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../assets/js/list_soal_teori.js"></script>
</body>
</html>