<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class Devices {

    public static function get_user_devices($user_id) {
        $manager = \WP_Session_Tokens::get_instance($user_id);
        $sessions = $manager->get_all();

        if (empty($sessions)) {
            return [];
        }

        $devices = [];
        $current_token = wp_get_session_token();
        $current_verifier = $current_token ? hash('sha256', $current_token) : '';

        foreach ($sessions as $token => $session) {
            $ua = isset($session['ua']) ? $session['ua'] : 'Unknown Device';
            $login = isset($session['login']) ? $session['login'] : time();
            $browser = self::parse_user_agent($ua);
            $is_current = ($token === $current_verifier);

            $devices[$token] = [
                'token' => $token,
                'name' => $browser,
                'ua' => $ua,
                'last_active' => $login,
                'is_current' => $is_current,
                'ip' => isset($session['ip']) ? $session['ip'] : '',
            ];
        }

        uasort($devices, function ($a, $b) {
            return $b['last_active'] - $a['last_active'];
        });

        $found_current = false;
        foreach ($devices as $device) {
            if ($device['is_current']) {
                $found_current = true;
                break;
            }
        }

        if (!$found_current && !empty($devices)) {
            $first_key = array_key_first($devices);
            $devices[$first_key]['is_current'] = true;
        }

        return $devices;
    }

    private static function parse_user_agent($ua) {
        $browsers = [
            '/Brave\/([0-9.]+)/i' => esc_html__('Brave', 'cine-movie-engine'),
            '/Edg\/([0-9.]+)/i' => esc_html__('Edge', 'cine-movie-engine'),
            '/OPR\/([0-9.]+)/i' => esc_html__('Opera', 'cine-movie-engine'),
            '/Vivaldi\/([0-9.]+)/i' => esc_html__('Vivaldi', 'cine-movie-engine'),
            '/Firefox\/([0-9.]+)/i' => esc_html__('Firefox', 'cine-movie-engine'),
            '/Chrome\/([0-9.]+)/i' => esc_html__('Chrome', 'cine-movie-engine'),
            '/Safari\/([0-9.]+)/i' => esc_html__('Safari', 'cine-movie-engine'),
            '/MSIE ([0-9.]+)/i' => esc_html__('Internet Explorer', 'cine-movie-engine'),
            '/Trident\/.*rv:([0-9.]+)/i' => esc_html__('Internet Explorer', 'cine-movie-engine'),
        ];

        foreach ($browsers as $pattern => $name) {
            if (preg_match($pattern, $ua, $matches)) {
                if ($name === 'Safari' && stripos($ua, 'Chrome') !== false) {
                    continue;
                }
                $version = isset($matches[1]) ? ' ' . explode('.', $matches[1])[0] : '';
                return $name . $version;
            }
        }

        if (stripos($ua, 'iPhone') !== false) return 'iPhone';
        if (stripos($ua, 'iPad') !== false) return 'iPad';
        if (stripos($ua, 'Android') !== false) {
            if (stripos($ua, 'Chrome') !== false) return 'Android Chrome';
            if (stripos($ua, 'Firefox') !== false) return 'Android Firefox';
            return 'Android';
        }

        if (preg_match('/([A-Za-z]+)\/([0-9.]+)/', $ua, $matches)) {
            return $matches[1] . ' ' . explode('.', $matches[2])[0];
        }

        return esc_html__('Unknown Browser', 'cine-movie-engine');
    }

    public static function logout_device($user_id, $token) {
        $token = (string)$token;
        $manager = \WP_Session_Tokens::get_instance($user_id);
        $manager->destroy($token);
        wp_cache_delete($user_id, 'user_meta');
        clean_user_cache($user_id);
    }

    public static function logout_all_others($user_id) {
        $current_token = wp_get_session_token();
        $manager = \WP_Session_Tokens::get_instance($user_id);
        $manager->destroy_others($current_token);
        wp_cache_delete($user_id, 'user_meta');
        clean_user_cache($user_id);
    }

    public static function is_device_management_enabled() {
        if (!apply_filters('movie_engine_is_pro', false)) {
            return true; // Always enabled for free version
        }

        $options = get_option('movie_engine_general_settings', []);
        $enabled = $options['movie_engine_enable_device_management'] ?? ($options['enable_device_management'] ?? 0);
        return (int)$enabled === 1;
    }

    public static function get_device_limit($user_id = 0) {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }

        if (!$user_id) return 1;

        // If Pro is not active, always return 1 device limit
        if (!apply_filters('movie_engine_is_pro', false)) {
            return 1;
        }

        // Check user's subscription plan first (Pro feature)
        $active_plan = get_user_meta($user_id, '_movie_engine_active_plan', true);
        if ($active_plan) {
            $plan_limit = get_post_meta($active_plan, '_movie_engine_device_limit', true);
            if ($plan_limit !== '' && $plan_limit !== false) {
                return (int) $plan_limit;
            }
        }

        // Fall back to global setting (Pro feature)
        $options = get_option('movie_engine_general_settings', []);
        $limit = isset($options['movie_engine_device_limit_count']) ? $options['movie_engine_device_limit_count'] : (isset($options['device_limit_count']) ? $options['device_limit_count'] : 2);

        return (int) $limit;
    }

    public static function handle_login_limit($user_login, $user) {
        if (!self::is_device_management_enabled() || !is_object($user)) {
            return;
        }

        $user_id = $user->ID;
        $sessions = get_user_meta($user_id, 'session_tokens', true);

        if (!is_array($sessions) || empty($sessions)) {
            return;
        }

        $sessions = array_filter($sessions, function ($session) {
            return isset($session['expiration']) && $session['expiration'] > time();
        });

        $count = count($sessions);
        $limit = self::get_device_limit($user_id);

        if ($limit <= 0 || $count <= $limit) {
            return;
        }

        uasort($sessions, function ($a, $b) {
            $time_a = isset($a['login']) ? (int)$a['login'] : 0;
            $time_b = isset($b['login']) ? (int)$b['login'] : 0;
            return $time_b - $time_a;
        });

        $session_keys = array_keys($sessions);
        $keep_keys = array_slice($session_keys, 0, $limit);

        $new_sessions = [];
        foreach ($keep_keys as $k) {
            $new_sessions[$k] = $sessions[$k];
        }

        update_user_meta($user_id, 'session_tokens', $new_sessions);
        wp_cache_delete($user_id, 'user_meta');
        clean_user_cache($user_id);
    }

    public static function enforce_limit_on_init() {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $request_uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
        if (!is_user_logged_in() || strpos($request_uri, 'wp-login.php') !== false) {
            return;
        }

        if (is_admin() && !wp_doing_ajax()) {
            return;
        }

        if (!self::is_device_management_enabled()) {
            return;
        }

        $user_id = get_current_user_id();
        $user = get_userdata($user_id);

        if ($user) {
            self::handle_login_limit($user->user_login, $user);
        }
    }

    public static function handle_dashboard_actions() {
        if (!is_user_logged_in() || !isset($_POST['movie_engine_action'])) {
            return;
        }

        check_admin_referer('movie_engine_dashboard_action');

        $user_id = get_current_user_id();
        $action = sanitize_text_field(wp_unslash($_POST['movie_engine_action']));

        if ($action === 'logout_device' && isset($_POST['token'])) {
            self::logout_device($user_id, sanitize_text_field(wp_unslash($_POST['token'])));
            wp_safe_redirect(remove_query_arg(['movie_engine_action', 'token']));
            exit;
        }

        if ($action === 'logout_all_others') {
            self::logout_all_others($user_id);
            wp_safe_redirect(remove_query_arg('movie_engine_action'));
            exit;
        }
    }

    public function __construct() {
        add_action('wp_login', [self::class, 'handle_login_limit'], 10, 2);
        add_action('init', [self::class, 'handle_dashboard_actions'], 5);
        add_action('init', [self::class, 'enforce_limit_on_init'], 1);
    }
}
