<?php
/**
 * اختصاص مجدد نقش‌های melk به کاربران تست (بدون پاک کردن پرونده‌ها)
 * php run-melk-fix-roles.php
 */
declare(strict_types=1);
define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';
require_once ACC_PATH . 'includes/helpers/acl-functions.php';

$GLOBALS['_melk_install_quiet'] = true;
ob_start();
include __DIR__ . '/run-melk-install.php';
ob_end_clean();

global $wpdb;

if ( ! function_exists( 'melk_role_id' ) ) {
    function melk_role_id( string $slug ): int {
        global $wpdb;
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug = %s", $slug
        ));
    }
}

if ( ! function_exists( 'melk_assign_role' ) ) {
    function melk_assign_role( int $user_id, string $role_slug, ?string $scope_type = null, ?int $scope_id = null ): void {
    global $wpdb;
    $role_id = melk_role_id($role_slug);
    if ( ! $role_id || ! $user_id ) return;
    $wpdb->delete("{$wpdb->prefix}acl_user_roles", [
        'user_id' => $user_id, 'role_id' => $role_id,
    ]);
    $wpdb->insert("{$wpdb->prefix}acl_user_roles", [
        'user_id'    => $user_id,
        'role_id'    => $role_id,
        'scope_type' => $scope_type ?? 'global',
        'scope_id'   => $scope_id,
        'granted_by' => 2,
    ]);
    }
}

$map = [
    'melk_lead_d1'   => ['district_lead', 'district', 1],
    'melk_lead_d2'   => ['district_lead', 'district', 2],
    'melk_mgr_007'   => ['neighborhood_manager', 'neighborhood', 1],
    'melk_mgr_006'   => ['neighborhood_manager', 'neighborhood', 17],
    'melk_legal'     => ['melk_specialist', 'global', null],
    'melk_shahrdari' => ['melk_specialist', 'global', null],
    'melk_registry'  => ['melk_specialist', 'global', null],
    'melk_coord'     => ['melk_coordinator', 'global', null],
    'melk_sysadmin'  => ['super_admin', 'global', null],
    'region_1'       => ['district_lead', 'district', 1],
    'melk_county_agency'      => ['melk_county_agency', 'global', null],
    'melk_specialist_arch'    => ['melk_building_specialist', 'global', null],
    'melk_specialist_struct'  => ['melk_building_specialist', 'global', null],
    'melk_specialist_mep'     => ['melk_building_specialist', 'global', null],
    'melk_specialist_pending' => ['melk_building_specialist', 'global', null],
    'melk_agent'              => ['agent', 'neighborhood', 1],
];

$fixed = [];
foreach ( $map as $login => [$role, $scope, $sid] ) {
    $uid = (int) $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_login=%s", $login));
    if ( ! $uid ) continue;
    melk_assign_role($uid, $role, $scope, $sid);
    $fixed[] = [
        'login' => $login, 'id' => $uid,
        'melk_view' => acl_user_can($uid, 'melk.view'),
    ];
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['success' => true, 'fixed' => $fixed], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
