/**
 * Main JavaScript - TutorKita System
 */

// Global Variables
let currentUser = null;
let notifications = [];
let isLoading = false;

// DOM Ready
document.addEventListener('DOMContentLoaded', function () {
    initializeApp();
});

function initializeApp() {
    checkSession();
    initializeTooltips();
    initializeDropdowns();
    initializeMobileMenu();
    setInterval(fetchNotifications, 10000);
}

// Session Management
async function checkSession() {
    try {
        var response = await fetch('../api.php?action=check_session');
        var result = await response.json();

        if (result.success && result.logged_in) {
            currentUser = result.user;
            updateUIForUser();
        } else {
            redirectToLogin();
        }
    } catch (error) {
        console.error('Session check failed:', error);
    }
}

function redirectToLogin() {
    window.location.href = '../index.php';
}

function updateUIForUser() {
    var greetingElement = document.getElementById('userGreeting');
    if (greetingElement && currentUser) {
        var name = currentUser.profile_name || currentUser.full_name || currentUser.username;
        greetingElement.textContent = 'Selamat sejahtera, ' + name + '!';
    }

    var emojiElement = document.getElementById('profileEmoji');
    if (emojiElement && currentUser.profile_emoji) {
        emojiElement.textContent = currentUser.profile_emoji;
    }
}

// Logout
async function logout() {
    try {
        var response = await fetch('../api.php?action=logout');
        var result = await response.json();

        if (result.success) {
            showNotification('Berjaya log keluar', 'success');
            setTimeout(function () {
                window.location.href = '../index.php';
            }, 1000);
        }
    } catch (error) {
        showNotification('Ralat semasa log keluar', 'error');
    }
}

// Notification System
async function fetchNotifications() {
    try {
        var response = await fetch('../api.php?action=get_notifications');
        var result = await response.json();

        if (result.success) {
            notifications = result.notifications;
            updateNotificationBadge();
        }
    } catch (error) {
        console.error('Failed to fetch notifications:', error);
    }
}

function updateNotificationBadge() {
    var badge = document.getElementById('notificationBadge');
    if (badge) {
        var unreadCount = 0;
        for (var i = 0; i < notifications.length; i++) {
            if (notifications[i].is_read === 'No') {
                unreadCount++;
            }
        }
        if (unreadCount > 0) {
            badge.textContent = unreadCount;
            badge.style.display = 'flex';
        } else {
            badge.style.display = 'none';
        }
    }
}

function showNotification(message, type, duration) {
    type = type || 'info';
    duration = duration || 5000;

    var container = document.getElementById('notificationContainer');
    if (!container) {
        container = document.createElement('div');
        container.id = 'notificationContainer';
        container.className = 'notification-panel';
        document.body.appendChild(container);
    }

    var notification = document.createElement('div');
    notification.className = 'notification-toast ' + type;

    var icons = {
        success: '✅',
        error: '❌',
        warning: '⚠️',
        info: 'ℹ️'
    };

    notification.innerHTML = '<span class="notification-icon">' + icons[type] + '</span>' +
        '<div class="notification-content" style="flex: 1;"><p>' + message + '</p></div>' +
        '<button class="notification-close" onclick="this.parentElement.remove()">×</button>';

    container.appendChild(notification);

    setTimeout(function () {
        notification.style.animation = 'slideInRight 0.3s ease reverse';
        setTimeout(function () {
            notification.remove();
        }, 300);
    }, duration);
}

// Tab Navigation
function switchTab(tabId) {
    var tabs = document.querySelectorAll('.tab-content');
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active');
    }

    var buttons = document.querySelectorAll('.tab-btn');
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].classList.remove('active');
    }

    var selectedTab = document.getElementById(tabId);
    if (selectedTab) {
        selectedTab.classList.add('active');
    }

    var tabBtn = document.querySelector('[data-tab="' + tabId + '"]');
    if (tabBtn) {
        tabBtn.classList.add('active');
    }
}

// Modal Management
function openModal(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        // Universal Kill Switch: Move modal to body to break out of any stacking context traps
        if (modal.parentNode !== document.body) {
            document.body.appendChild(modal);
        }

        // FORCE RESET DISPLAY PROPERTY (The Fix for auto-hidden modals)
        modal.style.display = '';
        modal.style.removeProperty('display');

        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    var modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

function closeAllModals() {
    var modals = document.querySelectorAll('.modal-overlay');
    for (var i = 0; i < modals.length; i++) {
        modals[i].classList.remove('active');
    }
    document.body.style.overflow = '';
}

// Close modal when clicking overlay
document.addEventListener('click', function (e) {
    if (e.target.classList.contains('modal-overlay')) {
        closeAllModals();
    }
});

// Close modal with ESC key
document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
        closeAllModals();
    }
});

// Form Handling
async function submitForm(formId, url) {
    var form = document.getElementById(formId);
    if (!form) return;

    var formData = new FormData(form);
    var submitBtn = form.querySelector('button[type="submit"]');

    if (submitBtn) {
        var originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="loading-spinner" style="width:20px;height:20px;border-width:2px;"></span> Sedang Memproses...';

        try {
            var response = await fetch(url, {
                method: 'POST',
                body: formData
            });

            var result = await response.json();

            if (result.success) {
                showNotification(result.message, 'success');
                closeAllModals();
                if (typeof refreshData === 'function') {
                    refreshData();
                }
            } else {
                showNotification(result.message, 'error');
            }
        } catch (error) {
            showNotification('Ralat sambungan. Sila cuba lagi.', 'error');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    }
}

// Dynamic Grade Level Dropdown
function updateGradeLevelDropdown() {
    var educationLevel = document.getElementById('educationLevel');
    var gradeLevel = document.getElementById('gradeLevel');

    if (!educationLevel || !gradeLevel) return;

    var level = educationLevel.value;
    var options = '<option value="">Pilih Tahun/Tingkat</option>';

    if (level === 'Sekolah Rendah') {
        for (var i = 1; i <= 6; i++) {
            options += '<option value="Tahun ' + i + '">Tahun ' + i + '</option>';
        }
    } else if (level === 'Sekolah Menengah') {
        for (var i = 1; i <= 5; i++) {
            options += '<option value="Ting ' + i + '">Ting ' + i + '</option>';
        }
    }

    gradeLevel.innerHTML = options;
}

// Subject Checklist
function initializeSubjectChecklist() {
    var checkboxes = document.querySelectorAll('.subject-checklist .form-check-input');

    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].addEventListener('change', function () {
            var parent = this.closest('.form-check');
            var otherInput = parent.querySelector('.other-subject-input');

            if (this.checked && this.classList.contains('show-other')) {
                if (otherInput) {
                    otherInput.style.display = 'block';
                    otherInput.required = true;
                }
            } else if (!this.checked && this.classList.contains('show-other')) {
                if (otherInput) {
                    otherInput.style.display = 'none';
                    otherInput.required = false;
                    otherInput.value = '';
                }
            }

            validateSubjectSelection();
        });
    }
}

function validateSubjectSelection() {
    var checkboxes = document.querySelectorAll('.subject-checklist .form-check-input:not(.show-other)');
    var submitBtn = document.querySelector('.subject-checklist .btn[type="submit"]');
    var errorMsg = document.getElementById('subjectError');

    var isChecked = false;
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked) {
            isChecked = true;
            break;
        }
    }

    if (submitBtn) {
        submitBtn.disabled = !isChecked;
    }

    if (errorMsg) {
        errorMsg.style.display = isChecked ? 'none' : 'block';
    }
}

// Emoji Picker
function initializeEmojiPicker() {
    var pickers = document.querySelectorAll('.emoji-picker');

    pickers.forEach(function (picker) {
        picker.addEventListener('click', function (e) {
            if (e.target.classList.contains('emoji-option')) {
                var options = this.querySelectorAll('.emoji-option');
                for (var i = 0; i < options.length; i++) {
                    options[i].classList.remove('selected');
                }

                e.target.classList.add('selected');

                // Try to find the input in the same form or container
                var input = document.getElementById('selectedEmoji');
                if (!input && this.closest('form')) {
                    input = this.closest('form').querySelector('input[name="profile_emoji"]');
                }

                if (input) {
                    input.value = e.target.textContent.trim() || e.target.getAttribute('data-emoji');
                }
            }
        });
    });
}

// Mobile Menu
function initializeMobileMenu() {
    var menuToggle = document.getElementById('mobileMenuToggle');
    var sidebar = document.querySelector('.sidebar');

    if (menuToggle && sidebar) {
        menuToggle.addEventListener('click', function () {
            sidebar.classList.toggle('open');
        });
    }

    document.addEventListener('click', function (e) {
        if (sidebar && window.innerWidth <= 1024) {
            // Only proceed if sidebar exists and we're on mobile
            // and if menuToggle exists, check if click was outside both
            if (menuToggle) {
                if (!sidebar.contains(e.target) && !menuToggle.contains(e.target)) {
                    sidebar.classList.remove('open');
                }
            } else {
                // If no menuToggle, still close sidebar if clicking outside
                if (!sidebar.contains(e.target)) {
                    sidebar.classList.remove('open');
                }
            }
        }
    });
}

// UI Utilities
function initializeTooltips() {
    var tooltips = document.querySelectorAll('[data-tooltip]');

    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].addEventListener('mouseenter', function () {
            var tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = this.dataset.tooltip;
            tooltip.style.cssText = 'position:absolute;background:#333;color:white;padding:5px 10px;border-radius:4px;font-size:12px;z-index:10000;pointer-events:none;';
            document.body.appendChild(tooltip);

            var rect = this.getBoundingClientRect();
            tooltip.style.top = (rect.top - 30) + 'px';
            tooltip.style.left = (rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2)) + 'px';

            this._tooltip = tooltip;
        });

        tooltips[i].addEventListener('mouseleave', function () {
            if (this._tooltip) {
                this._tooltip.remove();
            }
        });
    }
}

function initializeDropdowns() {
    var dropdowns = document.querySelectorAll('.dropdown');

    for (var i = 0; i < dropdowns.length; i++) {
        var toggle = dropdowns[i].querySelector('.dropdown-toggle');
        var menu = dropdowns[i].querySelector('.dropdown-menu');

        if (toggle && menu) {
            toggle.addEventListener('click', function (e) {
                e.stopPropagation();
                menu.classList.toggle('show');
            });
        }
    }

    document.addEventListener('click', function () {
        var menus = document.querySelectorAll('.dropdown-menu.show');
        for (var i = 0; i < menus.length; i++) {
            menus[i].classList.remove('show');
        }
    });
}

// Export Functions
function exportToCSV(tableId, filename) {
    var table = document.getElementById(tableId);
    if (!table) return;

    var csv = [];
    var rows = table.querySelectorAll('tr');

    for (var i = 0; i < rows.length; i++) {
        var cols = rows[i].querySelectorAll('td, th');
        var rowData = [];
        for (var j = 0; j < cols.length; j++) {
            rowData.push('"' + cols[j].textContent.trim() + '"');
        }
        csv.push(rowData.join(','));
    }

    var csvFile = new Blob([csv.join('\n')], { type: 'text/csv' });
    var downloadLink = document.createElement('a');
    downloadLink.download = filename + '.csv';
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = 'none';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

function printPage() {
    window.print();
}

// Date Formatting
function formatDate(dateString) {
    var options = { year: 'numeric', month: 'long', day: 'numeric' };
    return new Date(dateString).toLocaleDateString('ms-MY', options);
}

function formatDateTime(dateString) {
    var options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
    return new Date(dateString).toLocaleDateString('ms-MY', options);
}

// Validation Helpers
function isValidPhone(phone) {
    return /^[\d\-\+\s]{10,15}$/.test(phone);
}

function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function isValidAge(age) {
    return age >= 5 && age <= 25;
}

// Confirm Dialog
function confirmAction(message, onConfirm) {
    if (confirm(message)) {
        onConfirm();
    }
}

// Loading States
function setLoading(isLoadingState, elementId) {
    var element = document.getElementById(elementId);
    if (!element) return;

    if (isLoadingState) {
        element.dataset.originalContent = element.innerHTML;
        element.innerHTML = '<div class="loading-spinner"></div>';
        element.disabled = true;
    } else {
        if (element.dataset.originalContent) {
            element.innerHTML = element.dataset.originalContent;
            delete element.dataset.originalContent;
        }
        element.disabled = false;
    }
}

// URL Parameters
function getUrlParameter(name) {
    var params = new URLSearchParams(window.location.search);
    return params.get(name);
}

// Utility: Animate number CountUp effect
function animateValue(id, start, end, duration) {
    var obj = document.getElementById(id);
    if (!obj) return;
    var range = end - start;
    if (range === 0) return;
    var current = start;
    var increment = end > start ? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    stepTime = Math.max(stepTime, 10);

    var timer = setInterval(function () {
        current += increment;
        obj.textContent = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}

// Make functions globally available
window.logout = logout;
window.showNotification = showNotification;
window.switchTab = switchTab;
window.openModal = openModal;
window.closeModal = closeModal;
window.closeAllModals = closeAllModals;
window.submitForm = submitForm;
window.updateGradeLevelDropdown = updateGradeLevelDropdown;
window.initializeSubjectChecklist = initializeSubjectChecklist;
window.initializeEmojiPicker = initializeEmojiPicker;
window.exportToCSV = exportToCSV;
window.printPage = printPage;
window.confirmAction = confirmAction;
window.formatDate = formatDate;
window.formatDateTime = formatDateTime;
window.animateValue = animateValue;

