<?php
// helper/DeviceHelper.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!function_exists('getDeviceType')) {
    function getDeviceType() {
        if (isset($_SESSION['device_type'])) {
            return $_SESSION['device_type'];
        }
        
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $mobileDevices = ['Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
                          'Opera Mini', 'IEMobile', 'Mobile', 'Windows Phone'];
        
        foreach ($mobileDevices as $device) {
            if (stripos($ua, $device) !== false) {
                $_SESSION['device_type'] = 'mobile';
                return 'mobile';
            }
        }
        
        $_SESSION['device_type'] = 'desktop';
        return 'desktop';
    }
}

if (!function_exists('getDeviceParam')) {
    function getDeviceParam() {
        return getDeviceType() === 'mobile' ? 'mobile_access' : 'desktop_access';
    }
}

if (!function_exists('isMobileDevice')) {
    function isMobileDevice() {
        return getDeviceType() === 'mobile';
    }
}

if (!function_exists('isDesktopDevice')) {
    function isDesktopDevice() {
        return getDeviceType() === 'desktop';
    }
}

if (!function_exists('generateRandomText')) {
    function generateRandomText($length = 40) {
        return bin2hex(random_bytes($length / 2));
    }
}

if (!function_exists('redirectWithDeviceParam')) {
    function redirectWithDeviceParam($page, $params = []) {
        $deviceParam = getDeviceParam();
        $hash = generateRandomText(40);
        $params[$deviceParam] = $hash;
        $queryString = http_build_query($params);
        header("Location: ?auth_max_open={$page}&{$queryString}");
        exit;
    }
}

if (!function_exists('getFormAction')) {
    function getFormAction($action) {
        $deviceParam = getDeviceParam();
        $hash = generateRandomText(20);
        return "?action={$action}&{$deviceParam}={$hash}";
    }
}
?>