<?php
include 'config.php';

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

if (!isset($_SESSION['user_category'])) {
    $username = $_SESSION['username'];
    $stmt = $conn->prepare("SELECT user_category FROM user WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $result->num_rows > 0) {
        $userRow = $result->fetch_assoc();
        $_SESSION['user_category'] = $userRow['user_category'] ?: 'Normal';
    } else {
        $_SESSION['user_category'] = 'Normal';
    }
}

function isAdmin() {
    return isset($_SESSION['user_category']) && $_SESSION['user_category'] === 'Admin';
}

function isNormalUser() {
    return isset($_SESSION['user_category']) && $_SESSION['user_category'] === 'Normal';
}

function canAccessCreditSale() {
    return isAdmin() || isNormalUser();
}

function requireCreditSaleAccess($redirect = 'credit_sale.php') {
    if (!canAccessCreditSale()) {
        header("Location: " . $redirect);
        exit();
    }
}

function requireAdminAccess($redirect = 'sale.php') {
    if (!isAdmin()) {
        header("Location: " . $redirect);
        exit();
    }
}

function renderSidebar($currentPage = '') {
    $isAdminUser = isAdmin();
    $isNormal = isNormalUser();
    ?>
    <aside class="sidebar">
        <div style="text-align:center; margin-bottom:12px;">
            <img src="logo/logo_circle_1.png" alt="Krushi Sewa Piyasa Logo" style="width:80px; height:80px; object-fit:contain; display:block; margin:0 auto 2px auto;">
            <h2 style="margin-bottom:0;">Krushi Sewa Piyasa</h2>
        </div>

        <?php if ($isAdminUser) { ?>
            <a href="dashboard.php" <?php echo $currentPage === 'dashboard' ? 'class="active-menu"' : ''; ?>>Dashboard</a>
            <a href="sale.php" <?php echo $currentPage === 'sale' ? 'class="active-menu"' : ''; ?>>Sale</a>
            <a href="bill_return.php" <?php echo $currentPage === 'bill_return' ? 'class="active-menu"' : ''; ?>>Bill Return</a>
            <a href="daily_purchasing.php" <?php echo $currentPage === 'daily_purchasing' ? 'class="active-menu"' : ''; ?>>Inventory</a>
            <a href="stock.php" <?php echo $currentPage === 'stock' ? 'class="active-menu"' : ''; ?>>Stock</a>
            <a href="bill_search.php" <?php echo $currentPage === 'bill_search' ? 'class="active-menu"' : ''; ?>>Bill Search</a>
            <a href="suppliers.php" <?php echo $currentPage === 'suppliers' ? 'class="active-menu"' : ''; ?>>Suppliers</a>
            <a href="credit_sale.php" <?php echo $currentPage === 'credit_sale' ? 'class="active-menu"' : ''; ?>>Credit-Sale</a>
            <a href="credit_purchases.php" <?php echo $currentPage === 'credit_purchases' ? 'class="active-menu"' : ''; ?>>Credit-Purchases</a>
        <?php } elseif ($isNormal) { ?>
            <a href="sale.php" <?php echo $currentPage === 'sale' ? 'class="active-menu"' : ''; ?>>Sale</a>
            <a href="bill_return.php" <?php echo $currentPage === 'bill_return' ? 'class="active-menu"' : ''; ?>>Bill Return</a>
            <a href="credit_sale.php" <?php echo $currentPage === 'credit_sale' ? 'class="active-menu"' : ''; ?>>Credit-Sale</a>
        <?php } ?>

        <a href="logout.php">Logout</a>
    </aside>

    <div id="systemToast" class="system-toast" aria-live="polite"></div>
    <script>
    (function () {
        if (window.__kspToastInitialized) return;
        window.__kspToastInitialized = true;

        const toast = document.getElementById('systemToast');
        let toastTimer = null;

        window.showSystemToast = function (message, type = 'error', duration = 4200) {
            if (!toast || !message) return;
            toast.className = 'system-toast show ' + type;
            toast.textContent = message;

            if (toastTimer) clearTimeout(toastTimer);
            toastTimer = setTimeout(function () {
                toast.classList.remove('show');
            }, duration);
        };

        window.hideSystemToast = function () {
            if (!toast) return;
            toast.classList.remove('show');
        };

        window.addEventListener('offline', function () {
            window.showSystemToast('Network issue detected. Please check the connection.');
        });

        window.addEventListener('online', function () {
            window.showSystemToast('Connection restored.', 'success', 2200);
        });

        const originalFetch = window.fetch;
        if (originalFetch) {
            window.fetch = function () {
                return originalFetch.apply(this, arguments).then(function (response) {
                    if (!response.ok) {
                        if (response.status === 503) {
                            window.showSystemToast('Server busy or temporarily unavailable. Please try again.');
                        } else if (response.status >= 500) {
                            window.showSystemToast('Server error detected. Please retry the action.');
                        }
                    }
                    return response;
                }).catch(function (error) {
                    window.showSystemToast('Connection issue. Action could not be completed.');
                    throw error;
                });
            };
        }

        window.addEventListener('error', function () {
            window.showSystemToast('Unexpected issue detected. Please refresh and continue.');
        });

        window.addEventListener('unhandledrejection', function () {
            window.showSystemToast('Request failed. Please try again.');
        });
    })();
    </script>
    <?php
}
?>