<?php
// Schedule Tab Component
// Located at: components/teacher/tab-schedule.php
?>
<div id="schedule" class="tab-content">
    <div class="card" style="margin-bottom: 25px;">
        <div class="card-body">
            <div class="info-card-badge"
                style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
                <div>
                    <h4 style="margin: 0 0 5px 0; color: var(--primary-color);">📅 Jadual
                        Mengajar</h4>
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">Urus jadual kelas,
                        sesi mengajar, dan aktiviti anda.</p>
                </div>
                <div style="display: flex; gap: 10px;">
                    <span class="badge badge-warning" style="padding: 8px 15px; font-size: 0.9rem;">⏳ Sesi Hari
                        Ini: <span id="scheduleTodayCount">-</span></span>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3 class="card-title">📅 Jadual Waktu</h3>
            <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                <div class="btn-group">
                    <button class="btn btn-outline-primary btn-sm active" id="viewListBtn"
                        onclick="changeScheduleViewV3('list')">Senarai</button>
                    <button class="btn btn-outline-primary btn-sm" id="viewCalendarBtn"
                        onclick="changeScheduleViewV3('calendar')">Kalendar</button>
                </div>
                <!-- Search Teacher Schedule (Admin/All Teachers View) -->
                <?php if ($isMegaAdmin || $isSuperAdmin): ?>
                    <input type="text" class="form-control form-control-sm" id="scheduleTeacherSearch"
                        placeholder="Cari guru..." oninput="searchTeacherScheduleV3()"
                        style="width: 150px; display: inline-block;">
                <?php endif; ?>
                <button class="btn btn-primary btn-sm" onclick="showAddScheduleModalV3()">
                    <span>➕</span> Tambah Jadual
                </button>
            </div>
        </div>
        <div class="card-body">
            <div id="scheduleContent" style="min-height: 300px;">
                <p class="text-center text-muted">Memuatkan jadual...</p>
            </div>
        </div>
    </div>
</div>

<!-- SCHEDULE MODALS -->
<div class="modal-overlay" id="scheduleModal">
    <div class="modal" style="max-width: 600px;">
        <div class="modal-header">
            <h3 class="modal-title">📅 Tambah Jadual</h3>
            <button class="modal-close" onclick="closeModal('scheduleModal')">×</button>
        </div>
        <div class="modal-body">
            <form id="scheduleForm" onsubmit="saveScheduleV3(event)">
                <input type="hidden" name="id" id="scheduleId">

                <div class="form-group">
                    <label class="form-label">Tajuk Sesi <span class="required">*</span></label>
                    <input type="text" class="form-control" name="title" id="scheduleTitle" required
                        placeholder="cth: Kelas Matematik">
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Subjek <span class="required">*</span></label>
                        <select class="form-control form-select" name="subject" id="scheduleSubject" required>
                            <option value="">Pilih Subjek</option>
                            <?php foreach ($teacherSubjects as $subject): ?>
                                <option value="<?php echo htmlspecialchars($subject); ?>">
                                    <?php echo htmlspecialchars($subject); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Tarikh <span class="required">*</span></label>
                        <input type="date" class="form-control" name="schedule_date" id="scheduleDate" required>
                    </div>
                </div>

                <div class="form-row" style="grid-template-columns: 1fr 1fr;">
                    <div class="form-group">
                        <label class="form-label">Masa Mula <span class="required">*</span></label>
                        <input type="time" class="form-control" name="start_time" id="scheduleStartTime" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Masa Tamat</label>
                        <input type="time" class="form-control" name="end_time" id="scheduleEndTime">
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Penerangan</label>
                    <textarea class="form-control" name="description" id="scheduleDescription" rows="3"
                        placeholder="Penerangan sesi..."></textarea>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" style="flex: 1;"
                        onclick="closeModal('scheduleModal')">Batal</button>
                    <button type="submit" class="btn btn-primary" style="flex: 1;">💾 Simpan Jadual</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Schedule Logic V3
    var allSchedulesDataV3 = [];
    var currentScheduleViewV3 = 'list';

    function loadScheduleV3() {
        console.log('Loading Schedule V3...');
        fetch(API_PATH + '?action=get_teacher_schedule')
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success && result.schedules) {
                    allSchedulesDataV3 = result.schedules;

                    // Update today count
                    var today = new Date().toISOString().split('T')[0];
                    var todayCount = allSchedulesDataV3.filter(function (s) { return s.schedule_date === today; }).length;
                    var todayCountElem = document.getElementById('scheduleTodayCount');
                    if (todayCountElem) todayCountElem.textContent = todayCount;

                    displayScheduleV3();
                } else {
                    document.getElementById('scheduleContent').innerHTML = '<p class="text-muted text-center">Tiada jadual dijumpai</p>';
                    var todayCountElem = document.getElementById('scheduleTodayCount');
                    if (todayCountElem) todayCountElem.textContent = '0';
                }
            })
            .catch(function (err) {
                console.error('Error loading schedule:', err);
                document.getElementById('scheduleContent').innerHTML = '<p class="text-danger text-center">Ralat memuatkan jadual</p>';
            });
    }

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

        if (data.length === 0) {
            container.innerHTML = '<div style="text-align: center; padding: 40px;"><p class="text-muted">Tiada jadual untuk dipaparkan</p><button class="btn btn-primary" onclick="showAddScheduleModalV3()">Tambah Jadual</button></div>';
            return;
        }

        if (currentScheduleViewV3 === 'list') {
            // List View
            // Sort by date/time desc
            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">';
            html += '<thead><tr><th>Tarikh</th><th>Masa</th><th>Subjek / Topik</th><th>Guru</th><th>Tindakan</th></tr></thead><tbody>';

            data.forEach(function (s) {
                var isOwner = (parseInt(s.teacher_id) === CURRENT_USER_ID);
                html += '<tr>';
                html += '<td>' + formatDate(s.schedule_date) + '</td>';
                html += '<td>' + formatTime(s.start_time) + (s.end_time ? ' - ' + formatTime(s.end_time) : '') + '</td>';
                html += '<td><strong>' + s.title + '</strong><br><small class="text-muted">' + (s.subject || '-') + '</small></td>';
                html += '<td>' + (s.teacher_name || 'Anda') + '</td>';
                html += '<td>';
                if (isOwner) {
                    html += '<button class="btn btn-danger btn-sm" onclick="deleteScheduleV3(' + s.id + ')">🗑️</button>';
                }
                html += '</td>';
                html += '</tr>';
            });
            html += '</tbody></table></div>';
            container.innerHTML = html;

        } else {
            // Calendar View (Simple Implementation)
            container.innerHTML = '<p class="text-center text-muted">Paparan Kalendar akan datang...</p>';
            // You can integrate FullCalendar here later if requested
        }
    }

    function changeScheduleViewV3(view) {
        currentScheduleViewV3 = view;
        document.getElementById('viewListBtn').classList.toggle('active', view === 'list');
        document.getElementById('viewCalendarBtn').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() {
        openModal('scheduleModal');
        var scheduleForm = document.getElementById('scheduleForm');
        var scheduleId = document.getElementById('scheduleId');
        if (scheduleForm) scheduleForm.reset();
        if (scheduleId) scheduleId.value = '';
    }

    function saveScheduleV3(event) {
        event.preventDefault();
        var formData = new FormData(document.getElementById('scheduleForm'));
        formData.append('action', 'add_schedule');

        fetch(API_PATH, { method: 'POST', body: formData })
            .then(function (response) { return response.json(); })
            .then(function (result) {
                if (result.success) {
                    showNotificationV2('Jadual berjaya disimpan', 'success');
                    closeModal('scheduleModal');
                    loadScheduleV3();
                    // Update dashboard stats too if function exists
                    if (typeof loadTodaySlotsV3 === 'function') loadTodaySlotsV3();
                } else {
                    showNotificationV2(result.message, 'error');
                }
            })
            .catch(function (err) {
                showNotificationV2('Ralat sambungan', 'error');
            });
    }

    function deleteScheduleV3(id) {
        // Get portal theme color
        const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim() || '#667eea';

        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((result) => {
            if (result.isConfirmed) {
                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) {
                            showNotificationV2('Jadual berjaya dipadam', 'success');
                            loadScheduleV3();
                            if (typeof loadTodaySlotsV3 === 'function') loadTodaySlotsV3();
                        } else {
                            showNotificationV2(result.message, 'error');
                        }
                    })
                    .catch(function (err) {
                        showNotificationV2('Ralat sambungan', 'error');
                    });
            }
        });
    }
</script>