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

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

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

// Tambah station baru
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['tambah_station'])) {
    $nama_station = sanitize($_POST['nama_station']);
    $deskripsi = $_POST['deskripsi'];
    $instruksi_peserta = $_POST['instruksi_peserta'];
    $instruksi_penguji = $_POST['instruksi_penguji'];
    
    $stmt = $pdo->prepare("INSERT INTO stations (nama_station, deskripsi, instruksi_peserta, instruksi_penguji) VALUES (?, ?, ?, ?)");
    
    if ($stmt->execute([$nama_station, $deskripsi, $instruksi_peserta, $instruksi_penguji])) {
        $station_id = $pdo->lastInsertId();
        $success = "Station berhasil ditambahkan!";
        
        // Tambah aspek penilaian 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]);
                }
            }
        }
    } else {
        $error = "Gagal menambahkan station!";
    }
}

// Hapus station
if (isset($_GET['hapus_station'])) {
    $station_id = $_GET['hapus_station'];
    
    $stmt = $pdo->prepare("DELETE FROM stations WHERE id = ?");
    if ($stmt->execute([$station_id])) {
        $success = "Station berhasil dihapus!";
    } else {
        $error = "Gagal menghapus station!";
    }
}

// Ambil data stations
$stmt = $pdo->query("SELECT * FROM stations ORDER BY id DESC");
$stations = $stmt->fetchAll();
?>

<?php // Quick fix untuk variabel header
if (!isset($ujian)) $ujian = null;
if (!isset($ujian_id)) $ujian_id = null;

include 'header.php'; ?>

<div class="content">
    <h2>Kelola Soal & Stations</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; ?>
    
    <!-- Form Tambah Station -->
    <div class="card">
        <h3>Tambah Station Baru</h3>
        <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" required>
            </div>
            
            <div class="form-group">
                <label for="deskripsi">Deskripsi/Skenario:</label>
                <div id="deskripsiEditor" class="rich-text-editor" data-target="deskripsi"></div>
                <textarea id="deskripsi" name="deskripsi" style="display: none;"></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"></div>
                <textarea id="instruksi_peserta" name="instruksi_peserta" style="display: none;"></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"></div>
                <textarea id="instruksi_penguji" name="instruksi_penguji" style="display: none;"></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">1</span>/<span id="maxAspekDisplay">20</span> Aspek
                    </div>
                </div>
                <div id="aspekContainer">
                    <!-- Aspek akan ditambahkan secara dinamis di sini -->
                </div>
                <button type="button" id="tambahAspek" class="btn btn-secondary">
                    <i class="fas fa-plus"></i> Tambah Aspek
                </button>
            </div>
            
            <button type="submit" name="tambah_station" class="btn btn-primary">Simpan Station</button>
        </form>
    </div>
    
    <!-- Daftar Stations -->
    <div class="card">
        <h3>Daftar Stations</h3>
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Nama Station</th>
                        <th>Jumlah Aspek</th>
                        <th>Tanggal Dibuat</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($stations)): ?>
                        <tr>
                            <td colspan="5" style="text-align: center;">Belum ada station</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($stations as $index => $station): 
                            // Hitung jumlah aspek
                            $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM aspek_penilaian WHERE station_id = ?");
                            $stmt->execute([$station['id']]);
                            $jumlah_aspek = $stmt->fetch()['total'];
                        ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td>
                                    <strong><?php echo $station['nama_station']; ?></strong>
                                    <div class="station-preview">
                                        <?php echo substr(strip_tags($station['deskripsi']), 0, 100) . '...'; ?>
                                    </div>
                                </td>
                                <td><?php echo $jumlah_aspek; ?> aspek</td>
                                <td><?php echo formatTanggal($station['created_at']); ?></td>
                                <td>
                                    <a href="edit_station.php?id=<?php echo $station['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
                                    <a href="?hapus_station=<?php echo $station['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menghapus station ini?')">Hapus</a>
                                    <a href="detail_station.php?id=<?php echo $station['id']; ?>" class="btn btn-secondary btn-sm">Detail</a>
                                </td>
                                <td>
    <a href="edit_station.php?id=<?php echo $station['id']; ?>" class="btn btn-primary btn-sm">Edit</a>
    <a href="?hapus_station=<?php echo $station['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Yakin ingin menghapus station ini?')">Hapus</a>
    <a href="detail_station.php?id=<?php echo $station['id']; ?>" class="btn btn-info btn-sm">Preview</a>
</td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </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" 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>
                <small class="form-hint">Contoh: Menjawab salah/tidak menjawab/tidak melakukan</small>
            </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>
                <small class="form-hint">Contoh: Kurang lengkap/ada kesalahan/sebagian dilakukan</small>
            </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>
                <small class="form-hint">Contoh: Menjawab dengan lengkap dan benar/melakukan dengan sempurna</small>
            </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>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="../assets/js/soal.js"></script>
<script>
// Debug function untuk memeriksa state aspek
function debugAspek() {
    const aspekItems = document.querySelectorAll('.aspek-item');
    console.log('Total aspek:', aspekItems.length);
    
    aspekItems.forEach((item, index) => {
        const namaTextarea = item.querySelector('textarea[name="aspek_nama[]"]');
        const editorContent = item.querySelector('.nama-aspek-editor .editor-content');
        
        console.log(`Aspek ${index + 1}:`, {
            textareaValue: namaTextarea ? namaTextarea.value : 'null',
            editorContent: editorContent ? editorContent.innerHTML : 'null',
            hasText: namaTextarea && namaTextarea.value.trim() !== ''
        });
    });
}

// Panggil debug saat form disubmit
document.getElementById('stationForm')?.addEventListener('submit', function(e) {
    console.log('=== DEBUG BEFORE SUBMIT ===');
    debugAspek();
});
</script>
<script>
// Debug helper
console.log('Script loaded');
console.log('tambahAspek button:', document.getElementById('tambahAspek'));
console.log('aspekContainer:', document.getElementById('aspekContainer'));
console.log('aspekTemplate:', document.getElementById('aspekTemplate'));

// Manual test function
function testTambahAspek() {
    const manager = new AspekManager();
    manager.tambahAspek();
}
/* Style untuk mini editor */
.mini-editor {
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
}

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

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

.mini-toolbar .toolbar-btn:hover {
    background: #e9e9e9;
}

.mini-editor-content {
    min-height: 80px;
    padding: 8px;
    max-height: 150px;
    overflow-y: auto;
}

/* Style untuk aspek item */
.aspek-item {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    background: #f9f9f9;
}

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

.aspek-header h5 {
    margin: 0;
    color: #333;
}

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

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

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

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
}
</script>



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