<?php
?><h2>Vote & Reward - Nexora v2 Anti-Farm</h2><?php
$realm=class_exists('NexoraRealm')?NexoraRealm::active():'legacy';
$vote=new Vote();

function nexoraVoteConfigPath($realm) {
    $realm=class_exists('NexoraRealm')?NexoraRealm::validate($realm):'legacy';
    $path=__PATH_MODULE_CONFIGS__.'usercp.vote.'.$realm.'.xml';
    if(!is_file($path)) {
        $base=__PATH_MODULE_CONFIGS__.'usercp.vote.xml';
        if(is_file($base)) @copy($base,$path);
    }
    return $path;
}
function nexoraVoteXmlSet($xml,$name,$value) {
    if(isset($xml->{$name})) $xml->{$name}=$value;
    else $xml->addChild($name,(string)$value);
}

if(isset($_POST['submit_changes'])) {
    try {
        $path=nexoraVoteConfigPath($realm); $xml=simplexml_load_file($path);
        if(!$xml) throw new RuntimeException('No se pudo abrir la configuracion.');
        $values=array(
            'active'=>!empty($_POST['setting_1'])?1:0,
            'vote_save_logs'=>!empty($_POST['setting_2'])?1:0,
            'credit_config'=>(int)($_POST['setting_3']??0),
            'antifarm_min_account_days'=>(int)($_POST['min_account_days']??5),
            'antifarm_min_level'=>(int)($_POST['min_level']??400),
            'antifarm_min_resets'=>(int)($_POST['min_resets']??5),
            'antifarm_min_master_level'=>(int)($_POST['min_master_level']??0),
            'antifarm_min_online_hours'=>(int)($_POST['min_online_hours']??5),
            'antifarm_device_trust_hours'=>(int)($_POST['device_trust_hours']??24),
            'antifarm_max_accounts_ip_24h'=>(int)($_POST['max_accounts_ip']??2),
            'antifarm_max_accounts_device_24h'=>(int)($_POST['max_accounts_device']??1),
            'antifarm_points_per_conversion'=>(int)($_POST['points_per_conversion']??10),
            'antifarm_credits_per_conversion'=>(int)($_POST['credits_per_conversion']??10),
            'antifarm_daily_user_credit_cap'=>(int)($_POST['daily_user_cap']??20),
            'antifarm_daily_device_credit_cap'=>(int)($_POST['daily_device_cap']??20),
            'antifarm_daily_ip_credit_cap'=>(int)($_POST['daily_ip_cap']??40)
        );
        if($values['credit_config']<1) throw new RuntimeException('Selecciona la moneda que recibira la conversion.');
        foreach(array('antifarm_points_per_conversion','antifarm_credits_per_conversion') as $required) if($values[$required]<1) throw new RuntimeException('La conversion debe usar valores mayores que cero.');
        foreach($values as $key=>$value) nexoraVoteXmlSet($xml,$key,$value);
        if(!$xml->asXML($path)) throw new RuntimeException('No se pudo guardar la configuracion.');
        message('success','Configuracion Anti-Farm de '.ucfirst($realm).' guardada.');
    } catch(Throwable $e) { message('error',$e->getMessage()); }
}
if(isset($_POST['votesite_add_submit'])) {
    try { $vote->addVotesite($_POST['votesite_add_title']??'',$_POST['votesite_add_link']??'',$_POST['votesite_add_reward']??0,$_POST['votesite_add_time']??0); message('success','Sitio agregado.'); }
    catch(Throwable $e) { message('error',$e->getMessage()); }
}
if(isset($_POST['site_action'],$_POST['site_id'])) {
    try {
        $id=(int)$_POST['site_id']; $action=(string)$_POST['site_action'];
        if($action==='delete') { if(!$vote->deleteVotesite($id)) throw new RuntimeException('No se pudo eliminar.'); message('success','Sitio eliminado.'); }
        elseif($action==='enable'||$action==='disable') { if(!$vote->setVotesiteEnabled($id,$action==='enable')) throw new RuntimeException('No se pudo actualizar.'); message('success','Estado actualizado.'); }
    } catch(Throwable $e) { message('error',$e->getMessage()); }
}

$cfgPath=nexoraVoteConfigPath($realm); $cfgXml=simplexml_load_file($cfgPath); $cfg=$cfgXml?convertXML($cfgXml):array();
$creditSystem=new CreditSystem();
function vcfg($cfg,$key,$default){ return isset($cfg[$key])?$cfg[$key]:$default; }
?>
<div class="alert alert-info"><strong>Modelo v2:</strong> los sitios entregan Vote Points. Los creditos solo se generan al convertir puntos y pasar los controles Anti-Farm.</div>
<p><strong>Contexto actual:</strong> <?php echo htmlspecialchars(ucfirst($realm),ENT_QUOTES,'UTF-8'); ?>. La configuracion es independiente por reino.</p>
<form action="index.php?module=modules_manager&config=vote" method="post">
<table class="table table-striped table-bordered table-hover module_config_tables">
<tr><th colspan="2">General</th></tr>
<tr><th>Status</th><td><?php enabledisableCheckboxes('setting_1',vcfg($cfg,'active',0),'Enabled','Disabled'); ?></td></tr>
<tr><th>Historial de seguridad</th><td><strong>Enabled (obligatorio)</strong><input type="hidden" name="setting_2" value="1"><br><small>Anti-Farm necesita este registro para limitar IP y dispositivo.</small></td></tr>
<tr><th>Moneda de conversion</th><td><?php echo $creditSystem->buildSelectInput('setting_3',vcfg($cfg,'credit_config',0),'form-control'); ?></td></tr>
<tr><th colspan="2">Requisitos de cuenta</th></tr>
<tr><th>Antiguedad minima</th><td><input class="form-control" type="number" min="0" name="min_account_days" value="<?php echo (int)vcfg($cfg,'antifarm_min_account_days',5); ?>"> dias</td></tr>
<tr><th>Nivel minimo</th><td><input class="form-control" type="number" min="0" name="min_level" value="<?php echo (int)vcfg($cfg,'antifarm_min_level',400); ?>"></td></tr>
<tr><th>Resets minimos</th><td><input class="form-control" type="number" min="0" name="min_resets" value="<?php echo (int)vcfg($cfg,'antifarm_min_resets',5); ?>"></td></tr>
<tr><th>Master Level minimo</th><td><input class="form-control" type="number" min="0" name="min_master_level" value="<?php echo (int)vcfg($cfg,'antifarm_min_master_level',0); ?>"></td></tr>
<tr><th>Horas jugadas minimas</th><td><input class="form-control" type="number" min="0" name="min_online_hours" value="<?php echo (int)vcfg($cfg,'antifarm_min_online_hours',5); ?>"></td></tr>
<tr><th colspan="2">Dispositivo y red</th></tr>
<tr><th>Confianza del dispositivo</th><td><input class="form-control" type="number" min="0" name="device_trust_hours" value="<?php echo (int)vcfg($cfg,'antifarm_device_trust_hours',24); ?>"> horas antes de convertir WCoin. Votar sigue permitido.</td></tr>
<tr><th>Max. cuentas por IP / 24h</th><td><input class="form-control" type="number" min="0" name="max_accounts_ip" value="<?php echo (int)vcfg($cfg,'antifarm_max_accounts_ip_24h',2); ?>"> 0 = sin limite.</td></tr>
<tr><th>Max. cuentas por dispositivo / 24h</th><td><input class="form-control" type="number" min="0" name="max_accounts_device" value="<?php echo (int)vcfg($cfg,'antifarm_max_accounts_device_24h',1); ?>"> Recomendado: 1.</td></tr>
<tr><th colspan="2">Conversion Vote Points -> creditos</th></tr>
<tr><th>Puntos requeridos</th><td><input class="form-control" type="number" min="1" name="points_per_conversion" value="<?php echo (int)vcfg($cfg,'antifarm_points_per_conversion',10); ?>"></td></tr>
<tr><th>Creditos entregados</th><td><input class="form-control" type="number" min="1" name="credits_per_conversion" value="<?php echo (int)vcfg($cfg,'antifarm_credits_per_conversion',10); ?>"></td></tr>
<tr><th>Tope diario por cuenta</th><td><input class="form-control" type="number" min="0" name="daily_user_cap" value="<?php echo (int)vcfg($cfg,'antifarm_daily_user_credit_cap',20); ?>"> creditos. 0 = sin limite.</td></tr>
<tr><th>Tope diario por dispositivo</th><td><input class="form-control" type="number" min="0" name="daily_device_cap" value="<?php echo (int)vcfg($cfg,'antifarm_daily_device_credit_cap',20); ?>"> creditos.</td></tr>
<tr><th>Tope diario por IP</th><td><input class="form-control" type="number" min="0" name="daily_ip_cap" value="<?php echo (int)vcfg($cfg,'antifarm_daily_ip_credit_cap',40); ?>"> creditos.</td></tr>
<tr><td colspan="2"><input type="submit" name="submit_changes" value="Guardar cambios" class="btn btn-success"></td></tr>
</table></form>
<hr><h3>Sitios de votacion - <?php echo htmlspecialchars(ucfirst($realm),ENT_QUOTES,'UTF-8'); ?></h3>
<p>La columna Recompensa ahora significa <strong>Vote Points</strong>, no WCoin directo.</p>
<table class="table table-striped table-bordered table-hover"><tr><th>Nombre</th><th>URL</th><th>Vote Points</th><th>Cooldown</th><th>Estado</th><th>Acciones</th></tr>
<?php foreach($vote->retrieveVotesites() as $site) { ?>
<tr><td><?php echo htmlspecialchars($site['votesite_title'],ENT_QUOTES,'UTF-8'); ?></td><td><?php echo htmlspecialchars($site['votesite_link'],ENT_QUOTES,'UTF-8'); ?></td><td><?php echo (int)$site['votesite_reward']; ?></td><td><?php echo (int)$site['votesite_time']; ?> h</td><td><?php echo !empty($site['enabled'])?'Activo':'Pausado'; ?></td><td>
<form method="post" style="display:inline"><input type="hidden" name="site_id" value="<?php echo (int)$site['votesite_id']; ?>"><button class="btn btn-sm" name="site_action" value="<?php echo !empty($site['enabled'])?'disable':'enable'; ?>"><?php echo !empty($site['enabled'])?'Pausar':'Activar'; ?></button></form>
<form method="post" style="display:inline" onsubmit="return confirm('Eliminar este sitio?');"><input type="hidden" name="site_id" value="<?php echo (int)$site['votesite_id']; ?>"><button class="btn btn-danger btn-sm" name="site_action" value="delete">Eliminar</button></form>
</td></tr><?php } ?>
<form action="index.php?module=modules_manager&config=vote" method="post"><tr><td><input name="votesite_add_title" class="form-control" required></td><td><input name="votesite_add_link" class="form-control" type="url" required></td><td><input name="votesite_add_reward" class="form-control" type="number" min="1" value="1" required></td><td><input name="votesite_add_time" class="form-control" type="number" min="1" value="12" required> h</td><td>Activo</td><td><button type="submit" name="votesite_add_submit" value="1" class="btn btn-success">Agregar</button></td></tr></form>
</table>
<hr><h3>Eventos Anti-Farm recientes</h3>
<table class="table table-condensed table-hover"><tr><th>Fecha</th><th>Cuenta</th><th>Evento</th><th>IP</th><th>Detalle</th></tr>
<?php foreach($vote->recentSecurityEvents(50) as $event) { ?><tr>
<td><?php echo htmlspecialchars((string)$event['created_at'],ENT_QUOTES,'UTF-8'); ?></td>
<td><?php echo htmlspecialchars((string)$event['account_username'],ENT_QUOTES,'UTF-8'); ?></td>
<td><?php echo htmlspecialchars((string)$event['event_type'],ENT_QUOTES,'UTF-8'); ?></td>
<td><?php echo htmlspecialchars((string)$event['user_ip'],ENT_QUOTES,'UTF-8'); ?></td>
<td><?php echo htmlspecialchars((string)$event['detail'],ENT_QUOTES,'UTF-8'); ?></td>
</tr><?php } ?></table>
