<?php
/**
 * Region Redirect Manager
 * Handles browser language and IP detection to prompt users to switch to China site.
 */

if (!defined('ABSPATH')) {
    exit;
}

class Nenghui_Redirect_Manager {
    
    private static $instance = null;

    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // Enqueue scripts and styles
        add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
        
        // AJAX handlers for IP check
        add_action('wp_ajax_nenghui_check_user_ip', array($this, 'check_user_ip'));
        add_action('wp_ajax_nopriv_nenghui_check_user_ip', array($this, 'check_user_ip'));
        
        // Customizer registration is handled in admin-config.php as per user request,
        // but we can provide a method to be called there.
    }

    public function enqueue_assets() {
        // Check if feature is enabled
        if (!get_theme_mod('nenghui_redirect_enable', false)) {
            return;
        }

        // Enqueue CSS
        wp_enqueue_style(
            'nenghui-redirect-style',
            get_template_directory_uri() . '/inc/redirect-manager/assets/css/redirect.css',
            array(),
            '1.0.0'
        );

        // Enqueue JS
        wp_enqueue_script(
            'nenghui-redirect-script',
            get_template_directory_uri() . '/inc/redirect-manager/assets/js/redirect.js',
            array('jquery'),
            '1.0.0',
            true
        );

        // Localize script with params
        wp_localize_script('nenghui-redirect-script', 'nenghuiRedirectParams', array(
            'enable' => true,
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('nenghui_redirect_nonce'),
            'target_url' => get_theme_mod('nenghui_redirect_target_url', 'https://www.nenghui.com'),
            'check_ip' => get_theme_mod('nenghui_redirect_check_ip', true)
        ));
    }

    public function check_user_ip() {
        check_ajax_referer('nenghui_redirect_nonce', 'nonce');

        $is_china = false;
        
        // 1. Check Cloudflare Header
        if (isset($_SERVER['HTTP_CF_IPCOUNTRY'])) {
            if (strtoupper($_SERVER['HTTP_CF_IPCOUNTRY']) === 'CN') {
                $is_china = true;
            }
        } else {
            // 2. Fallback to IP API
            $user_ip = $this->get_client_ip();
            
            // Skip local IPs
            if ($user_ip === '127.0.0.1' || $user_ip === '::1') {
                wp_send_json_success(array('is_china' => false, 'source' => 'localhost'));
            }

            // Call ip-api.com (free, no key required, 45 requests/minute limit)
            // Note: ip-api.com returns HTTP, but we are making the request from server, so it's fine.
            $response = wp_remote_get("http://ip-api.com/json/{$user_ip}?fields=status,countryCode");
            
            if (!is_wp_error($response)) {
                $body = wp_remote_retrieve_body($response);
                $data = json_decode($body, true);
                
                if (isset($data['status']) && $data['status'] === 'success') {
                    if (isset($data['countryCode']) && strtoupper($data['countryCode']) === 'CN') {
                        $is_china = true;
                    }
                }
            }
        }

        wp_send_json_success(array('is_china' => $is_china));
    }

    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    // trim for safety measures
                    $ip = trim($ip);
                    // attempt to validate IP
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
    }

    // Static method to register customizer settings
    public static function register_customizer_settings($wp_customize) {
        // Add Panel
        $wp_customize->add_section('nenghui_redirect_section', array(
            'title' => '中国区跳转设置 (Region Redirect)',
            'description' => '配置基于语言和IP的自动跳转提示 / Configure language and IP based redirect prompt',
            'priority' => 120,
        ));

        // Enable Toggle
        $wp_customize->add_setting('nenghui_redirect_enable', array(
            'default' => false,
            'sanitize_callback' => 'wp_validate_boolean',
        ));
        $wp_customize->add_control('nenghui_redirect_enable', array(
            'label' => '启用跳转提示 (Enable Redirect Prompt)',
            'section' => 'nenghui_redirect_section',
            'type' => 'checkbox',
        ));

        // Target URL
        $wp_customize->add_setting('nenghui_redirect_target_url', array(
            'default' => 'https://www.nenghui.com',
            'sanitize_callback' => 'esc_url_raw',
        ));
        $wp_customize->add_control('nenghui_redirect_target_url', array(
            'label' => '中国区官网地址 (Target URL)',
            'section' => 'nenghui_redirect_section',
            'type' => 'url',
        ));

        // Check IP Toggle
        $wp_customize->add_setting('nenghui_redirect_check_ip', array(
            'default' => true,
            'sanitize_callback' => 'wp_validate_boolean',
        ));
        $wp_customize->add_control('nenghui_redirect_check_ip', array(
            'label' => '启用IP检测 (Enable IP Detection)',
            'description' => '如果在非中文浏览器环境下，是否检测IP归属地 / Check IP if browser language is not Chinese',
            'section' => 'nenghui_redirect_section',
            'type' => 'checkbox',
        ));
    }
}

// Initialize the class
Nenghui_Redirect_Manager::get_instance();
