<?php
/**
 * Database Setup Script
 * TutorKita System
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/db.php';

// Handle AJAX requests for setup steps
if (isset($_GET['action']) && $_GET['action'] == 'setup_step') {
    header('Content-Type: application/json');
    
    $step = isset($_GET['step']) ? (int)$_GET['step'] : 0;
    
    try {
        $message = '';
        
        switch ($step) {
            case 0:
                $pdo->exec("CREATE TABLE IF NOT EXISTS admin (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    profile_name VARCHAR(100) DEFAULT 'Admin',
                    profile_emoji VARCHAR(10) DEFAULT '👨‍💻',
                    profile_image VARCHAR(255) DEFAULT NULL,
                    login_background VARCHAR(255) DEFAULT NULL,
                    portal_name VARCHAR(100) DEFAULT 'TutorKita',
                    portal_tagline VARCHAR(200) DEFAULT 'Platform Pembelajaran Terbaik',
                    portal_logo VARCHAR(500) DEFAULT NULL,
                    portal_favicon VARCHAR(500) DEFAULT NULL,
                    theme_color VARCHAR(20) DEFAULT '#667eea',
                    font_type VARCHAR(50) DEFAULT 'Segoe UI',
                    font_size VARCHAR(10) DEFAULT '14px',
                    footer_text VARCHAR(255) DEFAULT 'Hak Cipta Terpelihara 2026',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual admin berjaya dicipta';
                break;
                
            case 1:
                $pdo->exec("CREATE TABLE IF NOT EXISTS teachers (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    full_name VARCHAR(100) NOT NULL,
                    email VARCHAR(100) DEFAULT NULL,
                    phone VARCHAR(20) NOT NULL,
                    education_level ENUM('Sekolah Rendah', 'Sekolah Menengah') NOT NULL,
                    grade_level VARCHAR(50) NOT NULL,
                    profile_emoji VARCHAR(10) DEFAULT '👨‍🏫',
                    profile_image VARCHAR(255) DEFAULT NULL,
                    subjects TEXT NOT NULL,
                    status ENUM('Active', 'Inactive') DEFAULT 'Active',
                    created_by INT DEFAULT 1,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_username (username),
                    INDEX idx_status (status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual guru berjaya dicipta';
                break;
                
            case 2:
                $pdo->exec("CREATE TABLE IF NOT EXISTS students (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    password VARCHAR(255) NOT NULL,
                    full_name VARCHAR(100) NOT NULL,
                    age INT NOT NULL,
                    parent_guardian_name VARCHAR(100) NOT NULL,
                    phone VARCHAR(20) NOT NULL,
                    education_level ENUM('Sekolah Rendah', 'Sekolah Menengah') NOT NULL,
                    grade_level VARCHAR(50) NOT NULL,
                    profile_emoji VARCHAR(10) DEFAULT '👨‍🎓',
                    profile_image VARCHAR(255) DEFAULT NULL,
                    required_subjects TEXT NOT NULL,
                    enrolled_subjects TEXT DEFAULT NULL,
                    enrolled_by INT DEFAULT NULL,
                    status ENUM('Active', 'Inactive') DEFAULT 'Active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_username (username),
                    INDEX idx_status (status),
                    INDEX idx_education (education_level)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual pelajar berjaya dicipta';
                break;
                
            case 3:
                $pdo->exec("CREATE TABLE IF NOT EXISTS subjects (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    subject_name VARCHAR(100) NOT NULL,
                    subject_code VARCHAR(20) DEFAULT NULL,
                    category ENUM('Wajib', 'Elektif') DEFAULT 'Wajib',
                    education_level ENUM('Sekolah Rendah', 'Sekolah Menengah') DEFAULT NULL,
                    is_active ENUM('Yes', 'No') DEFAULT 'Yes',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_name (subject_name),
                    INDEX idx_category (category)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual subjek berjaya dicipta';
                break;
                
            case 4:
                $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    setting_key VARCHAR(100) NOT NULL UNIQUE,
                    setting_value TEXT DEFAULT NULL,
                    setting_type ENUM('text', 'number', 'color', 'image', 'json') DEFAULT 'text',
                    description VARCHAR(255) DEFAULT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual tetapan berjaya dicipta';
                break;
                
            case 5:
                $pdo->exec("CREATE TABLE IF NOT EXISTS notifications (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    user_type ENUM('admin', 'teacher', 'student') NOT NULL,
                    title VARCHAR(200) NOT NULL,
                    message TEXT NOT NULL,
                    type ENUM('info', 'success', 'warning', 'error') DEFAULT 'info',
                    is_read ENUM('Yes', 'No') DEFAULT 'No',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_user (user_id, user_type),
                    INDEX idx_read (is_read)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual notifikasi berjaya dicipta';
                break;
                
            case 6:
                $adminPassword = password_hash('admin', PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT IGNORE INTO admin (username, password, profile_name, profile_emoji) VALUES ('admin', ?, 'GuruICT', '👨‍💻')");
                $stmt->execute([$adminPassword]);
                $message = 'Pengguna admin lalai berjaya dicipta (username: admin, password: admin)';
                break;
                
            case 7:
                $subjects = [
                    ['Bahasa Melayu', 'BM', 'Wajib', NULL],
                    ['English', 'ENG', 'Wajib', NULL],
                    ['Mathematics', 'MATH', 'Wajib', NULL],
                    ['Science', 'SCI', 'Wajib', NULL],
                    ['Sejarah', 'SEJ', 'Wajib', 'Sekolah Menengah'],
                    ['Geografi', 'GEO', 'Wajib', 'Sekolah Menengah'],
                    ['Physics', 'PHY', 'Elektif', 'Sekolah Menengah'],
                    ['Chemistry', 'CHEM', 'Elektif', 'Sekolah Menengah'],
                    ['Biology', 'BIO', 'Elektif', 'Sekolah Menengah'],
                    ['Additional Mathematics', 'AMATH', 'Elektif', 'Sekolah Menengah'],
                    ['Pendidikan Islam', 'PI', 'Wajib', NULL],
                    ['Pendidikan Moral', 'PM', 'Wajib', 'Sekolah Rendah']
                ];
                
                $stmt = $pdo->prepare("INSERT IGNORE INTO subjects (subject_name, subject_code, category, education_level) VALUES (?, ?, ?, ?)");
                
                foreach ($subjects as $subject) {
                    $stmt->execute($subject);
                }
                $message = 'Subjek lalai berjaya dimuatkan';
                break;
                
            case 8:
                $pdo->exec("CREATE TABLE IF NOT EXISTS modules (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    title VARCHAR(200) NOT NULL,
                    description TEXT,
                    content TEXT,
                    links JSON DEFAULT NULL,
                    subject VARCHAR(100) NOT NULL,
                    teacher_id INT NOT NULL,
                    for_all_students ENUM('Yes', 'No') DEFAULT 'No',
                    status ENUM('Active', 'Inactive') DEFAULT 'Active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_teacher (teacher_id),
                    INDEX idx_subject (subject)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual modul berjaya dicipta';
                break;
                
            case 9:
                $pdo->exec("CREATE TABLE IF NOT EXISTS module_students (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    module_id INT NOT NULL,
                    student_id INT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE KEY unique_enrollment (module_id, student_id),
                    INDEX idx_module (module_id),
                    INDEX idx_student (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual enrollment modul berjaya dicipta';
                break;
                
            case 10:
                $pdo->exec("CREATE TABLE IF NOT EXISTS schedule (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    title VARCHAR(200) NOT NULL,
                    description TEXT,
                    subject VARCHAR(100) NOT NULL,
                    day_of_week VARCHAR(20) DEFAULT NULL,
                    schedule_date DATE DEFAULT NULL,
                    start_time TIME NOT NULL,
                    duration_minutes INT DEFAULT 60,
                    teacher_id INT NOT NULL,
                    is_recurring ENUM('Yes', 'No') DEFAULT 'No',
                    status ENUM('Active', 'Inactive') DEFAULT 'Active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_teacher (teacher_id),
                    INDEX idx_date (schedule_date),
                    INDEX idx_subject (subject)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual jadual masa berjaya dicipta';
                break;
                
            case 11:
                $pdo->exec("CREATE TABLE IF NOT EXISTS schedule_students (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    schedule_id INT NOT NULL,
                    student_id INT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE KEY unique_enrollment (schedule_id, student_id),
                    INDEX idx_schedule (schedule_id),
                    INDEX idx_student (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual enrollment jadual berjaya dicipta';
                break;
                
            case 12:
                $pdo->exec("CREATE TABLE IF NOT EXISTS online_classes (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    title VARCHAR(200) NOT NULL,
                    description TEXT,
                    join_link VARCHAR(500) DEFAULT NULL,
                    subject VARCHAR(100) NOT NULL,
                    teacher_id INT NOT NULL,
                    schedule_id INT DEFAULT NULL,
                    class_date DATE NOT NULL,
                    start_time TIME NOT NULL,
                    end_time TIME DEFAULT NULL,
                    status ENUM('Scheduled', 'Live', 'Completed', 'Cancelled') DEFAULT 'Scheduled',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_teacher (teacher_id),
                    INDEX idx_date (class_date),
                    INDEX idx_subject (subject)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual kelas online berjaya dicipta';
                break;
                
            case 13:
                $pdo->exec("CREATE TABLE IF NOT EXISTS class_students (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    class_id INT NOT NULL,
                    student_id INT NOT NULL,
                    teacher_notes TEXT DEFAULT NULL,
                    student_comment TEXT DEFAULT NULL,
                    joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE KEY unique_enrollment (class_id, student_id),
                    INDEX idx_class (class_id),
                    INDEX idx_student (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual enrollment kelas online berjaya dicipta';
                break;
                
            case 14:
                $pdo->exec("CREATE TABLE IF NOT EXISTS forums (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    title VARCHAR(200) NOT NULL,
                    content TEXT NOT NULL,
                    subject VARCHAR(100) NOT NULL,
                    teacher_id INT NOT NULL,
                    is_pinned ENUM('Yes', 'No') DEFAULT 'No',
                    status ENUM('Active', 'Inactive') DEFAULT 'Active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_teacher (teacher_id),
                    INDEX idx_subject (subject)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual forum berjaya dicipta';
                break;
                
            case 15:
                $pdo->exec("CREATE TABLE IF NOT EXISTS forum_replies (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    forum_id INT NOT NULL,
                    user_id INT NOT NULL,
                    user_type ENUM('teacher', 'student') NOT NULL,
                    content TEXT NOT NULL,
                    is_answer ENUM('Yes', 'No') DEFAULT 'No',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_forum (forum_id),
                    INDEX idx_user (user_id, user_type)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual reply forum berjaya dicipta';
                break;
                
            case 16:
                $pdo->exec("CREATE TABLE IF NOT EXISTS forum_enrollments (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    forum_id INT NOT NULL,
                    student_id INT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE KEY unique_enrollment (forum_id, student_id),
                    INDEX idx_forum (forum_id),
                    INDEX idx_student (student_id)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual enrollment forum berjaya dicipta';
                break;

            case 17:
                $pdo->exec("CREATE TABLE IF NOT EXISTS announcements (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    teacher_id INT NOT NULL,
                    title VARCHAR(200) NOT NULL,
                    content TEXT NOT NULL,
                    category VARCHAR(50) DEFAULT 'Umum',
                    priority ENUM('Normal', 'Penting', 'Urgent') DEFAULT 'Normal',
                    attachment_link VARCHAR(500) DEFAULT NULL,
                    expiry_date DATE DEFAULT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_teacher (teacher_id),
                    INDEX idx_category (category),
                    INDEX idx_priority (priority)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                $message = 'Jadual pengumuman guru berjaya dicipta';
                break;

            case 18:
                $pdo->exec("CREATE TABLE IF NOT EXISTS maintenance_logs (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    activity VARCHAR(200) NOT NULL,
                    status ENUM('Aktif', 'Maintenance', 'Selesai') DEFAULT 'Aktif',
                    details TEXT DEFAULT NULL,
                    created_by INT DEFAULT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    INDEX idx_status (status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
                
                $oprInfo = json_encode([
                    'title' => 'One Page Report (OPR)',
                    'description' => 'One Page Report merupakan dokumentasi ringkas yang menerangkan penggunaan One Page Report sebagai medium pelaporan utama dalam pengurusan.',
                    'link' => 'https://www.canva.com/design/DAG6y7UmBKU/view'
                ]);
                $stmt = $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value, setting_type, description) VALUES ('opr_info', ?, 'json', 'One Page Report info and link')");
                $stmt->execute([$oprInfo]);
                
                $message = 'Jadual log penyelenggaraan dan tetapan OPR berjaya dicipta';
                break;
                
            default:
                throw new Exception('Langkah tidak dikenalpasti');
        }
        
        echo json_encode(['success' => true, 'message' => $message]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setup TutorKita - Pemasangan Pangkalan Data</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 700px;
            width: 100%;
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 { font-size: 2rem; margin-bottom: 10px; }
        .header p { opacity: 0.9; }
        .content { padding: 30px; }
        .step {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
        }
        .step:hover { transform: translateX(5px); }
        .step.success { border-left-color: #28a745; background: #d4edda; }
        .step.error { border-left-color: #dc3545; background: #f8d7da; }
        .step.pending { border-left-color: #ffc107; background: #fff3cd; }
        .step-title { font-weight: bold; margin-bottom: 5px; display: flex; align-items: center; gap: 10px; }
        .step-icon { font-size: 1.5rem; }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 40px;
            border-radius: 30px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: block;
            width: 100%;
            margin-top: 20px;
        }
        .btn:hover { transform: scale(1.02); box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4); }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }
        .progress {
            height: 8px;
            background: #e9ecef;
            border-radius: 10px;
            margin: 20px 0;
            overflow: hidden;
        }
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 10px;
            transition: width 0.5s ease;
            width: 0%;
        }
        .log { background: #1e1e1e; color: #00ff00; padding: 20px; border-radius: 10px; font-family: monospace; max-height: 300px; overflow-y: auto; margin-top: 20px; }
        .log-entry { margin: 5px 0; }
        .log-success { color: #00ff00; }
        .log-error { color: #ff6b6b; }
        .log-info { color: #74b9ff; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 TutorKita Setup</h1>
            <p>Pemasangan Sistem Pangkalan Data</p>
        </div>
        <div class="content">
            <div class="progress">
                <div class="progress-bar" id="progressBar"></div>
            <div id="stepsContainer"></div>
            <button class="btn" id="runBtn" onclick="runSetup()">▶ Mula Pemasangan</button>
            <button class="btn" id="resetBtn" onclick="resetSetup()" style="display:none;">🔄 Jalankan Semula</button>
        </div>

    <script>
        var step = 0;
        var steps = [
            { id: 'admin', title: 'Membuat jadual admin...', icon: '👨‍💻' },
            { id: 'teachers', title: 'Membuat jadual guru...', icon: '👨‍🏫' },
            { id: 'students', title: 'Membuat jadual pelajar...', icon: '👨‍🎓' },
            { id: 'subjects', title: 'Membuat jadual subjek...', icon: '📚' },
            { id: 'settings', title: 'Membuat jadual tetapan...', icon: '⚙️' },
            { id: 'notifications', title: 'Membuat jadual notifikasi...', icon: '🔔' },
            { id: 'admin_user', title: 'Mencipta pengguna admin...', icon: '🔑' },
            { id: 'insert_subjects', title: 'Memasukkan subjek default...', icon: '📖' },
            { id: 'modules', title: 'Membuat jadual modul...', icon: '📚' },
            { id: 'module_students', title: 'Membuat jadual enrollment modul...', icon: '👥' },
            { id: 'schedule', title: 'Membuat jadual jadual masa...', icon: '📅' },
            { id: 'schedule_students', title: 'Membuat jadual enrollment jadual...', icon: '👥' },
            { id: 'online_classes', title: 'Membuat jadual kelas online...', icon: '💻' },
            { id: 'class_students', title: 'Membuat jadual enrollment kelas...', icon: '👥' },
            { id: 'forums', title: 'Membuat jadual forum...', icon: '💬' },
            { id: 'forum_replies', title: 'Membuat jadual reply forum...', icon: '💭' },
            { id: 'forum_enrollments', title: 'Membuat jadual enrollment forum...', icon: '👥' },
            { id: 'announcements', title: 'Membuat jadual pengumuman...', icon: '📢' },
            { id: 'maintenance', title: 'Membuat jadual log penyelenggaraan & OPR...', icon: '🔧' }
        ];

        function updateUI(success) {
            var container = document.getElementById('stepsContainer');
            var html = '';
            for (var i = 0; i < steps.length; i++) {
                var statusClass = 'pending';
                var icon = '⏳';
                if (i < step) {
                    statusClass = 'success';
                    icon = '✅';
                } else if (i === step && success === true) {
                    statusClass = 'success';
                    icon = '✅';
                } else if (i === step && success === false) {
                    statusClass = 'error';
                    icon = '❌';
                }
                html = html + '<div class="step ' + statusClass + '"><div class="step-title"><span class="step-icon">' + icon + '</span>' + steps[i].title + '</div>';
            }
            container.innerHTML = html;
            
            var progress = (step / steps.length) * 100;
            document.getElementById('progressBar').style.width = progress + '%';
        }

        async function runSetup() {
            document.getElementById('runBtn').disabled = true;
            document.getElementById('runBtn').innerHTML = '⏳ Sedang Memasang...';
            
            var logContainer = document.createElement('div');
            logContainer.className = 'log';
            document.getElementById('stepsContainer').after(logContainer);

            for (var i = 0; i < steps.length; i++) {
                step = i;
                updateUI();
                
                try {
                    var response = await fetch('setup.php?action=setup_step&step=' + i);
                    var result = await response.json();
                    
                    if (result.success) {
                        logContainer.innerHTML = logContainer.innerHTML + '<div class="log-entry log-success">✅ ' + result.message + '</div>';
                    } else {
                        logContainer.innerHTML = logContainer.innerHTML + '<div class="log-entry log-error">❌ ' + result.message + '</div>';
                        throw new Error(result.message);
                    }
                } catch (e) {
                    logContainer.innerHTML = logContainer.innerHTML + '<div class="log-entry log-error">❌ Ralat: ' + e.message + '</div>';
                    updateUI(false);
                    document.getElementById('runBtn').style.display = 'none';
                    document.getElementById('resetBtn').style.display = 'block';
                    return;
                }
                
                logContainer.scrollTop = logContainer.scrollHeight;
                await new Promise(function(r) { setTimeout(r, 500); });
            }
            
            step = steps.length;
            updateUI();
            
            document.getElementById('runBtn').disabled = false;
            document.getElementById('runBtn').onclick = function() { window.location.href = 'index.php'; };
            document.getElementById('runBtn').innerHTML = '➡️ Pergi ke Halaman Login';
            
            logContainer.innerHTML = logContainer.innerHTML + '<div class="log-entry log-info">🎉 Setup lengkap! Sila log keluar jika perlu.</div>';
        }

        function resetSetup() {
            location.reload();
        }

        updateUI();
    </script>
</body>
</html>
