<?php
/**
 * Teacher Dashboard - Tab 7: Settings
 * Profile settings, password change, etc.
 * 
 * Required variables from parent:
 * - $teacher (array) - Teacher data from database
 */
?>
<!-- Tab 7: Tetapan (Content Only - No Wrapper) -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 25px;">

    <!-- Profile Settings Card -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">👤 Profil Saya</h3>
        </div>
        <div class="card-body">
            <div class="profile-section"
                style="display: flex; align-items: center; gap: 20px; margin-bottom: 25px; padding-bottom: 20px; border-bottom: 1px solid var(--border-color);">
                <div class="profile-emoji" id="profileEmojiDisplay"
                    style="font-size: 4rem; width: 100px; height: 100px; display: flex; align-items: center; justify-content: center; background: var(--bg-primary); border-radius: 50%;">
                    <?php echo htmlspecialchars($teacher['profile_emoji'] ?? '👨‍🏫'); ?>
                </div>
                <div class="profile-info">
                    <h3 style="margin: 0 0 5px;"><?php echo htmlspecialchars($teacher['full_name'] ?? ''); ?></h3>
                    <p style="margin: 0; color: var(--text-secondary);">
                        @<?php echo htmlspecialchars($teacher['username'] ?? ''); ?></p>
                </div>
            </div>

            <form id="profileForm" onsubmit="updateProfile(event)">
                <input type="hidden" name="profile_emoji" id="selectedEmoji"
                    value="<?php echo htmlspecialchars($teacher['profile_emoji'] ?? '👨‍🏫'); ?>">

                <div class="form-group">
                    <label class="form-label">Pilih Emoji Profil</label>
                    <div class="emoji-picker" id="teacherEmojiPicker">
                        <?php
                        $emojis = ['👨‍🏫', '👩‍🏫', '👨‍🎓', '👩‍🎓', '🧑‍🏫', '🧑‍🎓', '😀', '😎', '😊', '🤓'];
                        $currentEmoji = $teacher['profile_emoji'] ?? '👨‍🏫';
                        foreach ($emojis as $emoji):
                            ?>
                            <div class="emoji-option <?php echo $emoji === $currentEmoji ? 'selected' : ''; ?>"
                                data-emoji="<?php echo $emoji; ?>">
                                <?php echo $emoji; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Nama Penuh</label>
                    <input type="text" class="form-control" name="full_name"
                        value="<?php echo htmlspecialchars($teacher['full_name'] ?? ''); ?>" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Nombor Telefon</label>
                    <input type="tel" class="form-control" name="phone"
                        value="<?php echo htmlspecialchars($teacher['phone'] ?? ''); ?>" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Email <span
                            style="color: var(--text-muted); font-weight: normal;">(Optional)</span></label>
                    <input type="email" class="form-control" name="email"
                        value="<?php echo htmlspecialchars($teacher['email'] ?? ''); ?>" placeholder="contoh@email.com">
                    <p class="form-text">Email untuk pemberitahuan dan komunikasi</p>
                </div>

                <!-- Subjects Checklist (Editable) -->
                <div class="form-group">
                    <label class="form-label">📚 Subjek yang Diajar <span
                            style="color: var(--text-muted); font-weight: normal;">(Pilih satu atau
                            lebih)</span></label>
                    <div id="subjectsChecklistContainer"
                        style="display: flex; flex-wrap: wrap; gap: 10px; padding: 15px; background: var(--bg-secondary); border-radius: 8px; border: 1px solid var(--border-color);">
                        <p class="text-muted">Memuatkan senarai subjek...</p>
                    </div>
                    <p class="form-text">Tandakan subjek yang anda boleh ajar</p>
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%;">
                    💾 Simpan Profil
                </button>
            </form>
        </div>
    </div>

    <!-- Password Change Card -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">🔒 Ubah Kata Laluan</h3>
        </div>
        <div class="card-body">
            <form id="passwordForm" onsubmit="changePassword(event)">
                <div class="form-group">
                    <label class="form-label">Kata Laluan Semasa <span class="required">*</span></label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" name="current_password" id="currentPassword"
                            required placeholder="Masukkan kata laluan semasa">
                        <span class="password-toggle" onclick="togglePasswordVisibility('currentPassword')">👁️</span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Kata Laluan Baru <span class="required">*</span></label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" name="new_password" id="newPassword" required
                            placeholder="Masukkan kata laluan baru" minlength="6">
                        <span class="password-toggle" onclick="togglePasswordVisibility('newPassword')">👁️</span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Sahkan Kata Laluan Baru <span class="required">*</span></label>
                    <div class="password-wrapper">
                        <input type="password" class="form-control" name="confirm_password" id="confirmPassword"
                            required placeholder="Masukkan semula kata laluan baru">
                        <span class="password-toggle" onclick="togglePasswordVisibility('confirmPassword')">👁️</span>
                    </div>
                </div>

                <div style="background: var(--bg-primary); padding: 15px; border-radius: 10px; margin-bottom: 20px;">
                    <p style="margin: 0; font-size: 0.85rem; color: var(--text-secondary);">
                        <strong>💡 Tip:</strong> Gunakan sekurang-kurangnya 6 aksara dengan kombinasi huruf dan nombor
                        untuk keselamatan yang lebih baik.
                    </p>
                </div>

                <button type="submit" class="btn btn-primary" style="width: 100%;">
                    🔐 Tukar Kata Laluan
                </button>
            </form>
        </div>
    </div>

    <!-- Account Info Card -->
    <div class="card" style="grid-column: 1 / -1;">
        <div class="card-header">
            <h3 class="card-title">ℹ️ Maklumat Akaun</h3>
        </div>
        <div class="card-body">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                <div style="background: var(--bg-primary); padding: 20px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 2rem; margin-bottom: 10px;">👤</div>
                    <p style="margin: 0; color: var(--text-secondary); font-size: 0.85rem;">Nama Pengguna</p>
                    <strong
                        style="font-size: 1.1rem;"><?php echo htmlspecialchars($teacher['username'] ?? '-'); ?></strong>
                </div>

                <div style="background: var(--bg-primary); padding: 20px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 2rem; margin-bottom: 10px;">📅</div>
                    <p style="margin: 0; color: var(--text-secondary); font-size: 0.85rem;">Tarikh Daftar</p>
                    <strong
                        style="font-size: 1.1rem;"><?php echo $teacher['created_at'] ? date('d/m/Y', strtotime($teacher['created_at'])) : '-'; ?></strong>
                </div>

                <div style="background: var(--bg-primary); padding: 20px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 2rem; margin-bottom: 10px;">📧</div>
                    <p style="margin: 0; color: var(--text-secondary); font-size: 0.85rem;">Status Akaun</p>
                    <span class="badge badge-success" style="font-size: 1rem; padding: 8px 15px;">Aktif</span>
                </div>

                <div style="background: var(--bg-primary); padding: 20px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 2rem; margin-bottom: 10px;">🔑</div>
                    <p style="margin: 0; color: var(--text-secondary); font-size: 0.85rem;">Log Masuk Terakhir</p>
                    <strong style="font-size: 1.1rem;"><?php echo date('d/m/Y H:i'); ?></strong>
                </div>
            </div>
        </div>
    </div>

</div>

<script>
    // Teacher's current subjects (passed from PHP)
    const teacherCurrentSubjects = <?php echo json_encode(json_decode($teacher['subjects'] ?? '[]')); ?>;
    
    document.addEventListener('DOMContentLoaded', function () {
        initializeEmojiPicker();
        loadSubjectsChecklist();
    });

    // Load subjects checklist from database
    async function loadSubjectsChecklist() {
        const container = document.getElementById('subjectsChecklistContainer');
        
        try {
            const response = await fetch('../api.php?action=get_subjects');
            const result = await response.json();
            
            if (result.success && result.subjects) {
                container.innerHTML = '';
                
                result.subjects.forEach(subject => {
                    const isChecked = teacherCurrentSubjects.includes(subject.subject_name);
                    const checkboxId = 'subject_' + subject.id;
                    
                    const label = document.createElement('label');
                    label.className = 'subject-checkbox-label';
                    label.style.cssText = 'display: flex; align-items: center; gap: 8px; padding: 8px 15px; background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 20px; cursor: pointer; transition: all 0.2s; ' + (isChecked ? 'background: var(--primary-color); color: white; border-color: var(--primary-color);' : '');
                    label.innerHTML = `
                        <input type="checkbox" name="subjects[]" value="${subject.subject_name}" 
                               id="${checkboxId}" ${isChecked ? 'checked' : ''} 
                               onchange="toggleSubjectStyle(this)"
                               style="display: none;">
                        <span style="font-size: 0.9rem;">${subject.subject_name}</span>
                    `;
                    container.appendChild(label);
                });
                
                if (result.subjects.length === 0) {
                    container.innerHTML = '<p class="text-muted">Tiada subjek dalam sistem</p>';
                }
            } else {
                container.innerHTML = '<p class="text-danger">Gagal memuatkan senarai subjek</p>';
            }
        } catch (error) {
            console.error('Error loading subjects:', error);
            container.innerHTML = '<p class="text-danger">Ralat memuatkan subjek</p>';
        }
    }
    
    // Toggle checkbox label style
    function toggleSubjectStyle(checkbox) {
        const label = checkbox.parentElement;
        if (checkbox.checked) {
            label.style.background = 'var(--primary-color)';
            label.style.color = 'white';
            label.style.borderColor = 'var(--primary-color)';
        } else {
            label.style.background = 'var(--bg-primary)';
            label.style.color = 'inherit';
            label.style.borderColor = 'var(--border-color)';
        }
    }

    // Emoji Picker
    function initializeEmojiPicker() {
        const emojiOptions = document.querySelectorAll('#teacherEmojiPicker .emoji-option');
        const selectedInput = document.getElementById('selectedEmoji');

        emojiOptions.forEach(option => {
            option.addEventListener('click', function () {
                emojiOptions.forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');
                selectedInput.value = this.dataset.emoji;
                document.getElementById('profileEmojiDisplay').textContent = this.dataset.emoji;
            });
        });
    }

    function togglePasswordVisibility(inputId) {
        const input = document.getElementById(inputId);
        const toggleBtn = input.nextElementSibling;

        if (input.type === 'password') {
            input.type = 'text';
            toggleBtn.textContent = '🙈';
        } else {
            input.type = 'password';
            toggleBtn.textContent = '👁️';
        }
    }

    async function updateProfile(event) {
        event.preventDefault();

        const formData = new FormData(document.getElementById('profileForm'));
        formData.append('action', 'update_teacher_profile');
        
        // Get selected subjects
        const selectedSubjects = [];
        document.querySelectorAll('input[name="subjects[]"]:checked').forEach(cb => {
            selectedSubjects.push(cb.value);
        });
        
        // Validate at least one subject
        if (selectedSubjects.length === 0) {
            showNotification('Sila pilih sekurang-kurangnya satu subjek', 'warning');
            return;
        }
        
        // Append subjects as JSON
        formData.append('subjects', JSON.stringify(selectedSubjects));

        const submitBtn = document.querySelector('#profileForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="loading-spinner"></span> Sedang Memproses...';

        try {
            const response = await fetch('../api.php', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();

            if (result.success) {
                showNotification('Profil berjaya dikemaskini!', 'success');
                // Update session storage
                sessionStorage.setItem('profile_emoji', formData.get('profile_emoji'));
                // Reload page after short delay
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showNotification(result.message, 'error');
            }
        } catch (error) {
            showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    }

    async function changePassword(event) {
        event.preventDefault();

        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (newPassword !== confirmPassword) {
            showNotification('Kata laluan baru tidak sepadan!', 'error');
            return;
        }

        if (newPassword.length < 6) {
            showNotification('Kata laluan baru mesti sekurang-kurangnya 6 aksara!', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'change_teacher_password');
        formData.append('current_password', currentPassword);
        formData.append('new_password', newPassword);
        formData.append('confirm_password', confirmPassword);

        const submitBtn = document.querySelector('#passwordForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="loading-spinner"></span> Sedang Memproses...';

        try {
            const response = await fetch('../api.php', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();

            if (result.success) {
                showNotification('Kata laluan berjaya ditukar!', 'success');
                document.getElementById('passwordForm').reset();
            } else {
                showNotification(result.message, 'error');
            }
        } catch (error) {
            showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    }
</script>