<?php
/**
 * Teacher Registration Page - TutorKita System
 */

require_once 'db.php';

$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';

try {
    $stmt = $pdo->query("SELECT portal_name, portal_tagline, theme_color FROM admin LIMIT 1");
    $settings = $stmt->fetch();
    if ($settings) {
        $portalName = $settings['portal_name'] ?: $portalName;
        $portalTagline = $settings['portal_tagline'] ?: $portalTagline;
        $themeColor = $settings['theme_color'] ?: '#667eea';
    } else {
        $themeColor = '#667eea';
    }
} catch (Exception $e) {
    $themeColor = '#667eea';
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Guru - <?php echo htmlspecialchars($portalName); ?></title>
    <style>
        /* Back Button Style */
        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 10px 20px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-size: 0.95rem;
            font-weight: 500;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateX(-5px);
        }
        
        .back-btn:focus {
            outline: 2px solid white;
            outline-offset: 2px;
        }
        
        :root {
            --primary-color: <?php echo $themeColor; ?>;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .register-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 700px;
            width: 100%;
            margin: 0 auto;
            overflow: hidden;
            animation: slideUp 0.5s ease;
        }
        
        @keyframes slideUp {
            from { transform: translateY(30px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .register-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .logo {
            font-size: 4rem;
            margin-bottom: 10px;
        }
        
        .register-header h1 {
            font-size: 1.8rem;
            margin-bottom: 5px;
        }
        
        .register-header p {
            opacity: 0.9;
        }
        
        .register-body {
            padding: 30px;
        }
        
        .form-section {
            margin-bottom: 25px;
        }
        
        .form-section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(102, 126, 234, 0.2);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        
        .form-group label .required {
            color: #dc3545;
        }
        
        .form-control {
            width: 100%;
            padding: 14px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
        }
        
        .form-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23718096' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
            padding-right: 45px;
        }
        
        .form-check {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .form-check:hover {
            background: rgba(102, 126, 234, 0.1);
        }
        
        .form-check-input {
            width: 20px;
            height: 20px;
            margin-right: 12px;
            cursor: pointer;
            accent-color: var(--primary-color);
        }
        
        .subjects-container {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 15px 30px;
            font-size: 1.1rem;
            font-weight: 600;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .login-link {
            text-align: center;
            margin-top: 25px;
            padding-top: 25px;
            border-top: 1px solid #e0e0e0;
        }
        
        .login-link a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 600;
        }
        
        .login-link a:hover {
            text-decoration: underline;
        }
        
        .alert {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: none;
        }
        
        .alert.error {
            background: #fee2e2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }
        
        .alert.success {
            background: #dcfce7;
            color: #16a34a;
            border: 1px solid #bbf7d0;
        }
        
        .password-wrapper {
            position: relative;
        }
        
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
            font-size: 1.2rem;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .info-box {
            background: rgba(102, 126, 234, 0.1);
            border-left: 4px solid var(--primary-color);
            padding: 15px;
            border-radius: 0 10px 10px 0;
            margin-bottom: 20px;
        }
        
        .info-box p {
            margin: 0;
            color: #555;
            font-size: 0.9rem;
        }
        
        @media (max-width: 480px) {
            .register-container {
                border-radius: 15px;
            }
            
            .register-header {
                padding: 20px;
            }
            
            .logo {
                font-size: 3rem;
            }
            
            .register-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <!-- Back Button to Login Page -->
    <a href="index.php" class="back-btn">
        ← Kembali ke Log Masuk
    </a>
    
    <div class="register-container">
        <div class="register-header">
            <div class="logo">👨‍🏫</div>
            <h1><?php echo htmlspecialchars($portalName); ?></h1>
            <p><?php echo htmlspecialchars($portalTagline); ?></p>
        </div>
        
        <div class="register-body">
            <div class="alert" id="alertMessage"></div>
            
            <div class="info-box">
                <p>📝 <strong>Pendaftaran Guru Baru</strong><br>Sila isi semua maklumat di bawah untuk mendaftar sebagai guru.</p>
            </div>
            
            <form id="registerForm" onsubmit="handleRegister(event)">
                <!-- Personal Information -->
                <div class="form-section">
                    <h3 class="form-section-title">👤 Maklumat Peribadi</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Nama Penuh Guru <span class="required">*</span></label>
                        <input type="text" class="form-control" name="full_name" id="fullName" required placeholder="cth: Cikgu Ahmad Bin Ali" oninput="generateUsername()">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Nombor Telefon <span class="required">*</span></label>
                        <input type="tel" class="form-control" name="phone" required placeholder="cth: 012-3456789" pattern="[\d\-\+\s]{10,}">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Nama Pengguna (Auto-generate)</label>
                        <input type="text" class="form-control" id="username" readonly style="background: #f8f9fa;">
                        <p class="form-text">Nama pengguna akan dijana automatik berdasarkan nama</p>
                    </div>
                </div>
                
                <!-- Teaching Information -->
                <div class="form-section">
                    <h3 class="form-section-title">🎓 Maklumat Pengajaran</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Tahap Pendidikan Diajar <span class="required">*</span></label>
                        <select class="form-control form-select" name="education_level" id="educationLevel" onchange="updateGradeLevel()" required>
                            <option value="">Pilih Tahap</option>
                            <option value="Sekolah Rendah">Sekolah Rendah</option>
                            <option value="Sekolah Menengah">Sekolah Menengah</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Tahun/Tingkat Diajar <span class="required">*</span></label>
                        <select class="form-control form-select" name="grade_level" id="gradeLevel" required>
                            <option value="">Pilih Tahap Dahulu</option>
                        </select>
                    </div>
                </div>
                
                <!-- Subjects -->
                <div class="form-section">
                    <h3 class="form-section-title">📚 Subjek yang Diajar <span class="required">*</span></h3>
                    <p class="form-text" style="margin-bottom: 15px;">Pilih sekurang-kurangnya satu subjek:</p>
                    
                    <div class="subjects-container" id="subjectsChecklist">
                        <!-- Subjects will be loaded here -->
                        <p class="text-center">Memuatkan subjek...</p>
                    </div>
                    <div id="subjectError" class="form-text" style="color: #dc3545; display: none; margin-top: 10px;">Sila pilih sekurang-kurangnya satu subjek</div>
                </div>
                
                <!-- Password -->
                <div class="form-section">
                    <h3 class="form-section-title">🔐 Kata Laluan</h3>
                    
                    <div class="form-group">
                        <label class="form-label">Kata Laluan <span class="required">*</span></label>
                        <div class="password-wrapper">
                            <input type="password" class="form-control" name="password" id="password" required minlength="6" placeholder="Minimum 6 aksara">
                            <span class="password-toggle" onclick="togglePassword('password')">👁️</span>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Sahkan Kata Laluan <span class="required">*</span></label>
                        <div class="password-wrapper">
                            <input type="password" class="form-control" name="confirm_password" id="confirmPassword" required minlength="6" placeholder="Taip semula kata laluan">
                            <span class="password-toggle" onclick="togglePassword('confirmPassword')">👁️</span>
                        </div>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary" id="submitBtn">
                    📝 Daftar Sebagai Guru
                </button>
            </form>
            
            <div class="login-link">
                <p>Sudah mempunyai akaun? <a href="index.php">Log Masuk</a></p>
                <p style="margin-top: 10px;"><a href="register.php">Daftar sebagai Pelajar</a></p>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            loadSubjects();
        });
        
        async function loadSubjects() {
            try {
                var response = await fetch('api.php?action=get_subjects');
                var result = await response.json();
                
                var container = document.getElementById('subjectsChecklist');
                
                if (result.success && result.subjects.length > 0) {
                    var html = '';
                    for (var i = 0; i < result.subjects.length; i++) {
                        var subject = result.subjects[i];
                        html += '<label class="form-check">' +
                            '<input type="checkbox" class="form-check-input subject-checkbox" name="subjects[]" value="' + subject.subject_name + '" onchange="validateSubjects()">' +
                            '<span class="form-check-label">' + subject.subject_name + '</span>' +
                            '</label>';
                    }
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p class="text-center text-muted">Tiada subjek tersedia</p>';
                }
            } catch (error) {
                console.error('Error loading subjects:', error);
                document.getElementById('subjectsChecklist').innerHTML = '<p class="text-center text-danger">Ralat memuatkan subjek</p>';
            }
        }
        
        function updateGradeLevel() {
            var educationLevel = document.getElementById('educationLevel').value;
            var gradeLevel = document.getElementById('gradeLevel');
            var options = '<option value="">Pilih Tahun/Tingkat</option>';
            
            if (educationLevel === 'Sekolah Rendah') {
                for (var i = 1; i <= 6; i++) {
                    options += '<option value="Tahun ' + i + '">Tahun ' + i + '</option>';
                }
            } else if (educationLevel === 'Sekolah Menengah') {
                for (var i = 1; i <= 5; i++) {
                    options += '<option value="Ting ' + i + '">Ting ' + i + '</option>';
                }
            }
            
            gradeLevel.innerHTML = options;
        }
        
        function generateUsername() {
            var name = document.getElementById('fullName').value;
            var cleanName = name.toLowerCase().replace(/[^a-z0-9]/g, '').substring(0, 8);
            var random = Math.floor(Math.random() * 900) + 100;
            document.getElementById('username').value = cleanName + random;
        }
        
        function validateSubjects() {
            var checkboxes = document.querySelectorAll('.subject-checkbox:checked');
            var errorMsg = document.getElementById('subjectError');
            var submitBtn = document.getElementById('submitBtn');
            
            if (checkboxes.length === 0) {
                errorMsg.style.display = 'block';
                submitBtn.disabled = true;
            } else {
                errorMsg.style.display = 'none';
                submitBtn.disabled = false;
            }
        }
        
        function togglePassword(fieldId) {
            var field = document.getElementById(fieldId);
            var toggleBtn = field.nextElementSibling;
            
            if (field.type === 'password') {
                field.type = 'text';
                toggleBtn.textContent = '🙈';
            } else {
                field.type = 'password';
                toggleBtn.textContent = '👁️';
            }
        }
        
        function showAlert(message, type) {
            var alertEl = document.getElementById('alertMessage');
            alertEl.className = 'alert ' + type;
            alertEl.textContent = message;
            alertEl.style.display = 'block';
            
            setTimeout(function() {
                alertEl.style.display = 'none';
            }, 5000);
        }
        
        async function handleRegister(event) {
            event.preventDefault();
            
            var password = document.getElementById('password').value;
            var confirmPassword = document.getElementById('confirmPassword').value;
            
            if (password !== confirmPassword) {
                showAlert('Kata laluan tidak sepadan!', 'error');
                return;
            }
            
            var checkboxes = document.querySelectorAll('.subject-checkbox:checked');
            if (checkboxes.length === 0) {
                showAlert('Sila pilih sekurang-kurangnya satu subjek!', 'error');
                return;
            }
            
            var submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading-spinner"></span> Sedang Memproses...';
            
            var formData = new FormData(document.getElementById('registerForm'));
            formData.append('action', 'register_teacher');
            
            try {
                var response = await fetch('api.php', {
                    method: 'POST',
                    body: formData
                });
                
                var result = await response.json();
                
                if (result.success) {
                    showAlert(result.message, 'success');
                    document.getElementById('registerForm').reset();
                    document.getElementById('username').value = '';
                    
                    setTimeout(function() {
                        alert('Pendaftaran berjaya!\n\nNama Pengguna: ' + result.username + '\nKata Laluan: ' + result.password + '\n\nSila log masuk dengan maklumat di atas.');
                        window.location.href = 'index.php';
                    }, 1500);
                } else {
                    showAlert(result.message, 'error');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '📝 Daftar Sebagai Guru';
                }
            } catch (error) {
                showAlert('Ralat sambungan. Sila cuba lagi.', 'error');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '📝 Daftar Sebagai Guru';
            }
        }
    </script>
</body>
</html>

