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

if (!isAdmin()) {
    redirect('../login.php');
}

$station_id = $_GET['id'] ?? null;

if (!$station_id) {
    redirect('soal.php');
}

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

if (!$station) {
    redirect('soal.php');
}

// Ambil aspek penilaian
$stmt = $pdo->prepare("SELECT * FROM aspek_penilaian WHERE station_id = ? ORDER BY nomor_urut");
$stmt->execute([$station_id]);
$aspeks = $stmt->fetchAll();

$success = '';
$error = '';

// Update station
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_station'])) {
    $nama_station = sanitize($_POST['nama_station']);
    $deskripsi = $_POST['deskripsi'];
    $instruksi_peserta = $_POST['instruksi_peserta'];
    $instruksi_penguji = $_POST['instruksi_penguji'];
    
    $stmt = $pdo->prepare("UPDATE stations SET nama_station = ?, deskripsi = ?, instruksi_peserta = ?, instruksi_penguji = ? WHERE id = ?");
    
    if ($stmt->execute([$nama_station, $deskripsi, $instruksi_peserta, $instruksi_penguji, $station_id])) {
        $success = "Station berhasil diupdate!";
        
        // Hapus aspek lama
        $stmt = $pdo->prepare("DELETE FROM aspek_penilaian WHERE station_id = ?");
        $stmt->execute([$station_id]);
        
        // Tambah aspek penilaian baru jika ada
        if (isset($_POST['aspek_nama']) && is_array($_POST['aspek_nama'])) {
            foreach ($_POST['aspek_nama'] as $index => $aspek_nama) {
                if (!empty($aspek_nama)) {
                    $nomor_urut = intval($_POST['nomor_urut'][$index]);
                    $skor_0 = isset($_POST['skor_0'][$index]) ? 1 : 0;
                    $skor_1 = isset($_POST['skor_1'][$index]) ? 1 : 0;
                    $skor_2 = isset($_POST['skor_2'][$index]) ? 1 : 0;
                    $deskripsi_0 = $_POST['deskripsi_0'][$index] ?? '';
                    $deskripsi_1 = $_POST['deskripsi_1'][$index] ?? '';
                    $deskripsi_2 = $_POST['deskripsi_2'][$index] ?? '';
                    
                    $stmt = $pdo->prepare("INSERT INTO aspek_penilaian (station_id, nomor_urut, nama_aspek, skor_0, skor_1, skor_2, deskripsi_0, deskripsi_1, deskripsi_2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$station_id, $nomor_urut, $aspek_nama, $skor_0, $skor_1, $skor_2, $deskripsi_0, $deskripsi_1, $deskripsi_2]);
                }
            }
        }
        
        // Redirect to prevent resubmission
        redirect("edit_station.php?id=$station_id&success=1");
    } else {
        $error = "Gagal mengupdate station!";
    }
}

if (isset($_GET['success'])) {
    $success = "Station berhasil diupdate!";
}
?>

<?php include 'header.php'; ?>

<div class="content">
    <h2>Edit Station: <?php echo $station['nama_station']; ?></h2>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="card">
        <form method="POST" id="stationForm">
            <div class="form-group">
                <label for="nama_station">Nama Station:</label>
                <input type="text" id="nama_station" name="nama_station" value="<?php echo $station['nama_station']; ?>" required>
            </div>
            
            <div class="form-group">
                <label for="deskripsi">Deskripsi/Skenario:</label>
                <div id="deskripsiEditor" class="rich-text-editor" data-target="deskripsi"><?php echo $station['deskripsi']; ?></div>
                <textarea id="deskripsi" name="deskripsi" style="display: none;"><?php echo $station['deskripsi']; ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="instruksi_peserta">Instruksi untuk Peserta:</label>
                <div id="instruksiPesertaEditor" class="rich-text-editor" data-target="instruksi_peserta"><?php echo $station['instruksi_peserta']; ?></div>
                <textarea id="instruksi_peserta" name="instruksi_peserta" style="display: none;"><?php echo $station['instruksi_peserta']; ?></textarea>
            </div>
            
            <div class="form-group">
                <label for="instruksi_penguji">Instruksi untuk Penguji:</label>
                <div id="instruksiPengujiEditor" class="rich-text-editor" data-target="instruksi_penguji"><?php echo $station['instruksi_penguji']; ?></div>
                <textarea id="instruksi_penguji" name="instruksi_penguji" style="display: none;"><?php echo $station['instruksi_penguji']; ?></textarea>
            </div>
            
            <!-- Aspek Penilaian -->
            <div class="aspek-penilaian-section">
                <div class="section-header">
                    <h4>Aspek yang Dinilai</h4>
                    <div class="aspek-counter">
                        <span id="aspekCountDisplay"><?php echo count($aspeks); ?></span>/<span id="maxAspekDisplay">20</span> Aspek
                    </div>
                </div>
                <div id="aspekContainer">
                    <?php foreach ($aspeks as $index => $aspek): ?>
                        <div class="aspek-item">
                            <div class="aspek-header">
                                <h5>Aspek Penilaian <span class="aspek-number"><?php echo $index + 1; ?></span></h5>
                                <button type="button" class="btn btn-danger btn-sm hapus-aspek" title="Hapus aspek ini">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            </div>
                            
                            <div class="form-group">
                                <label>Nomor Urut:</label>
                                <input type="number" name="nomor_urut[]" class="nomor-urut" min="1" value="<?php echo $aspek['nomor_urut']; ?>" required>
                                <small class="form-hint">Urutan penampilan aspek penilaian</small>
                            </div>

                            <div class="form-group">
                                <label>Nama Aspek:</label>
                                <div class="mini-editor nama-aspek-editor with-image" data-target="aspek_nama[]"><?php echo $aspek['nama_aspek']; ?></div>
                                <textarea name="aspek_nama[]" style="display: none;"><?php echo $aspek['nama_aspek']; ?></textarea>
                            </div>
                            
                            <div class="skor-options">
                                <label>Pilih Skor yang Tersedia:</label>
                                <div class="checkbox-group">
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_0[]" value="1" <?php echo $aspek['skor_0'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-0-badge">Skor 0</span>
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_1[]" value="1" <?php echo $aspek['skor_1'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-1-badge">Skor 1</span>
                                    </label>
                                    <label class="checkbox-label">
                                        <input type="checkbox" name="skor_2[]" value="1" <?php echo $aspek['skor_2'] ? 'checked' : ''; ?>> 
                                        <span class="skor-badge skor-2-badge">Skor 2</span>
                                    </label>
                                </div>
                                <small class="form-hint">Pilih skor yang akan digunakan untuk aspek ini</small>
                            </div>
                            
                            <div class="skor-description">
                                <div class="skor-item skor-0" style="<?php echo !$aspek['skor_0'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-0-badge">Deskripsi Skor 0</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_0[]"><?php echo $aspek['deskripsi_0']; ?></div>
                                    <textarea name="deskripsi_0[]" style="display: none;"><?php echo $aspek['deskripsi_0']; ?></textarea>
                                </div>
                                
                                <div class="skor-item skor-1" style="<?php echo !$aspek['skor_1'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-1-badge">Deskripsi Skor 1</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_1[]"><?php echo $aspek['deskripsi_1']; ?></div>
                                    <textarea name="deskripsi_1[]" style="display: none;"><?php echo $aspek['deskripsi_1']; ?></textarea>
                                </div>
                                
                                <div class="skor-item skor-2" style="<?php echo !$aspek['skor_2'] ? 'display: none;' : ''; ?>">
                                    <label>
                                        <span class="skor-badge skor-2-badge">Deskripsi Skor 2</span>
                                    </label>
                                    <div class="mini-editor" data-target="deskripsi_2[]"><?php echo $aspek['deskripsi_2']; ?></div>
                                    <textarea name="deskripsi_2[]" style="display: none;"><?php echo $aspek['deskripsi_2']; ?></textarea>
                                </div>
                            </div>
                            
                            <div class="aspek-actions">
                                <button type="button" class="btn btn-secondary btn-sm duplicate-aspek" title="Duplikat aspek ini">
                                    <i class="fas fa-copy"></i> Duplikat
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" id="tambahAspek" class="btn btn-secondary">
                    <i class="fas fa-plus"></i> Tambah Aspek
                </button>
            </div>
            
            <button type="submit" name="update_station" class="btn btn-primary">Update Station</button>
            <a href="soal.php" class="btn btn-secondary">Kembali</a>
        </form>
    </div>
</div>

<!-- Template untuk Aspek Penilaian -->
<script type="text/template" id="aspekTemplate">
    <div class="aspek-item">
        <div class="aspek-header">
            <h5>Aspek Penilaian <span class="aspek-number">1</span></h5>
            <button type="button" class="btn btn-danger btn-sm hapus-aspek" title="Hapus aspek ini">
                <i class="fas fa-trash"></i> Hapus
            </button>
        </div>
        
        <div class="form-group">
            <label>Nomor Urut:</label>
            <input type="number" name="nomor_urut[]" class="nomor-urut" min="1" value="1" required>
            <small class="form-hint">Urutan penampilan aspek penilaian</small>
        </div>

        <div class="form-group">
            <label>Nama Aspek:</label>
            <div class="mini-editor nama-aspek-editor with-image" data-target="aspek_nama[]"></div>
            <textarea name="aspek_nama[]" style="display: none;"></textarea>
        </div>
        
        <div class="skor-options">
            <label>Pilih Skor yang Tersedia:</label>
            <div class="checkbox-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_0[]" value="1" checked> 
                    <span class="skor-badge skor-0-badge">Skor 0</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_1[]" value="1" checked> 
                    <span class="skor-badge skor-1-badge">Skor 1</span>
                </label>
                <label class="checkbox-label">
                    <input type="checkbox" name="skor_2[]" value="1" checked> 
                    <span class="skor-badge skor-2-badge">Skor 2</span>
                </label>
            </div>
            <small class="form-hint">Pilih skor yang akan digunakan untuk aspek ini</small>
        </div>
        
        <div class="skor-description">
            <div class="skor-item skor-0">
                <label>
                    <span class="skor-badge skor-0-badge">Deskripsi Skor 0</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_0[]"></div>
                <textarea name="deskripsi_0[]" style="display: none;"></textarea>
            </div>
            
            <div class="skor-item skor-1">
                <label>
                    <span class="skor-badge skor-1-badge">Deskripsi Skor 1</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_1[]"></div>
                <textarea name="deskripsi_1[]" style="display: none;"></textarea>
            </div>
            
            <div class="skor-item skor-2">
                <label>
                    <span class="skor-badge skor-2-badge">Deskripsi Skor 2</span>
                </label>
                <div class="mini-editor" data-target="deskripsi_2[]"></div>
                <textarea name="deskripsi_2[]" style="display: none;"></textarea>
            </div>
        </div>
        
        <div class="aspek-actions">
            <button type="button" class="btn btn-secondary btn-sm duplicate-aspek" title="Duplikat aspek ini">
                <i class="fas fa-copy"></i> Duplikat
            </button>
        </div>
    </div>
</script>

<style>
/* Style untuk aspek item */
.aspek-item {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    background: #f9f9f9;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.aspek-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #e9ecef;
}

.aspek-header h5 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.2rem;
}

.aspek-number {
    background: #3498db;
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #495057;
}

.form-hint {
    display: block;
    margin-top: 5px;
    font-size: 0.85rem;
    color: #6c757d;
}

.checkbox-group {
    display: flex;
    gap: 15px;
    margin: 10px 0;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.skor-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 4px;
    color: white;
    font-weight: bold;
    font-size: 0.85rem;
}

.skor-0-badge { background: #dc3545; }
.skor-1-badge { background: #ffc107; color: #000; }
.skor-2-badge { background: #28a745; }

.skor-item {
    margin-bottom: 15px;
    padding: 15px;
    background: white;
    border-radius: 6px;
    border-left: 4px solid #ddd;
}

.skor-0 { border-left-color: #dc3545; }
.skor-1 { border-left-color: #ffc107; }
.skor-2 { border-left-color: #28a745; }

.aspek-actions {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #e9ecef;
    text-align: right;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.aspek-counter {
    background: #6c757d;
    color: white;
    padding: 5px 10px;
    border-radius: 15px;
    font-size: 0.9rem;
    font-weight: 600;
}

/* Style untuk mini editor */
.mini-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
    background: white;
}

.mini-toolbar {
    background: #f5f5f5;
    padding: 5px;
    border-bottom: 1px solid #ddd;
    display: flex;
    gap: 2px;
    flex-wrap: wrap;
}

.mini-toolbar .toolbar-btn {
    padding: 4px 8px;
    border: none;
    background: white;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
}

.mini-toolbar .toolbar-btn:hover {
    background: #e9e9e9;
    transform: translateY(-1px);
}

.mini-editor-content {
    min-height: 80px;
    padding: 12px;
    max-height: 200px;
    overflow-y: auto;
    line-height: 1.5;
}

.mini-editor-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 5px 0;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Style untuk rich text editor */
.rich-text-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    background: white;
    position: relative;
}

.editor-toolbar {
    background: #f5f5f5;
    padding: 8px;
    border-bottom: 1px solid #ddd;
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    align-items: center;
}

.editor-toolbar .toolbar-btn {
    padding: 6px 10px;
    border: none;
    background: white;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.2s;
    border: 1px solid #ddd;
}

.editor-toolbar .toolbar-btn:hover {
    background: #e9e9e9;
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.editor-content {
    min-height: 200px;
    padding: 15px;
    max-height: 400px;
    overflow-y: auto;
    line-height: 1.6;
    font-family: Arial, sans-serif;
}

.editor-content img {
    max-width: 100%;
    height: auto;
    border-radius: 6px;
    margin: 10px 0;
    box-shadow: 0 3px 6px rgba(0,0,0,0.1);
    border: 1px solid #e9ecef;
}
</style>

<script src="../assets/js/soal.js"></script>
<script>
// Inisialisasi untuk edit station
document.addEventListener('DOMContentLoaded', function() {
    console.log('Edit Station initialized');
    
    // Initialize main editors
    try {
        const deskripsiEditor = document.getElementById('deskripsiEditor');
        const instruksiPesertaEditor = document.getElementById('instruksiPesertaEditor');
        const instruksiPengujiEditor = document.getElementById('instruksiPengujiEditor');
        
        if (deskripsiEditor) new RichTextEditor(deskripsiEditor);
        if (instruksiPesertaEditor) new RichTextEditor(instruksiPesertaEditor);
        if (instruksiPengujiEditor) new RichTextEditor(instruksiPengujiEditor);
        
        console.log('Main rich text editors initialized');
    } catch (error) {
        console.error('Error initializing main rich text editors:', error);
    }
    
    // Initialize aspek manager
    try {
        const aspekManager = new AspekManager();
        console.log('AspekManager created successfully for edit station');
        
        // Setup skor checkboxes untuk aspek yang sudah ada
        setTimeout(() => {
            const existingAspekItems = document.querySelectorAll('.aspek-item');
            existingAspekItems.forEach(item => {
                aspekManager.setupSkorCheckboxes(item);
            });
        }, 500);
        
    } catch (error) {
        console.error('Error initializing AspekManager:', error);
    }
});
</script>

<?php include 'footer.php'; ?>