<?php

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

/*
|--------------------------------------------------------------------------
| Register REST Routes
|--------------------------------------------------------------------------
*/

add_action('rest_api_init', function () {

    // Users list
    register_rest_route('acc/v1', '/users', [
        'methods'  => 'GET',
        'callback' => 'acc_users_list',
        'permission_callback' => 'acc_jwt_check_permission',
        'args' => [

            'page' => [
                'default' => 1,
                'sanitize_callback' => 'absint'
            ],

            'size' => [
                'default' => 10,
                'sanitize_callback' => 'absint'
            ],

            'search' => [
                'default' => '',
                'sanitize_callback' => 'sanitize_text_field'
            ],

            // ✅ فیلتر جدید روی نقش وردپرس
            'role' => [
                'default' => '',
                'sanitize_callback' => 'sanitize_text_field'
            ],

            // ✅ فیلتر کارت‌ها
            'has_permissions' => [
                'default' => null,
            ],
            'has_modules' => [
                'default' => null,
            ],
            'has_rows' => [
                'default' => null,
            ],
        ]
    ]);

    // Users roles summary
    register_rest_route('acc/v1', '/users/roles', [
        'methods'  => 'GET',
        'callback' => 'acc_users_roles_summary',
        'permission_callback' => 'acc_jwt_check_permission',
    ]);

    // User update
    register_rest_route('acc/v1', '/users/(?P<id>\d+)', [
        'methods'  => 'PUT',
        'callback' => 'acc_users_update',
        'permission_callback' => 'acc_jwt_check_permission',
        'args' => [
            'id' => [
                'required' => true,
            ],
            'fullname' => [
                'required' => false,
                'sanitize_callback' => 'sanitize_text_field',
            ],
            'email' => [
                'required' => false,
                'sanitize_callback' => 'sanitize_email',
            ],
        ],
    ]);

});



/**
 * PUT /wp-json/acc/v1/users/{id}
 */
function acc_users_update_permission_check() {

    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_forbidden',
            __('You must be logged in.', 'acc'),
            ['status' => 401]
        );
    }

    if (!current_user_can('edit_users')) {
        return new WP_Error(
            'rest_forbidden',
            __('You do not have permission to edit users.', 'acc'),
            ['status' => 403]
        );
    }

    return true;
}

function acc_users_update(WP_REST_Request $request) {

    $user_id = (int) $request->get_param('id');

    if ($user_id <= 0) {
        return new WP_Error(
            'rest_invalid_param',
            __('Invalid user ID.', 'acc'),
            ['status' => 400]
        );
    }

    $user = get_user_by('id', $user_id);
    if (!$user) {
        return new WP_Error(
            'rest_user_not_found',
            __('User not found.', 'acc'),
            ['status' => 404]
        );
    }

    $fullname = $request->get_param('fullname');
    $email    = $request->get_param('email');

    $userdata = [
        'ID' => $user_id,
    ];

    if (!empty($fullname)) {
        $userdata['display_name'] = sanitize_text_field($fullname);
    }

    if (!empty($email)) {
        $userdata['user_email'] = sanitize_email($email);
    }

    // اگر هیچ چیزی برای تغییر نداریم، اطلاعات فعلی را برگردان
    if (count($userdata) === 1) {
        return [
            'id'       => $user_id,
            'username' => $user->user_login,
            'fullname' => $user->display_name,
            'email'    => $user->user_email,
            'roles'    => array_values($user->roles),
        ];
    }

    $update_result = wp_update_user($userdata);
    if (is_wp_error($update_result)) {
        return $update_result;
    }

    $updated_user = get_user_by('id', $user_id);

    return [
        'id'       => $user_id,
        'username' => $updated_user->user_login,
        'fullname' => $updated_user->display_name,
        'email'    => $updated_user->user_email,
        'roles'    => array_values($updated_user->roles),
    ];
}


/*
|--------------------------------------------------------------------------
| Permission Check
|--------------------------------------------------------------------------
*/

function acc_users_permission_check() {

    if (!is_user_logged_in()) {
        return new WP_Error(
            'rest_forbidden',
            __('You must be logged in.', 'acc'),
            ['status' => 401]
        );
    }

    if (!current_user_can('list_users')) {
        return new WP_Error(
            'rest_forbidden',
            __('You do not have permission to list users.', 'acc'),
            ['status' => 403]
        );
    }

    return true;
}


/*
|--------------------------------------------------------------------------
| Users Roles Summary Endpoint
|--------------------------------------------------------------------------
| GET /wp-json/acc/v1/users/roles
*/

function acc_users_roles_summary(WP_REST_Request $request) {

    global $wpdb;

    $users_table    = $wpdb->users;
    $usermeta_table = $wpdb->usermeta;
    $cap_key        = $wpdb->prefix . 'capabilities';

    $sql = "
        SELECT
            SUBSTRING_INDEX(
                SUBSTRING_INDEX(um.meta_value, '\"', 2),
                '\"',
                -1
            ) AS role,
            COUNT(*) AS total_users
        FROM {$users_table} u
        JOIN {$usermeta_table} um ON um.user_id = u.ID
        WHERE um.meta_key = %s
        GROUP BY role
        ORDER BY total_users DESC
    ";

    $rows = $wpdb->get_results(
        $wpdb->prepare($sql, $cap_key),
        ARRAY_A
    );

    return [
        'data' => $rows
    ];
}


/*
|--------------------------------------------------------------------------
| Users List Endpoint (SQL-based filtering)
|--------------------------------------------------------------------------
| GET /wp-json/acc/v1/users
|
| فیلترها:
| - search
| - role
| - has_permissions (0/1)
| - has_modules (0/1)
| - has_rows (0/1)
*/

function acc_users_list(WP_REST_Request $request) {

    global $wpdb;

    /*
    |--------------------------------------------------------------------------
    | Inputs
    |--------------------------------------------------------------------------
    */

    $page   = max(1, intval($request->get_param('page')));
    $size   = max(1, intval($request->get_param('size')));
    $search = sanitize_text_field($request->get_param('search'));

    $role_filter     = sanitize_text_field($request->get_param('role'));
    $has_permissions = $request->get_param('has_permissions');
    $has_modules     = $request->get_param('has_modules');
    $has_rows        = $request->get_param('has_rows');

    $offset = ($page - 1) * $size;

    /*
    |--------------------------------------------------------------------------
    | Tables
    |--------------------------------------------------------------------------
    */

    $users_table    = $wpdb->users;
    $usermeta_table = $wpdb->usermeta;

    $table_user_roles       = $wpdb->prefix . 'erp_user_roles';
    $table_role_permissions = $wpdb->prefix . 'erp_role_permissions';
    $table_object_perm      = $wpdb->prefix . 'erp_object_permissions';
    $table_ui_perm          = $wpdb->prefix . 'erp_ui_permissions';

    $cap_key = $wpdb->prefix . 'capabilities';

    /*
    |--------------------------------------------------------------------------
    | WHERE conditions (base)
    |--------------------------------------------------------------------------
    */

    $where   = [];
    $params  = [];

    // جستجو روی login / email / display_name
    if ($search !== '') {
        $like = '%' . $wpdb->esc_like($search) . '%';
        $where[] = "(
            u.user_login   LIKE %s
            OR u.user_email LIKE %s
            OR u.display_name LIKE %s
        )";
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    // فیلتر نقش وردپرس
    $join_cap = '';
    if ($role_filter !== '') {

        $join_cap = " 
            INNER JOIN {$usermeta_table} um_cap
                ON um_cap.user_id = u.ID
               AND um_cap.meta_key = %s
        ";

        $params[] = $cap_key;

        // meta_value مثل: a:1:{s:13:"administrator";b:1;}
        $like_role = '%"' . $wpdb->esc_like($role_filter) . '"%';
        $where[]   = "um_cap.meta_value LIKE %s";
        $params[]  = $like_role;
    }

    /*
    |--------------------------------------------------------------------------
    | JOIN های مربوط به مجوز، ماژول، ردیف‌ها
    |--------------------------------------------------------------------------
    | اینجا با LEFT JOIN + GROUP BY کاربر را یکبار می‌گیریم و همه count ها
    | را در همان کوئری محاسبه می‌کنیم.
    |--------------------------------------------------------------------------
    */

    // join برای role_ids
    $join_user_roles = "LEFT JOIN {$table_user_roles} tur ON tur.user_id = u.ID";

    // join برای permissions از روی نقش‌های ERP
    $join_role_perms = "LEFT JOIN {$table_role_permissions} trp
                           ON trp.role_id = tur.role_id";

    // join برای object permissions (rows)
    $join_object_perm = "LEFT JOIN {$table_object_perm} topm
                            ON topm.user_id = u.ID";

    // join برای ui permissions (modules)
    $join_ui_perm = "LEFT JOIN {$table_ui_perm} tuip
                        ON tuip.user_id = u.ID";

    /*
    |--------------------------------------------------------------------------
    | HAVING conditions برای فیلتر کارت‌ها
    |--------------------------------------------------------------------------
    */

    $having = [];
    if ($has_permissions !== null && $has_permissions !== '') {
        if ((int)$has_permissions === 1) {
            $having[] = "permission_count > 0";
        } else {
            $having[] = "permission_count = 0";
        }
    }

    if ($has_modules !== null && $has_modules !== '') {
        if ((int)$has_modules === 1) {
            $having[] = "module_count > 0";
        } else {
            $having[] = "module_count = 0";
        }
    }

    if ($has_rows !== null && $has_rows !== '') {
        if ((int)$has_rows === 1) {
            $having[] = "row_count > 0";
        } else {
            $having[] = "row_count = 0";
        }
    }

    $where_sql  = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
    $having_sql = $having ? ('HAVING ' . implode(' AND ', $having)) : '';

    /*
    |--------------------------------------------------------------------------
    | Main SQL (paged)
    |--------------------------------------------------------------------------
    */

    $sql = "
        SELECT
            u.ID,
            u.user_login,
            u.user_email,
            u.display_name,

            -- شمارش permission های یونیک بر اساس نقش‌های ERP
            COUNT(DISTINCT trp.permission_key) AS permission_count,

            -- شمارش ردیف‌ها
            COUNT(DISTINCT topm.id) AS row_count,

            -- شمارش ماژول‌ها
            COUNT(DISTINCT tuip.id) AS module_count,

            -- جمع‌آوری role_id ها برای هر کاربر
            GROUP_CONCAT(DISTINCT tur.role_id) AS role_ids_csv
        FROM {$users_table} u
        {$join_cap}
        {$join_user_roles}
        {$join_role_perms}
        {$join_object_perm}
        {$join_ui_perm}
        {$where_sql}
        GROUP BY u.ID
        {$having_sql}
        ORDER BY u.ID DESC
        LIMIT %d OFFSET %d
    ";

    $params_paged   = $params;
    $params_paged[] = $size;
    $params_paged[] = $offset;

    $prepared_sql = $wpdb->prepare($sql, $params_paged);

    $rows = $wpdb->get_results($prepared_sql, ARRAY_A);

    /*
    |--------------------------------------------------------------------------
    | Total Count (بدون LIMIT, با همان WHERE/HAVING)
    |--------------------------------------------------------------------------
    */

    $count_sql = "
        SELECT COUNT(*) FROM (
            SELECT u.ID
            FROM {$users_table} u
            {$join_cap}
            {$join_user_roles}
            {$join_role_perms}
            {$join_object_perm}
            {$join_ui_perm}
            {$where_sql}
            GROUP BY u.ID
            {$having_sql}
        ) AS t
    ";

    $prepared_count_sql = $wpdb->prepare($count_sql, $params);
    $total = (int)$wpdb->get_var($prepared_count_sql);

    /*
    |--------------------------------------------------------------------------
    | Build Users Response (مطابق ساختار قبلی)
    |--------------------------------------------------------------------------
    */

    $users = [];

    foreach ($rows as $row) {

        $permission_count = (int)$row['permission_count'];
        $module_count     = (int)$row['module_count'];
        $row_count        = (int)$row['row_count'];

        // role_ids از CSV به آرایه
        $role_ids = [];
        if (!empty($row['role_ids_csv'])) {
            $role_ids = array_map('intval', explode(',', $row['role_ids_csv']));
        }

        // گرفتن roles وردپرسی (همان قبلی، برای سازگاری)
        $wp_user   = get_user_by('id', $row['ID']);
        $wp_roles  = $wp_user ? array_values($wp_user->roles) : [];

        $users[] = [
            'id'       => (int)$row['ID'],
            'username' => $row['user_login'],
            'fullname' => $row['display_name'],
            'email'    => $row['user_email'],

            'roles'    => $wp_roles,
            'role_ids' => $role_ids,

            'permission_count' => $permission_count,
            'module_count'     => $module_count,
            'row_count'        => $row_count,

            'has_permissions'  => $permission_count > 0,
            'has_modules'      => $module_count > 0,
            'has_rows'         => $row_count > 0,
        ];
    }

    $last_page = $size > 0
        ? ceil($total / $size)
        : 1;

    /*
    |--------------------------------------------------------------------------
    | Tabulator Compatible Response
    |--------------------------------------------------------------------------
    */

    return [
        'data'      => $users,
        'last_page' => $last_page,
        'total'     => $total
    ];
}
