<?php
/**
 * Deteksi perangkat: mobile atau PC.
 * Digunakan untuk memilih view dari views/mobile/ atau views/pc/
 */

if (!function_exists('is_mobile_device')) {
    function is_mobile_device() {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $ua = strtolower($ua);
        if (empty($ua)) {
            return false;
        }
        $mobileKeywords = [
            'mobile', 'android', 'iphone', 'ipod', 'ipad', 'webos', 'blackberry',
            'windows phone', 'iemobile', 'opera mini', 'opera mobi', 'fennec',
            'maemo', 'kindle', 'silk', 'uc browser', 'mobile safari', 'miuibrowser',
            'samsungbrowser', 'crios', 'fxios', 'edgios', 'touch', 'tablet',
        ];
        foreach ($mobileKeywords as $kw) {
            if (strpos($ua, $kw) !== false) {
                return true;
            }
        }
        return false;
    }
}

if (!function_exists('get_device_theme')) {
    function get_device_theme() {
        if (isset($_GET['theme']) && in_array($_GET['theme'], ['mobile', 'pc'], true)) {
            if (session_status() === PHP_SESSION_NONE) {
                @session_start();
            }
            $_SESSION['force_theme'] = $_GET['theme'];
            return $_GET['theme'];
        }
        if (!empty($_SESSION['force_theme']) && in_array($_SESSION['force_theme'], ['mobile', 'pc'], true)) {
            return $_SESSION['force_theme'];
        }
        return is_mobile_device() ? 'mobile' : 'pc';
    }
}

if (!isset($GLOBALS['__device'])) {
    $GLOBALS['__device'] = get_device_theme();
    $GLOBALS['__is_mobile'] = ($GLOBALS['__device'] === 'mobile');
}
$__device = $GLOBALS['__device'];
$__is_mobile = $GLOBALS['__is_mobile'];

if (!function_exists('get_device_view_path')) {
    /**
     * Ambil path view berdasarkan device (mobile/pc).
     * Cek views/{device}/{page}.php dulu, fallback ke views/{page}.php
     */
    function get_device_view_path($page) {
        $page = ltrim($page, '/');
        $device = $GLOBALS['__device'] ?? 'pc';
        $deviceView = '/' . $device . '/' . $page;
        $fallbackView = '/' . $page;
        $viewsPath = defined('VIEWS_PATH') ? VIEWS_PATH : (dirname(__DIR__) . '/views');
        if (file_exists($viewsPath . $deviceView)) {
            return $deviceView;
        }
        return $fallbackView;
    }
}
