<?php

namespace LoftyIDX\includes;

defined('ABSPATH') || exit;

class LoftyIDXHelpers
{
    public static function get_page_id($page)
    {
        $page = apply_filters('lofty_idx_get_' . $page . '_page_id', get_option('lofty_idx_' . $page . '_page_id'));

        return $page ? absint($page) : -1;
    }

    public static function get_current_url()
    {
        // 构建当前页面的完整URL
        $REQUEST_URI = isset($_SERVER['REQUEST_URI']) ? sanitize_url(wp_unslash($_SERVER['REQUEST_URI'])) : "";
        if (strlen(LOFTY_API_REFERRER) > 0) {
            return LOFTY_API_REFERRER . $REQUEST_URI;
        }
        // 检查 HTTP_REFERER 是否来自同一域名
        $HTTP_REFERER = isset($_SERVER['HTTP_REFERER']) ? sanitize_url(wp_unslash($_SERVER['HTTP_REFERER'])) : "";
        if (strlen($HTTP_REFERER) > 0) {
            $referer_host = wp_parse_url($HTTP_REFERER, PHP_URL_HOST);
            $current_host = wp_parse_url(home_url(), PHP_URL_HOST);
            
            // 只有当 referer 来自同一域名时才使用，避免第三方域名跳转的问题
            if ($referer_host === $current_host) {
                return $HTTP_REFERER;
            }
        }
        return home_url($REQUEST_URI);
    }

    public static function parse_request_params_type($value)
    {
        if ($value === 'true') {
            return true;
        } elseif ($value === 'false') {
            return false;
        } elseif (is_numeric($value)) {
            //  Convert to integer or floating point number
            if (strpos($value, '.') !== false) {
                return (float) $value;  //  If you include a decimal point ， Convert to floating point
            } else {
                return (int) $value;    //  Otherwise convert to integer
            }
        }
        return $value;
    }

    public static function get_request_param($param_name = null, $allowed_params = null)
    {
        // if (empty($allowed_params)) {
        //     return null;
        // }

        //  Initialization parameter array
        $params = [];

        $request_method =  strtolower(sanitize_key(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'));

        // Process only allowed parameters based on request method
        switch ($request_method) {
            case 'get':
                if (is_array($allowed_params)) {
                    foreach ($allowed_params as $allowed_param) {
                        if (isset($_GET[$allowed_param])) {
                            $params[$allowed_param] = self::parse_request_params_type(sanitize_text_field($_GET[$allowed_param]));
                        }
                    }
                } else {
                    // compat with legacy code
                    // deal with  GET  Request parameters
                    foreach ($_GET as $key => $value) {
                        $params[$key] = self::parse_request_params_type(sanitize_text_field($value));
                    }
                }

                break;

            case 'post':
                if (is_array($allowed_params)) {
                    foreach ($allowed_params as $allowed_param) {
                        if (isset($_POST[$allowed_param])) {
                            $params[$allowed_param] = self::parse_request_params_type(sanitize_text_field($_POST[$allowed_param]));
                        }
                    }
                } else {
                    // deal with  POST  Request parameters
                    foreach ($_POST as $key => $value) {
                        $params[$key] = self::parse_request_params_type(sanitize_text_field($value));
                    }
                }

                // Handle JSON requests (PUT, PATCH, etc.)
                $input = file_get_contents('php://input');
                $json_params = json_decode($input, false);

                if ($json_params !== null) {
                    if (is_array($allowed_params)) {
                        foreach ($allowed_params as $allowed_param) {
                            if (isset($json_params[$allowed_param])) {
                                $params[$allowed_param] = $json_params[$allowed_param];
                            }
                        }
                    } else {
                        foreach ($json_params as $key => $value) {
                            $params[$key] = $value;
                        }
                    }
                }

                // attach GET params from url, otherwise will missing some params
                $extra_keys=['action', 'path'];
                foreach ($extra_keys as $key) {
                    if (isset($_GET[$key])) {
                        $params[$key] = self::parse_request_params_type(sanitize_text_field($_GET[$key]));
                    }
                }

                break;

            default:
                // Handle JSON requests (PUT, PATCH, etc.)
                $input = file_get_contents('php://input');
                $json_params = json_decode($input, true);

                if ($json_params !== null) {
                    if (is_array($allowed_params)) {
                        foreach ($allowed_params as $allowed_param) {
                            if (isset($json_params[$allowed_param])) {
                                $params[$allowed_param] = $json_params[$allowed_param];
                            }
                        }
                    } else {
                        foreach ($json_params as $key => $value) {
                            $params[$key] = $value;
                        }
                    }
                }
                break;
        }

        global $wp_query;
        $query_vars = $wp_query->query_vars ?? [];

        if (is_array($allowed_params)) {
            foreach ($allowed_params as $allowed_param) {
                if (isset($query_vars[$allowed_param]) && strpos($allowed_param, 'lofty') === 0) {
                    $params[$allowed_param] = self::parse_request_params_type($query_vars[$allowed_param]);
                }
            }
        } else {
            foreach ($query_vars as $key => $value) {
                if (strpos($key, 'lofty') === 0) {
                    $params[$key] = self::parse_request_params_type($value);
                }
            }
        }

        //  If no parameter name is specified ， Returns all parameters
        if ($param_name === null) {
            return $params;
        }
        return isset($params[$param_name]) ? $params[$param_name] : null;
    }


    public static function loftyVites($u, $dir = '')
    {
        if (LOFTY_IS_DEV) {
            return 'http://127.0.0.1:5173/' . $u;
        }
        preg_match('/\/([^\/]+)\/index\.js$/', $u, $matches);
        $module =  "assets/$matches[1].js";
        return LOFTY_IDX_URL . $module . "?t="  . LOFTY_BUILD_ID;
    }

    public static function is_mobile()
    {
        //  Define some common mobile terminals User-Agent string
        $mobile_user_agents = array(
            'Mobile',
            'Android',
            'iPhone',
            'iPad',
            'Windows Phone',
            'BlackBerry',
            'Opera Mini',
            'SymbianOS',
            'webOS',
            'DoCoMo',
            'iPhone Simulator',
            'BlackBerry Simulator',
            'Android Emulator',
            'Mobile Safari',
            'Opera Mobi',
            'IEMobile',
            'WPDesktop'
        );
        $HTTP_USER_AGENT = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : "";
        $user_agent = strtolower($HTTP_USER_AGENT);
        foreach ($mobile_user_agents as $mobile_user_agent) {
            if (strpos($user_agent, strtolower($mobile_user_agent)) !== false) {
                return true;
            }
        }
        return false;
    }

    public static function numeral($number, $keep_decimal = 2)
    {
        $formattedNumber = number_format($number, $keep_decimal, '.', ',');
        $formattedNumber = '$' . $formattedNumber;
        return $formattedNumber;
    }

    public static function get_value_by_path($obj, $path, $def = null)
    {
        // Ensure $path is a string or handle other data types gracefully
        $path = is_string($path) ? $path : '';
        $paths = explode('.', $path);
        $current = $obj;

        foreach ($paths as $i => $key) {
            if (is_array($current) && array_key_exists($key, $current)) {
                $current = $current[$key];
            } elseif (is_object($current) && property_exists($current, $key)) {
                $current = $current->$key;
            } else {
                return $def;
            }
        }

        // If the loop completes, $current should be the result
        return isset($current) ? $current : $def;
    }

    public static function generate_random_hex($length = 32)
    {
        // 每两个字符对应一个字节，因此需要的字节数为 $length / 2
        $bytes = random_bytes($length / 2);
        return bin2hex($bytes);
    }

    public static function respond($code, $message, $data = null)
    {
        wp_send_json([
            'status' => [
                'code' => $code,
                'message' => $message,
            ],
            'data' => $data
        ]);
        wp_die();
    }
}
