<?php
/**
 * Teacher Dashboard - Tab 2: Students Management with Enrollment System
 * Manage students with approve/reject/auto-fallback functionality
 */

$teacherSubjects = json_decode($teacher['subjects'] ?? '[]');
?>
<!-- Tab 2: Pengurusan Pelajar -->
<div id="students" class="tab-content <?php echo $currentTab === 'students' ? 'active' : ''; ?>">
    
    <!-- Stats Cards for Enrollments -->
    <div class="stats-grid" style="margin-bottom: 25px;">
        <div class="stat-card warning">
            <div class="stat-icon">⏳</div>
            <div class="stat-content">
                <div class="stat-value" id="pendingCount">0</div>
                <div class="stat-label">Menunggu Kelulusan</div>
            </div>
            <div class="stat-bg-icon">⏳</div>
        </div>
        
        <div class="stat-card success">
            <div class="stat-icon">✅</div>
            <div class="stat-content">
                <div class="stat-value" id="approvedCount">0</div>
                <div class="stat-label">Diluluskan</div>
            </div>
            <div class="stat-bg-icon">✅</div>
        </div>
        
        <div class="stat-card" style="--card-gradient: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);">
            <div class="stat-icon">❌</div>
            <div class="stat-content">
                <div class="stat-value" id="rejectedCount">0</div>
                <div class="stat-label">Ditolak</div>
            </div>
            <div class="stat-bg-icon">❌</div>
        </div>
    </div>
    
    <!-- Main Card -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">👨‍🎓 Pengurusan Pelajar & Pendaftaran</h3>
            <div style="display: flex; gap: 10px;">
                <button class="btn btn-primary btn-sm" onclick="showAddStudentModal()">
                    <span>➕</span> Daftar Pelajar Baru
                </button>
                <button class="btn btn-secondary btn-sm" onclick="loadTeacherEnrollments('all')">
                    <span>🔄</span> Muat Semula
                </button>
            </div>
        </div>
        
        <div class="card-body">
            <!-- Status Filter -->
            <div style="margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap;">
                <button class="btn btn-secondary btn-sm" onclick="loadTeacherEnrollments('all')" data-filter="all">Semua</button>
                <button class="btn btn-warning btn-sm" onclick="loadTeacherEnrollments('pending')" data-filter="pending">Menunggu</button>
                <button class="btn btn-success btn-sm" onclick="loadTeacherEnrollments('approved')" data-filter="approved">Diluluskan</button>
                <button class="btn btn-danger btn-sm" onclick="loadTeacherEnrollments('rejected')" data-filter="rejected">Ditolak</button>
            </div>
            
            <!-- Search -->
            <div style="margin-bottom: 20px;">
                <input type="text" class="form-control" id="studentSearch" placeholder="Cari pelajar..." oninput="searchEnrollments()">
            </div>
            
            <!-- Enrollments Table -->
            <div class="table-container">
                <table class="table" id="enrollmentsTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama Pelajar</th>
                            <th>Subjek</th>
                            <th>Status</th>
                            <th>Tarikh</th>
                            <th>Tindakan</th>
                        </tr>
                    </thead>
                    <tbody id="enrollmentsList">
                        <tr><td colspan="6" class="text-center">Memuatkan...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Subject Requests -->
    <div class="card" style="margin-top: 25px;">
        <div class="card-header">
            <h3 class="card-title">📋 Pelajar Menunggu Subjek Anda</h3>
            <button class="btn btn-secondary btn-sm" onclick="loadSubjectRequests()">
                <span>🔄</span> Muat Semula
            </button>
        </div>
        <div class="card-body" id="subjectRequestsList">
            <p class="text-center text-muted">Memuatkan...</p>
        </div>
    </div>
</div>

<!-- Add Student Modal -->
<div class="modal-overlay" id="addStudentModal">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title">➕ Daftar Pelajar Baru</h3>
            <button class="modal-close" onclick="closeModal('addStudentModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="addStudentForm" onsubmit="teacherRegisterStudent(event)">
                <p style="background: #dcfce7; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 0.9rem;">
                    Pelajar yang didaftarkan akan <strong>TERUS DILULUSKAN</strong>.
                </p>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Nama Penuh <span class="required">*</span></label>
                        <input type="text" class="form-control" name="full_name" id="studentName" required placeholder="cth: Ali Bin Abu">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Umur (5-25) <span class="required">*</span></label>
                        <input type="number" class="form-control" name="age" id="studentAge" required min="5" max="25" placeholder="cth: 12">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nama Ibu Bapa/Penjaga <span class="required">*</span></label>
                    <input type="text" class="form-control" name="parent_guardian_name" id="parentGuardian" required placeholder="cth: Abu Bin Said">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Nombor Telefon <span class="required">*</span></label>
                    <input type="tel" class="form-control" name="phone" id="studentPhone" required placeholder="cth: 012-3456789">
                </div>
                
                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Tahap <span class="required">*</span></label>
                        <select class="form-control form-select" name="education_level" id="studentEducationLevel" onchange="updateStudentGradeLevel()" 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 <span class="required">*</span></label>
                        <select class="form-control form-select" name="grade_level" id="studentGradeLevel" required>
                            <option value="">Pilih Tahap Dahulu</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Subjek yang Diajar <span class="required">*</span></label>
                    <div id="teacherSubjectChecklist" class="subject-checklist" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    </div>
                    <div id="teacherSubjectError" class="form-error" style="display: none; margin-top: 10px;">Sila pilih sekurang-kurangnya satu subjek</div>
                </div>
                
                <div style="background: var(--bg-primary); padding: 15px; border-radius: 10px; margin-top: 15px;">
                    <p style="margin: 0; font-size: 0.9rem;">
                        Kata laluan lalai: <code style="background: var(--bg-secondary); padding: 3px 8px; border-radius: 4px;">pelajartutor123</code>
                    </p>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary btn-lg" style="width: 100%;">
                        💾 Daftar Pelajar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Approve Modal -->
<div class="modal-overlay" id="approveModal">
    <div class="modal" style="max-width: 500px;">
        <div class="modal-header">
            <h3 class="modal-title">✅ Luluskan Pelajar</h3>
            <button class="modal-close" onclick="closeModal('approveModal')">×</button>
        </div>
        <div class="modal-body">
            <div id="approveStudentInfo" style="margin-bottom: 20px;"></div>
            <form id="approveForm" onsubmit="approveStudent(event)">
                <input type="hidden" name="enrollment_id" id="approveEnrollmentId">
                <div class="form-group">
                    <label class="form-label">Nota (pilihan)</label>
                    <textarea class="form-control" name="notes" id="approveNotes" rows="3" placeholder="Selamat datang..."></textarea>
                </div>
                <div style="display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;" onclick="closeModal('approveModal')">Batal</button>
                    <button type="submit" class="btn btn-success" style="flex: 1;">✅ Luluskan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal-overlay" id="rejectModal">
    <div class="modal" style="max-width: 500px;">
        <div class="modal-header">
            <h3 class="modal-title">❌ Tolak Pelajar</h3>
            <button class="modal-close" onclick="closeModal('rejectModal')">×</button>
        </div>
        <div class="modal-body">
            <div id="rejectStudentInfo" style="margin-bottom: 20px; padding: 15px; background: #fee2e2; border-radius: 10px;"></div>
            <form id="rejectForm" onsubmit="rejectStudent(event)">
                <input type="hidden" name="enrollment_id" id="rejectEnrollmentId">
                <div class="form-group">
                    <label class="form-label">Sebab Penolakan <span class="required">*</span></label>
                    <textarea class="form-control" name="reason" id="rejectReason" rows="3" required placeholder="Sila nyatakan sebab..."></textarea>
                </div>
                <p style="font-size: 0.85rem; color: #dc2626; margin-bottom: 15px;">
                    Pelajar akan di-auto-assign ke guru lain jika ada.
                </p>
                <div style="display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;" onclick="closeModal('rejectModal')">Batal</button>
                    <button type="submit" class="btn btn-danger" style="flex: 1;">❌ Tolak</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var enrollmentsData = [];

document.addEventListener('DOMContentLoaded', function() {
    loadTeacherEnrollments('all');
    loadTeacherSubjects();
    loadSubjectRequests();
});

async function loadTeacherEnrollments(status) {
    try {
        const response = await fetch(`../../api.php?action=get_teacher_enrollments&status=${status}`);
        const result = await response.json();
        
        if (result.success) {
            enrollmentsData = result.enrollments || [];
            document.getElementById('pendingCount').textContent = result.stats.pending || 0;
            document.getElementById('approvedCount').textContent = result.stats.approved || 0;
            document.getElementById('rejectedCount').textContent = result.stats.rejected || 0;
            displayEnrollments(enrollmentsData);
        }
    } catch (error) {
        console.error('Error loading enrollments:', error);
        document.getElementById('enrollmentsList').innerHTML = '<tr><td colspan="6" class="text-center text-danger">Ralat memuatkan data</td></tr>';
    }
}

function displayEnrollments(enrollments) {
    const tbody = document.getElementById('enrollmentsList');
    
    if (enrollments.length > 0) {
        let html = '';
        enrollments.forEach((enrollment, index) => {
            let statusBadge = '', statusClass = '';
            switch(enrollment.status) {
                case 'Pending': statusBadge = 'Menunggu'; statusClass = 'warning'; break;
                case 'Approved': statusBadge = 'Diluluskan'; statusClass = 'success'; break;
                case 'Rejected': statusBadge = 'Ditolak'; statusClass = 'danger'; break;
            }
            
            let actions = '';
            if (enrollment.status === 'Pending') {
                actions = `<button class="btn btn-success btn-sm btn-icon" onclick="showApproveModal(${enrollment.id}, '${enrollment.student_name}', '${enrollment.subject}')" title="Luluskan">✅</button>
                <button class="btn btn-danger btn-sm btn-icon" onclick="showRejectModal(${enrollment.id}, '${enrollment.student_name}', '${enrollment.subject}')" title="Tolak">❌</button>`;
            }
            actions += `<a href="tel:${enrollment.student_phone}" class="btn btn-secondary btn-sm btn-icon" title="Hubungi">📞</a>`;
            
            html += `<tr>
                <td>${index + 1}</td>
                <td><strong>${enrollment.student_name}</strong><br><small style="color: var(--text-muted);">📞 ${enrollment.student_phone}</small></td>
                <td><span class="badge badge-primary">${enrollment.subject}</span></td>
                <td><span class="badge badge-${statusClass}">${statusBadge}</span></td>
                <td>${formatDate(enrollment.enrolled_at)}</td>
                <td><div style="display: flex; gap: 5px;">${actions}</div></td>
            </tr>`;
        });
        tbody.innerHTML = html;
    } else {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Tiada pelajar dalam kategori ini</td></tr>';
    }
}

function searchEnrollments() {
    const searchTerm = document.getElementById('studentSearch').value.toLowerCase();
    const filtered = enrollmentsData.filter(e => 
        e.student_name.toLowerCase().includes(searchTerm) ||
        e.subject.toLowerCase().includes(searchTerm)
    );
    displayEnrollments(filtered);
}

function loadTeacherSubjects() {
    const container = document.getElementById('teacherSubjectChecklist');
    const teacherSubjects = <?php echo json_encode($teacherSubjects); ?>;
    
    if (teacherSubjects.length > 0) {
        let html = '';
        teacherSubjects.forEach(subject => {
            html += `<label class="form-check">
                <input type="checkbox" class="form-check-input" name="required_subjects[]" value="${subject}">
                <span class="form-check-label">${subject}</span>
            </label>`;
        });
        container.innerHTML = html;
    } else {
        container.innerHTML = '<p class="text-muted">Tiada subjek didaftarkan. Sila hubungi admin.</p>';
    }
}

async function loadSubjectRequests() {
    const container = document.getElementById('subjectRequestsList');
    
    try {
        const response = await fetch('../../api.php?action=get_subject_requests');
        const result = await response.json();
        
        if (result.success && result.requests && result.requests.length > 0) {
            let html = '<div class="table-container"><table class="table"><thead><tr><th>Pelajar</th><th>Subjek</th><th>Tarikh</th><th>Tindakan</th></tr></thead><tbody>';
            result.requests.forEach(request => {
                html += `<tr>
                    <td><strong>${request.student_name}</strong><br><small>📞 ${request.student_phone}</small></td>
                    <td><span class="badge badge-warning">${request.requested_subject}</span></td>
                    <td>${formatDate(request.created_at)}</td>
                    <td><a href="tel:${request.student_phone}" class="btn btn-secondary btn-sm">📞</a></td>
                </tr>`;
            });
            html += '</tbody></table></div>';
            container.innerHTML = html;
        } else {
            container.innerHTML = '<p class="text-center text-muted">Tiada pelajar menunggu untuk subjek anda</p>';
        }
    } catch (error) {
        container.innerHTML = '<p class="text-center text-muted">Ralat memuatkan data</p>';
    }
}

function showAddStudentModal() {
    openModal('addStudentModal');
    document.getElementById('addStudentForm').reset();
    document.getElementById('studentGradeLevel').innerHTML = '<option value="">Pilih Tahap Dahulu</option>';
}

function updateStudentGradeLevel() {
    const educationLevel = document.getElementById('studentEducationLevel').value;
    const gradeLevel = document.getElementById('studentGradeLevel');
    let options = '<option value="">Pilih Tahun/Tingkat</option>';
    
    if (educationLevel === 'Sekolah Rendah') {
        for (let i = 1; i <= 6; i++) options += `<option value="Tahun ${i}">Tahun ${i}</option>`;
    } else if (educationLevel === 'Sekolah Menengah') {
        for (let i = 1; i <= 5; i++) options += `<option value="Ting ${i}">Ting ${i}</option>`;
    }
    gradeLevel.innerHTML = options;
}

function showApproveModal(enrollmentId, studentName, subject) {
    document.getElementById('approveEnrollmentId').value = enrollmentId;
    document.getElementById('approveStudentInfo').innerHTML = `<p><strong>Pelajar:</strong> ${studentName}</p><p style="margin:5px 0 0"><strong>Subjek:</strong> ${subject}</p>`;
    openModal('approveModal');
}

function showRejectModal(enrollmentId, studentName, subject) {
    document.getElementById('rejectEnrollmentId').value = enrollmentId;
    document.getElementById('rejectStudentInfo').innerHTML = `<p><strong>Pelajar:</strong> ${studentName}</p><p style="margin:5px 0 0"><strong>Subjek:</strong> ${subject}</p>`;
    openModal('rejectModal');
}

async function teacherRegisterStudent(event) {
    event.preventDefault();
    const subjects = document.querySelectorAll('#teacherSubjectChecklist input[name="required_subjects[]"]:checked');
    if (subjects.length === 0) {
        document.getElementById('teacherSubjectError').style.display = 'block';
        return;
    }
    document.getElementById('teacherSubjectError').style.display = 'none';
    
    const formData = new FormData(document.getElementById('addStudentForm'));
    formData.append('action', 'teacher_register_student');
    
    const submitBtn = document.querySelector('#addStudentForm button[type="submit"]');
    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('Pelajar berjaya didaftarkan!', 'success');
            closeModal('addStudentModal');
            loadTeacherEnrollments('all');
        } else {
            showNotification(result.message, 'error');
        }
    } catch (error) {
        showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '💾 Daftar Pelajar';
    }
}

async function approveStudent(event) {
    event.preventDefault();
    const formData = new FormData(document.getElementById('approveForm'));
    formData.append('action', 'approve_student');
    
    const submitBtn = document.querySelector('#approveForm button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> Memproses...';
    
    try {
        const response = await fetch('../../api.php', { method: 'POST', body: formData });
        const result = await response.json();
        
        if (result.success) {
            showNotification('Pelajar berjaya diluluskan!', 'success');
            closeModal('approveModal');
            loadTeacherEnrollments('all');
        } else {
            showNotification(result.message, 'error');
        }
    } catch (error) {
        showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '✅ Luluskan';
    }
}

async function rejectStudent(event) {
    event.preventDefault();
    const formData = new FormData(document.getElementById('rejectForm'));
    formData.append('action', 'reject_student');
    
    const submitBtn = document.querySelector('#rejectForm button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="loading-spinner"></span> Memproses...';
    
    try {
        const response = await fetch('../../api.php', { method: 'POST', body: formData });
        const result = await response.json();
        
        if (result.success) {
            let message = result.message;
            if (result.fallback_assigned) message += ` Pelajar di-assign ke ${result.next_teacher}.`;
            showNotification(message, result.fallback_assigned ? 'success' : 'warning');
            closeModal('rejectModal');
            loadTeacherEnrollments('all');
            loadSubjectRequests();
        } else {
            showNotification(result.message, 'error');
        }
    } catch (error) {
        showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '❌ Tolak';
    }
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleDateString('ms-MY', { day: '2-digit', month: '2-digit', year: 'numeric' });
}
</script>

