// assets/js/app.js

async function checkAuth(requiredRole = null) {
    // --- INSTALLATION CHECK ---
    const currentPage = window.location.pathname.split('/').pop().replace('.html', '');
    if (currentPage !== 'install') {
        const installRes = await fetch('api/auth.php?action=check_install');
        const installData = await installRes.json();
        if (!installData.installed) {
            window.location.href = 'install';
            return null;
        }
    }
    // -------------------------

    try {
        const response = await fetch('api/auth.php?action=me');
        const data = await response.json();

        if (!data.success) {
            window.location.href = 'login';
            return null;
        }

        // --- MOBILE REDIRECT GATEKEEPER ---
        const isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        if (isMobileDevice) {
            let currentPage = window.location.pathname.split('/').pop().replace('.html', '');
            if (!currentPage || currentPage === '' || currentPage === 'admin' || currentPage === 'index') {
                if (data.user.role === 'Admin' || data.user.role === 'Accounts') {
                    window.location.href = 'mobile-admin.html';
                } else {
                    window.location.href = 'mobile-pos.html';
                }
                return null;
            } else if (currentPage === 'pos') {
                window.location.href = 'mobile-pos.html';
                return null;
            } else {
                // Not admin, pos or index. Let them view the page, but transform the navbar to Mobile style!
                const topNav = document.querySelector('.top-main-nav');
                if (topNav) topNav.style.display = 'none'; // Hide desktop nav
                
                // Add mobile css
                if (!document.querySelector('link[href*="mobile-admin.css"]')) {
                    const l = document.createElement('link');
                    l.rel = 'stylesheet';
                    l.href = 'assets/css/mobile-admin.css';
                    document.head.appendChild(l);
                }

                // Inject mobile bottom nav
                if (!document.querySelector('.mobile-bottom-nav')) {
                    const mNav = document.createElement('nav');
                    mNav.className = 'mobile-bottom-nav';
                    mNav.innerHTML = `
                        <button class="nav-item" onclick="window.location.href='mobile-admin.html'">
                            <i class="fa-solid fa-house"></i><span>Home</span>
                        </button>
                        <button class="nav-item ${currentPage.includes('inventory') ? 'active' : ''}" onclick="window.location.href='inventory.html'">
                            <i class="fa-solid fa-boxes-stacked"></i><span>Items</span>
                        </button>
                        <button class="nav-fab" onclick="window.location.href='mobile-pos.html'">
                            <i class="fa-solid fa-cart-shopping"></i>
                        </button>
                        <button class="nav-item ${currentPage.includes('report') ? 'active' : ''}" onclick="window.location.href='reports.html'">
                            <i class="fa-solid fa-chart-pie"></i><span>Reports</span>
                        </button>
                        <button class="nav-item" onclick="window.location.href='mobile-admin.html'">
                            <i class="fa-solid fa-bars"></i><span>More</span>
                        </button>
                    `;
                    document.body.appendChild(mNav);
                }
            }
        }
        // ----------------------------------


        // --- LICENSING GATEKEEPER ---
        // Verify license is active for this installation
        const licenseRes = await fetch('api/activate.php?action=check');
        const licenseData = await licenseRes.json();
        
        let currentPage = window.location.pathname.split('/').pop().replace('.html', '');
        if (!currentPage || currentPage === '') currentPage = 'admin'; // Default fallback
        
        if (!licenseData.isLicensed && currentPage !== 'activate') {
            window.location.href = 'activate';
            return null;
        }
        // -----------------------------
        
        // --- DATABASE VERSION CHECK ---
        if (data.system_version && data.db_version && data.system_version !== data.db_version) {
            let currentPage = window.location.pathname.split('/').pop().replace('.html', '');
            if (data.user.role === 'Admin' && currentPage !== 'finish_update') {
                window.location.href = 'finish_update.php';
                return null;
            }
        }

        // Cashier restriction - Prioritize over general auth check
        const isCashier = data.user.role === 'Cashier';
        const currentPath = window.location.pathname;
        
        if (isCashier) {
            // Only allow pos, profile, and index (login)
            const allowedPages = ['pos', 'profile', 'index', 'login', ''];
            if (!allowedPages.includes(currentPage)) {
                window.location.href = 'pos';
                return null;
            }

            // Load System Settings (Logo & Company Name)
            fetch('api/settings.php?action=get').then(r => r.json()).then(data => {
                if (data.success && data.data) {
                    const s = data.data;
                    const companyName = s.company_name || 'JUSTSALE POS';
                    const el = document.getElementById('licensedToName');
                    if (el) el.innerText = companyName;

                    if (s.company_logo) {
                        const logoImg = document.getElementById('loginLogo');
                        if (logoImg) {
                            logoImg.src = s.company_logo;
                            logoImg.classList.remove('d-none');
                            const brandText = document.getElementById('loginBrandText');
                            if (brandText) brandText.classList.add('d-none');
                        }
                    }
                }
            });
            // Hide restricted navigation elements for cashiers
            document.querySelectorAll('.nav-link').forEach(link => {
                const href = link.getAttribute('href');
                if (href && href !== 'pos' && !link.classList.contains('dropdown-toggle')) {
                    link.style.display = 'none';
                }
            });
            document.querySelectorAll('.nav-link-dropdown').forEach(dropdown => {
                dropdown.style.display = 'none';
            });
        }

        // Authorization check
        if (requiredRole && data.user.role !== requiredRole && data.user.role !== 'Admin') {
            Swal.fire('Unauthorized', 'You do not have permission to view this page.', 'error')
                .then(() => window.location.href = 'login');
            return null;
        }

        // Display user context
        const userDisplay = document.getElementById('current-user');
        if (userDisplay) {
            const firstName = data.user.fullname ? data.user.fullname.split(' ')[0] : data.user.username;
            const photoUrl = data.user.photo ? data.user.photo : 'https://ui-avatars.com/api/?name=' + (data.user.fullname || data.user.username) + '&background=random';

            // Hide settings if cashier
            const settingsItem = isCashier ? '' : `<li><a class="dropdown-item py-2" href="settings"><i class="fa-solid fa-gear me-3 text-muted"></i>Settings</a></li>`;

            const isOnPos = currentPage.includes('pos');
            const posShortcut = !isOnPos ? `
                <a href="pos" target="_blank" class="nav-icon-link me-2" title="Point of Sale">
                    <i class="fa-solid fa-cart-shopping"></i>
                </a>` : '';

            userDisplay.innerHTML = `
                ${posShortcut}
                <div class="dropdown">
                    <div class="d-flex align-items-center gap-2 cursor-pointer dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" style="cursor: pointer;">
                        <img src="${photoUrl}" class="rounded-circle border border-2 border-white shadow-sm" width="32" height="32" style="object-fit: cover;">
                        <div class="text-white d-none d-md-block">
                            <div class="fw-bold lh-1 small text-start">${firstName}</div>
                            <div class="text-white-50 lh-1" style="font-size: 0.65rem;">${data.user.role}</div>
                        </div>
                    </div>
                    <ul class="dropdown-menu dropdown-menu-end shadow-lg border-0 mt-2 rounded-3 overflow-hidden">
                        <li class="px-3 py-2 bg-light border-bottom d-md-none">
                            <div class="fw-bold small">${data.user.fullname || data.user.username}</div>
                            <div class="text-muted small">${data.user.role}</div>
                        </li>
                        <li><a class="dropdown-item py-2" href="profile"><i class="fa-solid fa-user-circle me-3 text-muted"></i>My Profile</a></li>
                        ${settingsItem}
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item py-2 text-danger" href="#" onclick="logout()"><i class="fa-solid fa-sign-out-alt me-3"></i>Logout</a></li>
                    </ul>
                </div>
            `;
        }

        // Update version tag if exists
        const versionTag = document.querySelector('.version-tag');
        if (versionTag && data.system_version) {
            versionTag.innerText = 'Ver: ' + data.system_version;
        }

        // --- AUTOMATIC UPDATE CHECKER ---
        // Only run check if we haven't checked in the last 24 hours
        const lastCheck = localStorage.getItem('justsale_last_update_check');
        const now = Date.now();
        const oneDay = 24 * 60 * 60 * 1000;
        
        if (!lastCheck || (now - lastCheck > oneDay)) {
            checkUpdate();
        }
        // ---------------------------------

        window.currentUser = data.user;
        return data.user;
    } catch (e) {
        window.location.href = 'login';
    }
}

async function logout() {
    await fetch('api/auth.php?action=logout');
    window.location.href = 'login';
}

async function getAppSettings() {
    try {
        const response = await fetch('api/settings.php?action=get');
        const data = await response.json();
        if (data.success) {
            return data.data;
        }
    } catch (e) {
        console.error('Failed to fetch settings', e);
    }
    return null;
}

function showToast(message, icon = 'success') {
    const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
    });
    Toast.fire({
        icon: icon,
        title: message
    });
}

function formatCurrency(amount) {
    if (isNaN(amount) || amount === null) return '0';
    return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    }).format(amount);
}

// Inter-tab communication for real-time updates
const syncChannel = new BroadcastChannel('justsale_inventory_sync');

function notifyInventoryChange() {
    syncChannel.postMessage({ type: 'INVENTORY_CHANGED', timestamp: Date.now() });
}

async function checkUpdate() {
    try {
        const response = await fetch('api/update_checker.php?action=check');
        const data = await response.json();
        
        localStorage.setItem('justsale_last_update_check', Date.now());
        
        if (data.success && data.has_update) {
            showUpdateToast(data.latest_version, data.changelog);
        }
    } catch (e) {
        console.error('Update check failed', e);
    }
}

function showUpdateToast(version, changelog = '') {
    // Remove existing if any
    const existing = document.getElementById('updateToast');
    if (existing) existing.remove();

    const toastHTML = `
        <div id="updateToast" class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1100;">
            <div class="toast show animate__animated animate__fadeInUp" role="alert" aria-live="assertive" aria-atomic="true" style="border-radius: 12px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.2); background: white; width: 350px;">
                <div class="toast-header border-0 bg-transparent pt-3 px-3">
                    <div class="rounded-circle bg-primary bg-opacity-10 p-2 me-2 d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                        <i class="fa-solid fa-cloud-arrow-up text-primary small"></i>
                    </div>
                    <strong class="me-auto text-dark">Software Update</strong>
                    <small class="text-muted">v${version}</small>
                    <button type="button" class="btn-close" onclick="closeUpdateToast()" aria-label="Close"></button>
                </div>
                <div class="toast-body px-3 pb-3">
                    <div class="update-content mb-3 p-2 bg-light rounded-3" style="max-height: 200px; overflow-y: auto; font-size: 0.8rem; border: 1px solid #eee;">
                        ${changelog || 'A newer version of JUSTSALE is available.'}
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-primary btn-sm flex-fill fw-bold py-2 shadow-sm" onclick="redirectToSettingsUpdate()" style="border-radius: 8px;">
                            <i class="fa-solid fa-download me-1"></i> Get v${version}
                        </button>
                        <button class="btn btn-success btn-sm flex-fill fw-bold py-2 shadow-sm" onclick="showMigrationModal()" style="border-radius: 8px;">
                            <i class="fa-solid fa-sync me-1"></i> Finish Update
                        </button>
                        <button class="btn btn-light btn-sm fw-bold py-2 border px-3" onclick="closeUpdateToast()" style="border-radius: 8px;">
                            <i class="fa-solid fa-times"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', toastHTML);
}

function showMigrationModal() {
    window.location.href = 'finish_update.php';
}


function redirectToSettingsUpdate() {
    window.location.href = 'settings.html#v-pills-updates';
}

function closeUpdateToast() {
    const toast = document.getElementById('updateToast');
    if (toast) {
        toast.classList.add('animate__fadeOutDown');
        setTimeout(() => toast.remove(), 500);
    }
}



