<?php
/**
 * ایجاد کاربر مدیر سیستم melk_sysadmin
 */
declare(strict_types=1);
define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

global $wpdb;
$pre = $wpdb->prefix;
$pass = 'Melk@1404';
$login = 'melk_sysadmin';
$name = 'مدیر سیستم اقتصاد ملک';

$id = (int) $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login));
if (!$id) {
    $max = (int) $wpdb->get_var("SELECT COALESCE(MAX(ID), 0) FROM {$wpdb->users}");
    $id = $max + 1;
    $wpdb->insert("{$wpdb->users}", [
        'ID' => $id, 'user_login' => $login,
        'user_pass' => wp_hash_password($pass),
        'user_nicename' => sanitize_title($login),
        'user_email' => $login . '@melk.test',
        'user_registered' => date('Y-m-d H:i:s'),
        'display_name' => $name,
        'user_status' => 0,
    ]);
}

$role_id = (int) $wpdb->get_var("SELECT id FROM {$pre}acl_roles WHERE slug='super_admin' LIMIT 1");
if ($role_id) {
    $wpdb->query($wpdb->prepare(
        "DELETE FROM {$pre}acl_user_roles WHERE user_id=%d AND role_id=%d",
        $id, $role_id
    ));
    $wpdb->insert("{$pre}acl_user_roles", [
        'user_id' => $id, 'role_id' => $role_id,
        'scope_type' => 'global', 'scope_id' => null, 'granted_by' => 2,
    ]);
}

echo json_encode([
    'success' => true,
    'login' => $login,
    'password' => $pass,
    'user_id' => $id,
    'role' => 'super_admin',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
