<?php

require_once(dirname(__FILE__) . '/sso-storage.php');

if (!function_exists('migrate_sso_user_meta_to_database')) {
    function migrate_sso_user_meta_to_database()
    {
        global $db_tables;

        if (!sso_tables_exist()) {
            throw new Exception('SSO database tables do not exist.');
        }

        // Query xi_usermeta directly for all rows with keyname = 'aad_tenants'
        $sql = "SELECT * FROM " . $db_tables[DB_NAGIOSXI]["usermeta"] . " WHERE keyname='" . escape_sql_param('aad_tenants', DB_NAGIOSXI) . "'";
        $rs = exec_sql_query(DB_NAGIOSXI, $sql);
        
        if (!$rs || $rs->RecordCount() === 0) {
            return array('migrated' => 0, 'already_migrated' => true);
        }

        $migrated = 0;

        // Iterate through all user meta entries with aad_tenants
        if ($rs->MoveFirst()) {
            do {
                $user_id = (int)$rs->fields["user_id"];
                $meta_encrypted = $rs->fields["keyvalue"];

                if (empty($meta_encrypted)) {
                    continue;
                }

                // Decrypt and decode the tenant mappings
                $decrypted = decrypt_data($meta_encrypted);
                if (empty($decrypted)) {
                    continue;
                }

                $UserTenants = json_decode($decrypted);
                
                // Handle both array and object cases as shown in the example
                if (is_array($UserTenants)) {
                    $tenant_mappings = $UserTenants;
                } elseif ($UserTenants instanceof stdClass) {
                    $tenant_mappings = (array)$UserTenants;
                } else {
                    continue;
                }

                // Process each tenant mapping
                foreach ($tenant_mappings as $object_id => $tenant_info) {
                    if (!is_array($tenant_info)) {
                        $tenant_info = (array)$tenant_info;
                    }

                    $client_id = grab_array_var($tenant_info, 'client_id');
                    $tenant_id = grab_array_var($tenant_info, 'tenant_id');

                    if (empty($object_id) || empty($client_id) || empty($tenant_id)) {
                        continue;
                    }

                    // Skip if mapping already exists
                    $existing = get_sso_mapping($object_id, $client_id);
                    if ($existing) {
                        continue;
                    }

                    // Create the SSO mapping
                    create_sso_mapping(array(
                        'object_id' => $object_id,
                        'client_id' => $client_id,
                        'user_id' => $user_id,
                        'tenant_id' => $tenant_id,
                        'source' => 'individual',
                        'priority' => 'individual',
                        'source_group_id' => null,
                        'created_via_sso' => 0, // We are not creating new users, so we have to set this to 0 to not accidentally delete pre-existing users
                    ));
                    $migrated++;
                }

                // Delete the user meta entry after processing
                delete_user_meta($user_id, 'aad_tenants');

            } while ($rs->MoveNext());
        }

        if ($migrated > 0) {
            if (function_exists('log_sso')) {
                log_sso("Migrated {$migrated} SSO user mappings from user_meta to xi_sso_mappings.", 'info');
            } else {
                error_log("Migrated {$migrated} SSO user mappings from user_meta to xi_sso_mappings.");
            }
        }

        return array('migrated' => $migrated, 'already_migrated' => false);
    }
}

