<?php
/**
 * Nexora account country cache updater.
 * Game session data is read from the active realm; country metadata is stored in Platform.
 */

$file_name = basename(__FILE__);

$realmDb = Connection::Database('Me_MuOnline');
$platformDb = Connection::Database('Platform');

// Read a bounded set from the realm and decide Platform membership in PHP. This avoids
// coupling the job to cross-database SQL permissions when Platform is enabled.
$accountList = $realmDb->query_fetch(
    "SELECT TOP 100 "._CLMN_MS_MEMBID_.", "._CLMN_MS_IP_." FROM "._TBL_MS_." WHERE "._CLMN_MS_IP_." IS NOT NULL"
);

if(is_array($accountList)) {
    $Account = new Account();
    $inserted = 0;
    foreach($accountList as $row) {
        if($inserted >= 40) break;
        $accountId = $row[_CLMN_MS_MEMBID_];
        $existing = $platformDb->query_fetch_single(
            "SELECT TOP 1 account FROM ".WEBENGINE_ACCOUNT_COUNTRY." WHERE account = ?",
            array($accountId)
        );
        if(is_array($existing)) continue;

        $countryCode = getCountryCodeFromIp($row[_CLMN_MS_IP_]);
        if(!check_value($countryCode)) continue;
        $Account->setAccount($accountId);
        $Account->setCountry($countryCode);
        if($Account->insertAccountCountry()) $inserted++;
    }
}

updateCronLastRun($file_name);
