<?php
if(!isLoggedIn()) redirect(1,'login');
$pageTitle='Votar por créditos';
try {
    if(!mconfig('active')) throw new Exception(lang('error_47',true));
    $vote=new Vote();
    $clientIp=class_exists('NexoraSecurity')?NexoraSecurity::clientIp():($_SERVER['REMOTE_ADDR']??'0.0.0.0');
    if(isset($_POST['submit'])) {
        $vote->setUserid($_SESSION['userid']);
        $vote->setIp($clientIp);
        $vote->setVotesiteId($_POST['voting_site_id']??null);
        $vote->vote();
    }
    echo '<div class="nexora-usercp-page">';
    echo '<header class="nexora-usercp-page-header"><h1 class="nexora-usercp-page-title">'.$pageTitle.'</h1><p class="nexora-usercp-page-subtitle">'.htmlspecialchars(ucfirst($vote->getRealm()),ENT_QUOTES,'UTF-8').' · Cada sitio mantiene su propio cooldown.</p></header>';
    echo '<div class="nexora-usercp-panel"><div class="nexora-usercp-panel-body"><div class="nexora-usercp-table-wrap">';
    echo '<table class="nexora-usercp-table"><thead><tr><th>Sitio</th><th>Recompensa</th><th>Estado</th></tr></thead><tbody>';
    $sites=$vote->retrieveVotesites();
    if(!$sites) echo '<tr><td colspan="3">No hay sitios de votación configurados para este reino.</td></tr>';
    foreach($sites as $site) {
        if(empty($site['enabled'])) continue;
        $availability=$vote->availability($site['votesite_id'],$_SESSION['userid'],$clientIp);
        echo '<tr><td>'.htmlspecialchars($site['votesite_title'],ENT_QUOTES,'UTF-8').'</td><td><strong>+'.(int)$site['votesite_reward'].'</strong> créditos</td><td>';
        if($availability['available']) {
            echo '<form action="" method="post" style="margin:0"><input type="hidden" name="voting_site_id" value="'.(int)$site['votesite_id'].'"><button type="submit" name="submit" value="1" class="nexora-usercp-btn" data-nexora-submit-label="Abriendo...">VOTAR</button></form>';
        } else {
            $h=floor($availability['remaining']/3600); $m=floor(($availability['remaining']%3600)/60);
            echo '<span class="nexora-usercp-badge">Disponible en '.sprintf('%02dh %02dm',$h,$m).'</span>';
        }
        echo '</td></tr>';
    }
    echo '</tbody></table></div>';
    echo '<div class="nexora-usercp-note" style="margin-top:16px">La recompensa y el cooldown se registran juntos. Si el proceso falla, no pierdes la oportunidad de votar.</div>';
    echo '</div></div></div>';
} catch(Exception $ex) { message('error',$ex->getMessage()); }
