<?php
/**
 * Tab Schedule Component (V3)
 * Provides a modern interface for managing teacher schedules.
 */
?>

<!-- Schedule Performance Card -->
<div id="schedule" class="tab-content">
    <div class="card p-4 mb-4"
        style="background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); color: white; border: none; border-radius: 20px; box-shadow: 0 15px 35px rgba(102, 126, 234, 0.25);">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h3 class="mb-1" style="font-weight: 700; color: white;">Kalendar & Jadual Kelas</h3>
                <p class="mb-0 text-white-50">Sila rancang dan kemaskini jadual anda dengan pelajar.</p>
            </div>
            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                <div
                    style="background: rgba(255,255,255,0.2); padding: 15px 25px; border-radius: 15px; display: inline-block; backdrop-filter: blur(5px);">
                    <div class="small text-white-50 mb-1">Slot Bulan Ini</div>
                    <div class="h2 mb-0" style="font-weight: 700;" id="scheduleMonthCount">0</div>
                </div>
            </div>
        </div>
    </div>

    <style>
        .schedule-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
        }

        .view-switcher {
            background: #f1f3f9;
            padding: 5px;
            border-radius: 12px;
            display: inline-flex;
        }

        .view-btn {
            padding: 8px 16px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 600;
            color: #64748b;
            border: none;
            background: transparent;
        }

        .view-btn.active {
            background: white;
            color: var(--primary-color);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 12px;
            margin-top: 15px;
        }

        .calendar-day-name {
            text-align: center;
            font-weight: 600;
            color: #94a3b8;
            font-size: 0.8rem;
            text-transform: uppercase;
            padding-bottom: 10px;
        }

        .calendar-day {
            aspect-ratio: 1;
            background: white;
            border: 1px solid #f1f5f9;
            border-radius: 12px;
            padding: 10px;
            position: relative;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            min-height: 80px;
        }

        .calendar-day:hover {
            border-color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }

        .calendar-day.today {
            border-color: var(--primary-color);
            background: #f8faff;
        }

        .calendar-day.today span {
            color: var(--primary-color);
            font-weight: 700;
        }

        .calendar-day.other-month {
            opacity: 0.4;
            background: #f8fafc;
            cursor: default;
        }

        .calendar-day.selected {
            background: var(--primary-color) !important;
            border-color: var(--primary-color) !important;
            color: white !important;
        }

        .calendar-day.selected .event-dot {
            background: white !important;
        }

        .dot-container {
            display: flex;
            gap: 3px;
            flex-wrap: wrap;
            margin-top: 5px;
        }

        .event-dot {
            width: 6px;
            height: 6px;
            border-radius: 50%;
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            margin-bottom: 15px;
        }
    </style>

    <div class="card shadow-sm border-0" style="border-radius: 20px; overflow: hidden;">
        <div class="card-header bg-white border-0 pt-4 px-4">
            <div class="schedule-controls">
                <div class="view-switcher">
                    <button class="view-btn active" id="viewListBtn"
                        onclick="changeScheduleViewV3('list')">Senarai</button>
                    <button class="view-btn" id="viewCalendarBtn"
                        onclick="changeScheduleViewV3('calendar')">Kalendar</button>
                </div>

                <div class="d-flex gap-2 align-items-center">
                    <!-- Filter Owner/All -->
                    <div class="btn-group me-2" role="group">
                        <button type="button" class="btn btn-outline-primary btn-sm active" id="btnFilterOwn"
                            onclick="filterScheduleViewV3('own')">Jadual Saya</button>
                        <button type="button" class="btn btn-outline-primary btn-sm" id="btnFilterAll"
                            onclick="filterScheduleViewV3('all')">Semua Guru</button>
                    </div>

                    <select id="teacherFilterSelect" class="form-select" style="width: 200px; border-radius: 12px;" onchange="filterScheduleByTeacherV3(this.value)">
                        <option value="">Semua Guru</option>
                    </select>

                    <input type="text" id="scheduleTeacherSearch" class="form-control"
                        placeholder="Cari tajuk/subjek..." style="width: 200px; border-radius: 12px;"
                        onkeyup="searchTeacherScheduleV3()">
                    <button class="btn btn-primary" style="border-radius: 12px;" onclick="showAddScheduleModalV3()">
                        <i class="fas fa-plus me-2"></i> Tambah
                    </button>
                </div>
            </div>
        </div>

        <div class="card-body p-4" id="scheduleContent">
            <!-- Content will be injected by JavaScript -->
            <div class="text-center py-5">
                <div class="loading-spinner mb-3"></div>
                <p class="text-muted">Memuatkan jadual...</p>
            </div>
        </div>
    </div>
</div>

<!-- Add Schedule Modal -->
<div class="modal-overlay" id="scheduleModal">
    <div class="modal" style="max-width: 500px;">
        <div class="modal-header">
            <h5 class="modal-title">Tambah Jadual Baru</h5>
            <button class="modal-close" onclick="closeModal('scheduleModal')">&times;</button>
        </div>
        <div class="modal-body">
            <form id="scheduleForm" onsubmit="saveScheduleV3(event)">
                <input type="hidden" id="scheduleId" name="id">
                <div class="mb-3">
                    <label class="form-label">Tajuk Kelas / Topik</label>
                    <input type="text" class="form-control" name="title" required
                        placeholder="Contoh: Kelas Matematik Bab 1">
                </div>
                <div class="mb-3">
                    <label class="form-label">Subjek</label>
                    <select class="form-control" name="subject" id="scheduleSubjectSelect" required>
                        <option value="">Memuatkan subjek...</option>
                    </select>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Tarikh</label>
                        <input type="date" class="form-control" name="schedule_date" required
                            min="<?php echo date('Y-m-d'); ?>">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Waktu Mula</label>
                        <input type="time" class="form-control" name="start_time" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Waktu Tamat</label>
                        <input type="time" class="form-control" name="end_time" required>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Nota Tambahan (Opsional)</label>
                    <textarea class="form-control" name="notes" rows="2"
                        placeholder="Sila bawa buku teks..."></textarea>
                </div>
                <button type="submit" class="btn btn-primary w-100 py-3"
                    style="border-radius: 15px; font-weight: 600;">Simpan Jadual</button>
            </form>
        </div>
    </div>
</div>

<script>
    // Schedule Logic V3
    var MY_TEACHER_SUBJECTS = <?php echo json_encode(isset($teacherSubjects) ? $teacherSubjects : []); ?>;
    var allSchedulesDataV3 = [];
    var currentScheduleViewV3 = 'list';
    var currentScheduleFilterV3 = 'own'; // 'own' or 'all'
    var currentTeacherFilterId = null; // New: Stores selected teacher ID for filtering
    var currentCalendarDate = new Date();
    var selectedCalendarDate = null;

    function filterScheduleViewV3(filter) {
        currentScheduleFilterV3 = filter;
        currentTeacherFilterId = null; // Reset teacher filter when switching view
        document.getElementById('teacherFilterSelect').value = ''; // Reset dropdown

        // Update Active Button State
        document.getElementById('btnFilterOwn').classList.toggle('active', filter === 'own');
        document.getElementById('btnFilterAll').classList.toggle('active', filter === 'all');

        // Reload schedule with new filter
        loadScheduleV3();
    }

    function filterScheduleByTeacherV3(teacherId) {
        currentTeacherFilterId = teacherId;
        currentScheduleFilterV3 = 'all'; // Always show 'all' when filtering by specific teacher
        document.getElementById('btnFilterOwn').classList.remove('active');
        document.getElementById('btnFilterAll').classList.add('active');
        loadScheduleV3();
    }

    function loadScheduleV3() {
        console.log('Loading Schedule V3... Filter:', currentScheduleFilterV3, 'Teacher ID:', currentTeacherFilterId);
        var container = document.getElementById('scheduleContent');
        if (container && !container.innerHTML.includes('table')) {
            container.innerHTML = '<div class="text-center py-5"><div class="loading-spinner mb-3"></div><p class="text-muted">Memuatkan jadual...</p></div>';
        }

        let apiUrl = API_PATH + '?action=get_teacher_schedule&view=' + currentScheduleFilterV3;
        if (currentTeacherFilterId) {
            apiUrl += '&teacher_id=' + currentTeacherFilterId;
        }

        fetch(apiUrl)
            .then(function (response) {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.text();
            })
            .then(function (text) {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    if (text.indexOf('<br />') !== -1 || text.indexOf('<b>') !== -1) {
                        throw new Error('Server Error: ' + text.replace(/<[^>]*>?/gm, '').substring(0, 100));
                    }
                    throw new Error('Invalid JSON response');
                }
            })
            .then(function (result) {
                if (result.success && result.schedules) {
                    allSchedulesDataV3 = result.schedules;
                    // Filter schedules for MONTH slot count
                    var now = new Date();
                    var currentMonthPrefix = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
                    var monthCount = allSchedulesDataV3.filter(function (s) {
                        return s.schedule_date.startsWith(currentMonthPrefix);
                    }).length;
                    var monthCountElem = document.getElementById('scheduleMonthCount');
                    if (monthCountElem) monthCountElem.textContent = monthCount;
                    displayScheduleV3();
                } else {
                    allSchedulesDataV3 = []; // Ensure it is empty array
                    // If list view, show empty state immediately. If calendar, let displayScheduleV3 handle it.
                    if (currentScheduleViewV3 === 'list') {
                        document.getElementById('scheduleContent').innerHTML = '<div class="text-center py-5"><p class="text-muted">Tiada jadual dijumpai</p><button class="btn btn-primary rounded-pill px-4" onclick="showAddScheduleModalV3()">Tambah Jadual</button></div>';
                    } else {
                        displayScheduleV3();
                    }

                    var monthCountElem = document.getElementById('scheduleMonthCount');
                    if (monthCountElem) monthCountElem.textContent = '0';
                }
            })
            .catch(function (err) {
                console.error('Error loading schedule:', err);
                var container = document.getElementById('scheduleContent');
                if (container) {
                    container.innerHTML = '<div style="text-align:center; padding:40px; color:#dc3545;"><i class="fas fa-exclamation-triangle" style="font-size:2rem; margin-bottom:10px;"></i><p><strong>Ralat Memuatkan Jadual</strong></p><p style="font-size:0.85rem; opacity:0.8;">' + err.message + '</p><button class="btn btn-sm btn-outline-primary mt-2" onclick="loadScheduleV3()">Cuba Lagi</button></div>';
                }
            });
    }

    function loadTeacherFilterDropdown() {
        fetch(API_PATH + '?action=getTeacherList')
            .then(response => response.json())
            .then(result => {
                if (result.success && result.teachers) {
                    const selectElement = document.getElementById('teacherFilterSelect');
                    selectElement.innerHTML = '<option value="">Semua Guru</option>'; // Reset and add default
                    result.teachers.forEach(teacher => {
                        const option = document.createElement('option');
                        option.value = teacher.id;
                        option.textContent = teacher.full_name;
                        selectElement.appendChild(option);
                    });
                } else {
                    console.error('Failed to load teachers:', result.message);
                }
            })
            .catch(error => console.error('Error fetching teachers:', error));
    }

    // Call this function on page load
    document.addEventListener('DOMContentLoaded', loadTeacherFilterDropdown);

    function displayScheduleV3(filteredData) {
        var data = filteredData || allSchedulesDataV3;
        var container = document.getElementById('scheduleContent');

        // Allow Calendar view to render even if data is empty
        if (data.length === 0 && !filteredData && currentScheduleViewV3 === 'list') {
            container.innerHTML = '<div style="text-align: center; padding: 40px;"><div style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;">📅</div><p class="text-muted">Tiada jadual untuk dipaparkan</p><button class="btn btn-primary rounded-pill" onclick="showAddScheduleModalV3()">Tambah Jadual</button></div>';
            return;
        }

        if (currentScheduleViewV3 === 'list') {
            data.sort(function (a, b) {
                return new Date(b.schedule_date + ' ' + b.start_time) - new Date(a.schedule_date + ' ' + a.start_time);
            });

            var html = '<div class="table-responsive"><table class="table highlight-row"><thead><tr><th>Tarikh</th><th>Masa</th><th>Subjek / Topik</th><th>Guru</th><th>Tindakan</th></tr></thead><tbody>';
            if (data.length > 0) {
                data.forEach(function (s) {
                    var isOwner = (parseInt(s.teacher_id) === CURRENT_USER_ID);
                    html += '<tr>' +
                        '<td>' + (typeof formatDate === 'function' ? formatDate(s.schedule_date) : s.schedule_date) + '</td>' +
                        '<td>' + (typeof formatTime === 'function' ? formatTime(s.start_time) : s.start_time) + (s.end_time ? ' - ' + (typeof formatTime === 'function' ? formatTime(s.end_time) : s.end_time) : '') + '</td>' +
                        '<td><strong>' + s.title + '</strong><br><small class="text-muted">' + (s.subject || '-') + '</small></td>' +
                        '<td>' + (s.teacher_name || 'Anda') + '</td>' +
                        '<td>' + (isOwner ? '<button class="btn btn-danger btn-sm" onclick="deleteScheduleV3(' + s.id + ')">🗑️</button>' : '') + '</td>' +
                        '</tr>';
                });
            } else {
                html += '<tr><td colspan="5" class="text-center text-muted py-4">Tiada hasil carian</td></tr>';
            }
            html += '</tbody></table></div>';
            container.innerHTML = html;
        } else {
            renderCalendarV3(data);
        }
    }

    function renderCalendarV3(data) {
        var container = document.getElementById('scheduleContent');
        var year = currentCalendarDate.getFullYear();
        var month = currentCalendarDate.getMonth();
        var monthNames = ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"];

        var html = '<div class="calendar-header">' +
            '<button class="btn btn-sm btn-outline-secondary" onclick="changeCalendarMonthV3(-1)"><i class="fas fa-chevron-left"></i></button>' +
            '<h4 style="margin:0; font-weight:700; color:#1a1a2e;">' + monthNames[month] + ' ' + year + '</h4>' +
            '<button class="btn btn-sm btn-outline-secondary" onclick="changeCalendarMonthV3(1)"><i class="fas fa-chevron-right"></i></button>' +
            '</div>' +
            '<div class="calendar-grid">' +
            '<div class="calendar-day-name">Ahad</div><div class="calendar-day-name">Isnin</div><div class="calendar-day-name">Selasa</div><div class="calendar-day-name">Rabu</div><div class="calendar-day-name">Khamis</div><div class="calendar-day-name">Jumaat</div><div class="calendar-day-name">Sabtu</div>' +
            renderCalendarGridV3(year, month, data) +
            '</div>' +
            '<div style="margin-top:20px; border-top:1px dashed #eee; padding-top:15px;">' +
            '<h6 class="text-muted mb-3" style="font-size:0.9rem; text-transform:uppercase; letter-spacing:1px;">Jadual ' + (selectedCalendarDate ? (typeof formatDate === 'function' ? formatDate(selectedCalendarDate) : selectedCalendarDate) : 'Bulan Ini') + '</h6>' +
            '<div id="calendarEventsList"></div>' +
            '</div>';

        container.innerHTML = html;
        updateCalendarEventsList(data);
    }

    function getTeacherColorV3(id) {
        // Palette of distinct colors
        var colors = [
            '#4e73df', // Blue
            '#1cc88a', // Green
            '#36b9cc', // Cyan
            '#f6c23e', // Yellow
            '#e74a3b', // Red
            '#6f42c1', // Purple
            '#fd7e14', // Orange
            '#20c997', // Teal
            '#e83e8c'  // Pink
        ];
        return colors[parseInt(id) % colors.length];
    }

    function renderCalendarGridV3(year, month, data) {
        var firstDay = new Date(year, month, 1).getDay();
        var daysInMonth = new Date(year, month + 1, 0).getDate();
        var daysInPrevMonth = new Date(year, month, 0).getDate();
        var today = new Date();
        var isCurrentMonth = today.getFullYear() === year && today.getMonth() === month;

        var html = '';
        var dayCount = 1;
        var nextMonthDay = 1;

        for (var i = 0; i < 6; i++) {
            for (var j = 0; j < 7; j++) {
                if (i === 0 && j < firstDay) {
                    html += '<div class="calendar-day other-month">' + (daysInPrevMonth - (firstDay - j - 1)) + '</div>';
                } else if (dayCount > daysInMonth) {
                    html += '<div class="calendar-day other-month">' + (nextMonthDay++) + '</div>';
                } else {
                    var dateStr = year + '-' + (month + 1).toString().padStart(2, '0') + '-' + dayCount.toString().padStart(2, '0');
                    var isToday = isCurrentMonth && dayCount === today.getDate();
                    var isSelected = selectedCalendarDate === dateStr;
                    var dayEvents = data.filter(function (s) { return s.schedule_date === dateStr; });
                    var dotsHtml = '';
                    if (dayEvents.length > 0) {
                        dotsHtml = '<div class="dot-container">';
                        for (var k = 0; k < Math.min(dayEvents.length, 4); k++) {
                            var ev = dayEvents[k];
                            // Use teacher_id for color mapping
                            var dotColor = getTeacherColorV3(ev.teacher_id);
                            var tooltipText = (ev.teacher_name || 'Guru');
                            if (currentScheduleFilterV3 === 'all' && !currentTeacherFilterId) {
                                tooltipText = (ev.teacher_name || 'Guru') + ': ' + ev.title;
                            }
                            dotsHtml += '<div class="event-dot" style="background-color: ' + dotColor + ';" title="' + tooltipText + '"></div>';
                        }
                        if (dayEvents.length > 4) dotsHtml += '<small style="font-size:0.6rem;">+</small>';
                        dotsHtml += '</div>';
                    }
                    html += '<div class="calendar-day ' + (isToday ? 'today' : '') + ' ' + (isSelected ? 'selected' : '') + '" onclick="selectCalendarDateV3(\'' + dateStr + '\')"><span>' + dayCount + '</span>' + dotsHtml + '</div>';
                    dayCount++;
                }
            }
            if (dayCount > daysInMonth && ((i + 1) * 7) >= (firstDay + daysInMonth)) break;
        }
        return html;
    }

    function changeCalendarMonthV3(step) {
        currentCalendarDate.setMonth(currentCalendarDate.getMonth() + step);
        renderCalendarV3(allSchedulesDataV3);
    }

    function selectCalendarDateV3(dateStr) {
        selectedCalendarDate = dateStr;
        renderCalendarV3(allSchedulesDataV3);
    }

    function updateCalendarEventsList(data) {
        var container = document.getElementById('calendarEventsList');
        if (!container) return;
        var filtered = data;
        if (selectedCalendarDate) {
            filtered = data.filter(function (s) { return s.schedule_date === selectedCalendarDate; });
            if (filtered.length === 0) { container.innerHTML = '<p class="text-muted text-center small py-3">Tiada kelas pada tarikh ini.</p>'; return; }
        } else {
            var mStr = (currentCalendarDate.getMonth() + 1).toString().padStart(2, '0');
            var yStr = currentCalendarDate.getFullYear().toString();
            var prefix = yStr + '-' + mStr;
            filtered = data.filter(function (s) { return s.schedule_date.indexOf(prefix) === 0; });
            if (filtered.length === 0) { container.innerHTML = '<p class="text-muted text-center small py-3">Tiada kelas pada bulan ini.</p>'; return; }
        }
        filtered.sort(function (a, b) { return a.start_time.localeCompare(b.start_time); });
        var html = '<div class="list-group list-group-flush">';
        filtered.forEach(function (s) {
            var isOwner = (parseInt(s.teacher_id) === CURRENT_USER_ID);
            var teacherColor = getTeacherColorV3(s.teacher_id);

            html += '<li class="list-group-item d-flex justify-content-between align-items-center" style="border-left: 5px solid ' + getTeacherColorV3(s.teacher_id) + ';">' +
                '<div class="d-flex align-items-center gap-3">' +
                '<div style="text-align:center; min-width:60px;">' +
                '<div style="font-weight:bold; font-size:1.0rem; color:var(--primary-color);">' + (typeof formatTime === 'function' ? formatTime(s.start_time) : s.start_time) + '</div>' +
                '<small class="text-muted" style="font-size:0.75rem;">' + (s.end_time ? (typeof formatTime === 'function' ? formatTime(s.end_time) : s.end_time) : '') + '</small>' +
                '</div>' +
                '<div style="padding-left:12px;">' +
                (currentScheduleFilterV3 === 'all' && !currentTeacherFilterId ? '<span class="badge bg-primary-subtle text-primary mb-1">' + (s.teacher_name || 'Guru') + '</span><br>' : '') +
                '<h6 class="mb-0" style="font-weight:600;">' + s.title + '</h6>' +
                '<small style="display:block; color:#666;">' + (s.subject || '-') + '</small>' +
                '<small style="display:block; font-weight:500; color:' + teacherColor + '; margin-top:2px;">Oleh Tutor: ' + (s.teacher_name || 'Anda') + '</small>' +
                (currentScheduleFilterV3 === 'all' && !currentTeacherFilterId ? '<br><small class="text-info">Guru: ' + (s.teacher_name || 'Tidak Diketahui') + '</small>' : '') +
                '</div>' +
                 (isOwner ? '<button class="btn btn-outline-danger btn-sm rounded-circle" style="width:30px;height:30px;padding:0;display:flex;align-items:center;justify-content:center;" onclick="deleteScheduleV3(' + s.id + ')"><i class="fas fa-trash-alt" style="font-size:0.8rem;"></i></button>' : '') +
                '</div>';
        });
        html += '</div>';
        container.innerHTML = html;
    }

    function changeScheduleViewV3(view) {
        currentScheduleViewV3 = view;
        var listBtn = document.getElementById('viewListBtn');
        var calBtn = document.getElementById('viewCalendarBtn');
        if (listBtn) listBtn.classList.toggle('active', view === 'list');
        if (calBtn) calBtn.classList.toggle('active', view === 'calendar');
        displayScheduleV3();
    }

    function searchTeacherScheduleV3() {
        var query = document.getElementById('scheduleTeacherSearch').value.toLowerCase();
        if (!query) { displayScheduleV3(); return; }
        var filtered = allSchedulesDataV3.filter(function (s) {
            return (s.teacher_name && s.teacher_name.toLowerCase().includes(query)) ||
                (s.title && s.title.toLowerCase().includes(query)) ||
                (s.subject && s.subject.toLowerCase().includes(query));
        });
        displayScheduleV3(filtered);
    }

    function showAddScheduleModalV3() {
        if (typeof openModal === 'function') openModal('scheduleModal');
        else document.getElementById('scheduleModal').classList.add('active');
        
        // Load subjects if not loaded
        loadSubjectsV3();
        
        var scheduleForm = document.getElementById('scheduleForm');
        var scheduleId = document.getElementById('scheduleId');
        if (scheduleForm) scheduleForm.reset();
        if (scheduleId) scheduleId.value = '';
    }

    var subjectsLoadedV3 = false;

    function getSubjectIconV3(subject) {
        var icons = {
            'Matematik': '🔢', 'Mathematics': '🔢',
            'Sains': '🔬', 'Science': '🔬',
            'Bahasa Melayu': '📖', 'Malay Language': '📖',
            'Bahasa Inggeris': '🗣️', 'English Language': '🗣️',
            'Sejarah': '📜', 'History': '📜',
            'Geografi': '🌍', 'Geography': '🌍',
            'Pendidikan Islam': '☪️', 'Islamic Education': '☪️',
            'Pendidikan Moral': '💡', 'Moral Education': '💡',
            'Fizik': '⚛️', 'Physics': '⚛️',
            'Kimia': '🧪', 'Chemistry': '🧪',
            'Biologi': '🧬', 'Biology': '🧬',
            'Ekonomi': '💰', 'Economics': '💰',
            'Perakaunan': '📊', 'Accounting': '📊',
            'Perniagaan': '💼', 'Business': '💼',
            'Seni': '🎨', 'Art': '🎨',
            'Muzik': '🎵', 'Music': '🎵',
            'Pendidikan Jasmani': '⚽', 'Physical Education': '⚽',
            'Teknologi Maklumat': '💻', 'Information Technology': '💻'
        };
        return icons[subject] || '📚';
    }

    function loadSubjectsV3() {
        if (subjectsLoadedV3) return;
        
        var select = document.getElementById('scheduleSubjectSelect');
        if (!select) return;

        fetch(API_PATH + '?action=get_subjects')
            .then(function(res) { return res.json(); })
            .then(function(result) {
                if (result.success && result.subjects) {
                    var html = '<option value="">Pilih Subjek...</option>';
                    
                    // Filter based on teacher's subjects
                    var subjectsToRender = result.subjects;
                    if (typeof MY_TEACHER_SUBJECTS !== 'undefined' && Array.isArray(MY_TEACHER_SUBJECTS) && MY_TEACHER_SUBJECTS.length > 0) {
                        subjectsToRender = result.subjects.filter(function(sub) {
                            return MY_TEACHER_SUBJECTS.includes(sub.subject_name);
                        });
                    }

                    if (subjectsToRender.length > 0) {
                        subjectsToRender.forEach(function(sub) {
                            var icon = getSubjectIconV3(sub.subject_name);
                            var label = icon + ' ' + sub.subject_name;
                            if (sub.education_level && sub.education_level !== 'Semua') {
                                label += ' (' + sub.education_level + ')';
                            }
                            html += '<option value="' + sub.subject_name + '">' + label + '</option>';
                        });
                        select.innerHTML = html;
                        subjectsLoadedV3 = true;
                    } else {
                        select.innerHTML = '<option value="">Tiada subjek yang padan</option>';
                    }
                } else {
                    select.innerHTML = '<option value="">Tiada subjek dijumpai</option>';
                }
            })
            .catch(function(err) {
                console.error('Error loading subjects:', err);
                select.innerHTML = '<option value="">Ralat memuatkan subjek</option>';
            });
    }

    function saveScheduleV3(event) {
        event.preventDefault();
        var form = document.getElementById('scheduleForm');
        var formData = new FormData(form);
        formData.append('action', 'add_schedule');
        var submitBtn = form.querySelector('button[type="submit"]');
        var originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sedang Simpan...';
        fetch(API_PATH, { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    if (typeof showNotificationV2 === 'function') showNotificationV2('Jadual berjaya disimpan', 'success');
                    if (typeof closeModal === 'function') closeModal('scheduleModal');
                    else document.getElementById('scheduleModal').classList.remove('active');
                    loadScheduleV3();
                } else {
                    if (typeof showNotificationV2 === 'function') showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                console.error('Error saving schedule:', err);
                if (typeof showNotificationV2 === 'function') showNotificationV2('Ralat sambungan', 'error');
            })
            .finally(function () {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
    }

    function deleteScheduleV3(id) {
        var themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                title: 'Padam Jadual?',
                text: 'Jadual ini akan dipadamkan secara kekal.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: themeColor,
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Padam',
                cancelButtonText: 'Batal',
                borderRadius: '15px',
                reverseButtons: true
            }).then(function (result) {
                if (result.isConfirmed) { performDeleteSchedule(id); }
            });
        } else if (confirm('Padam jadual ini?')) {
            performDeleteSchedule(id);
        }
    }

    function performDeleteSchedule(id) {
        var formData = new FormData();
        formData.append('action', 'delete_schedule');
        formData.append('id', id);
        fetch(API_PATH, { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    if (typeof showNotificationV2 === 'function') showNotificationV2('Jadual berjaya dipadam', 'success');
                    loadScheduleV3();
                } else {
                    if (typeof showNotificationV2 === 'function') showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                if (typeof showNotificationV2 === 'function') showNotificationV2('Ralat sambungan', 'error');
            });
    }
</script>