<?php
namespace Plugin\ReferralSystem;
define('__PATH_REFERRALSYSTEM_ROOT__', __PATH_PLUGINS__.'referralsystem/');
define('__REFERRALSYSTEM_HOME__', __BASE_URL__.'referral/');
$extra_admincp_sidebar[] = array('Referral System - Nexora', array(array('Settings','referralsystem&page=settings'),array('Referrals','referralsystem&page=logs')));
$langDir=__PATH_REFERRALSYSTEM_ROOT__.'languages/'.config('language_default',true).'/language.php';
if(!is_file($langDir)) $langDir=__PATH_REFERRALSYSTEM_ROOT__.'languages/en/language.php';
if(!@include_once($langDir)) throw new \Exception('Error loading language file (referralsystem).');
if(!@include_once(__PATH_REFERRALSYSTEM_ROOT__.'classes/class.referralsystem.php')) throw new \Exception(lang('referralsystem_error_1'));

// Capture a referral only while the registration form is being submitted.
if(isset($_POST['webengineRegister_submit'],$_POST['webengineRegister_user'],$_COOKIE['nexora_referral_player'],$_COOKIE['nexora_referral_realm'])) {
    try {
        $realm=\NexoraRealm::validate((string)$_COOKIE['nexora_referral_realm']);
        if(isset($_POST['nexora_realm']) && \NexoraRealm::validate($_POST['nexora_realm']) !== $realm) throw new \RuntimeException('El enlace de referido pertenece a otro reino.');
        $player=trim((string)$_COOKIE['nexora_referral_player']);
        $db=\Connection::Database('MuOnline',$realm);
        $char=$db->query_fetch_single('SELECT TOP 1 '. _CLMN_CHR_ACCID_ .' AS account,'. _CLMN_CHR_NAME_ .' AS character_name FROM '. _TBL_CHR_ .' WHERE '. _CLMN_CHR_NAME_ .'=?',array($player));
        if(is_array($char)) {
            $r=new ReferralSystem($realm);
            $r->setReferralUsername($char['account']);
            $r->setReferralCharacter($char['character_name']);
            $r->setReferredUsername($_POST['webengineRegister_user']);
            $r->registerReferral();
        }
        setcookie('nexora_referral_player','',time()-3600,'/');
        setcookie('nexora_referral_realm','',time()-3600,'/');
    } catch(\Throwable $e) { /* registration itself must never be blocked by referral metadata */ }
}
