<?php
/**
 * Mobile Detection Helper
 * Checks User-Agent for mobile/tablet browsers.
 * Returns true if the current visitor is on a mobile device.
 */
function isMobileDevice(): bool
{
    $ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');

    $mobileKeywords = [
        'android','iphone','ipad','ipod','blackberry','windows phone',
        'mobile','opera mini','opera mobi','kindle','silk','webos',
        'fennec','minimo','bolt','teashark','blazer','palm',
    ];

    foreach ($mobileKeywords as $kw) {
        if (strpos($ua, $kw) !== false) {
            return true;
        }
    }
    return false;
}

/**
 * Redirect to mobile app if on a mobile device.
 * Call after login or on any desktop page load.
 */
function redirectMobileIfNeeded(): void
{
    // Allow override: ?desktop=1 forces desktop view
    if (isset($_GET['desktop']) || ($_SESSION['force_desktop'] ?? false)) {
        $_SESSION['force_desktop'] = true;
        return;
    }
    // Allow override: ?mobile=1 forces mobile view
    if (isset($_GET['mobile'])) {
        $_SESSION['force_desktop'] = false;
    }

    if (isMobileDevice() && !($_SESSION['force_desktop'] ?? false)) {
        header('Location: ' . BASE_URL . '/mobile/index.php');
        exit;
    }
}

/**
 * Redirect to desktop if on a desktop browser (from mobile pages).
 */
function redirectDesktopIfNeeded(): void
{
    if (!isMobileDevice() && !isset($_GET['mobile'])) {
        header('Location: ' . BASE_URL . '/dashboard.php');
        exit;
    }
}
