<?php
// Schedule Tab Component
// Located at: components/teacher/tab-schedule.php
?>
<div id="schedule" class="tab-content">
    <div class="card"
        style="margin-bottom: 25px; border-radius: 20px; overflow: hidden; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); animation: fadeInDown 0.6s ease-out;">
        <div style="height: 6px; background: linear-gradient(90deg, var(--primary-color) 0%, #764ba2 100%);"></div>
        <div class="card-body" style="padding: 25px;">
            <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
                <div
                    style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); width: 60px; height: 60px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; box-shadow: 0 8px 16px rgba(102, 126, 234, 0.25); color: white;">
                    📅
                </div>
                <div style="flex: 1; min-width: 200px;">
                    <h4 style="margin: 0 0 5px 0; color: #1a1a2e; font-size: 1.4rem; font-weight: 800;">Jadual Mengajar
                    </h4>
                    <p style="margin: 0; color: #6b7280; font-size: 0.95rem; line-height: 1.5;">Urus jadual kelas, sesi
                        mengajar, dan aktiviti anda.</p>
                </div>
                <div class="d-none d-md-block">
                    <div
                        style="background: rgba(102, 126, 234, 0.05); padding: 10px 20px; border-radius: 12px; border: 1px dashed rgba(102, 126, 234, 0.3);">
                        <span style="color: var(--primary-color); font-weight: 600; font-size: 0.85rem;">Sesi Hari Ini:
                            <span id="scheduleTodayCount">-</span> ⏳</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card"
        style="border-radius: 20px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.05); overflow: hidden; animation: fadeInUp 0.6s ease-out 0.2s both;">
        <div class="card-header bg-white"
            style="padding: 20px 25px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <div
                    style="background: #f0f4ff; width: 35px; height: 35px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: var(--primary-color);">
                    <i class="fas fa-calendar-alt"></i>
                </div>
                <h3 class="card-title" style="margin: 0; font-size: 1.15rem; font-weight: 700; color: #1a1a2e;">Jadual
                    Waktu</h3>
            </div>
            <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
                <div class="btn-group shadow-sm" style="border-radius: 50px; overflow: hidden;">
                    <button class="btn btn-outline-primary btn-sm active" id="viewListBtn"
                        onclick="changeScheduleViewV3('list')" style="border-radius: 0;">Senarai</button>
                    <button class="btn btn-outline-primary btn-sm" id="viewCalendarBtn"
                        onclick="changeScheduleViewV3('calendar')" style="border-radius: 0;">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; border-radius: 20px; padding-left: 15px;">
                <?php endif; ?>
                <button class="btn btn-primary btn-sm rounded-pill px-4 py-2 shadow-sm d-flex align-items-center gap-2"
                    onclick="showAddScheduleModalV3()"
                    style="background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%); border: none; font-weight: 600; transition: transform 0.2s;">
                    <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>