<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WP_REST_Request;
use WP_REST_Response;
use WP_User_Query;

/**
 * User Controller
 *
 * Handles user-related API endpoints
 */
class UserController
{
    /**
     * Get admin emails
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_admin_emails(WP_REST_Request $request)
    {
        $args = array(
            'role' => 'administrator',
            'fields' => 'user_email'
        );
        $admin_query = new WP_User_Query($args);
        return new WP_REST_Response($admin_query->get_results(), 200);
    }

    /**
     * Get all users (formatted)
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_all_users(WP_REST_Request $request)
    {
        $users = get_users();

        $formatted_users = array_map(function ($user) {
            return [
                'value' => $user->display_name,
                'code' => $user->user_login,
            ];
        }, $users);

        return rest_ensure_response($formatted_users);
    }

    /**
     * Get users with metadata
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_users(WP_REST_Request $request)
    {
        $users = get_users();
        $role_names = wp_roles()->get_names();

        foreach ($users as $id => $user) {
            $ultimate_security_login_token = get_user_meta($user->ID, 'ultimate_security_login_token', true);
            $ultimate_security_user_last_logged_in = get_user_meta($user->ID, 'ultimate_security_user_last_logged_in', true);
            $ultimate_security_user_logged_count = get_user_meta($user->ID, 'ultimate_security_user_logged_count', true);
            $ultimate_security_user_expiration = get_user_meta($user->ID, 'ultimate_security_user_expiration', true);

            // Build the one-time login URL
            $login_url = add_query_arg([
                'ultimate_security_login_token' => $ultimate_security_login_token,
            ], home_url('/ultimate-security-temp-user-login'));

            $users[$id]->user_meta = get_user_meta($user->ID);
            $users[$id]->avatar = esc_url(get_avatar_url($user->ID));
            $users[$id]->role = esc_html($role_names[$user->roles[0]]);
            $users[$id]->ultimate_security_user_last_logged_in = esc_html($ultimate_security_user_last_logged_in);
            $users[$id]->ultimate_security_user_logged_count = esc_html($ultimate_security_user_logged_count);
            $users[$id]->ultimate_security_user_expiration = $ultimate_security_user_expiration ? esc_html(gmdate('Y-m-d', $ultimate_security_user_expiration)) : '';
            $users[$id]->login_url = esc_url($login_url);
        }

        return rest_ensure_response($users);
    }

    /**
     * Get roles with counts
     *
     * @param WP_REST_Request $request
     * @return array
     */
    public static function get_roles(WP_REST_Request $request)
    {
        global $wpdb;

        try {
            $roles = wp_roles()->roles;
            $roles_count = array();

            foreach ($roles as $role_slug => $role_details) {
                $roles_count[$role_slug] = array(
                    'name' => $role_details['name'],
                    'count' => 0
                );
            }

            // Query usermeta table for role counts
            $meta_key = $wpdb->prefix . 'capabilities';

            $sql = $wpdb->prepare(
                "SELECT meta_value AS role, COUNT(*) AS count
                FROM {$wpdb->usermeta}
                WHERE meta_key = %s
                GROUP BY meta_value",
                            $meta_key
                        );

            $user_roles = $wpdb->get_results($sql);

            foreach ($user_roles as $user_role) {
                $role_data = maybe_unserialize($user_role->role);
                if (is_array($role_data)) {
                    foreach ($role_data as $role => $enabled) {
                        if ($enabled && isset($roles_count[$role])) {
                            $roles_count[$role]['count'] += $user_role->count;
                        }
                    }
                }
            }

            return new WP_REST_Response($roles_count, 200);

        } catch (\Exception $e) {
            return new WP_REST_Response(
                array(
                    'message' => __('Failed to retrieve roles', 'ultimate-security'),
                    'error' => $e->getMessage()
                ),
                500
            );
        }
    }

    public static function get_setting_theme(WP_REST_Request $request)
    {
        $settings_theme = get_user_meta(get_current_user_id(), 'ultimate_security_settings_theme', true);
        return rest_ensure_response($settings_theme);
    }

    public static function set_setting_theme(WP_REST_Request $request)
    {
        // $user_id = sanitize_text_field(wp_unslash($request->get_param('user_id')))??get_current_user_id();
        $user_id = get_current_user_id();
        $settings_theme = sanitize_text_field(wp_unslash($request->get_param('settings_theme')));
        // get_user_meta($user_id, 'ultimate_security_settings_theme', $settings_theme);
        update_user_meta($user_id, 'ultimate_security_settings_theme', $settings_theme);

        $response = [
            'success' => true,
            'msg' => esc_html__('Theme set successfully.' . $user_id . $settings_theme, 'ultimate-security'),
        ];

        return new WP_REST_Response($response, 200);
    }
}
