<?php
if(!isLoggedIn()) redirect(1,'login');
echo '<div class="page-title"><span>'.lang('module_titles_txt_7',true).'</span></div>';
try {
    if(!mconfig('active')) throw new Exception(lang('error_47',true));
    $vote=new Vote();
    $vote->setUserid($_SESSION['userid']);
    $clientIp=class_exists('NexoraSecurity')?NexoraSecurity::clientIp():$_SERVER['REMOTE_ADDR'];
    $vote->setIp($clientIp);

    if(isset($_POST['vote_claim'])) {
        $vote->setVotesiteId($_POST['voting_site_id']??null);
        $vote->vote();
    }
    if(isset($_POST['convert_vote_points'])) {
        $converted=$vote->convertPoints();
        message('success','Conversion completada: +'.(int)$converted['credits_granted'].' creditos. Saldo de Vote Points: '.(int)$converted['points_balance'].'.');
    }

    $wallet=$vote->walletSummary();
    $eligibility=$vote->eligibility(false);
    $conversionEligibility=$vote->eligibility(true);
    echo '<div class="alert alert-info"><strong>Vote Points Nexora</strong><br>';
    echo 'Votar genera puntos. Los creditos se entregan solo al convertirlos, sujetos a controles Anti-Farm del reino activo.</div>';
    echo '<div class="row">';
    echo '<div class="col-md-6"><div class="panel panel-default"><div class="panel-heading"><strong>Mi saldo</strong></div><div class="panel-body">';
    echo '<p style="font-size:24px;margin:0 0 10px"><strong>'.(int)$wallet['points'].' Vote Points</strong></p>';
    echo '<p>'.(int)$wallet['points_per_conversion'].' puntos = '.(int)$wallet['credits_per_conversion'].' creditos.</p>';
    echo '<form method="post"><button type="submit" name="convert_vote_points" value="1" class="btn btn-success"'.((empty($wallet['can_convert'])||empty($conversionEligibility['eligible']))?' disabled':'').'>Convertir puntos</button></form>';
    if(empty($conversionEligibility['eligible'])) echo '<p class="text-muted" style="margin-top:10px">Conversion pendiente: '.htmlspecialchars(implode(' / ',$conversionEligibility['reasons']),ENT_QUOTES,'UTF-8').'</p>';
    echo '</div></div></div>';
    echo '<div class="col-md-6"><div class="panel panel-default"><div class="panel-heading"><strong>Proteccion economica</strong></div><div class="panel-body">';
    echo '<p>Antiguedad: '.(int)$eligibility['account_age_days'].' dias | Dispositivo: '.(int)$eligibility['device_age_hours'].' h</p>';
    echo '<p>Nivel: '.(int)$eligibility['stats']['level'].' | Resets: '.(int)$eligibility['stats']['resets'].' | Master Level: '.(int)$eligibility['stats']['master_level'].' | Horas: '.(int)$eligibility['stats']['online_hours'].'</p>';
    if(!empty($wallet['daily_user_cap'])) echo '<p>Limite diario de cuenta: '.(int)$wallet['today_user_credits'].' / '.(int)$wallet['daily_user_cap'].' creditos</p>';
    echo '</div></div></div></div>';

    echo '<table class="table general-table-ui"><tr><td>Sitio</td><td>Vote Points</td><td>Accion</td></tr>';
    foreach($vote->retrieveVotesites() as $site) {
        if(empty($site['enabled'])) continue;
        $availability=$vote->availability($site['votesite_id'],$_SESSION['userid'],$clientIp);
        $url=$vote->getVoteUrl($site['votesite_id']);
        $voteHost=$url!=='' ? strtolower((string)parse_url($url,PHP_URL_HOST)) : '';
        $isXtremeTop100=($voteHost==='xtremetop100.com' || $voteHost==='www.xtremetop100.com' || substr($voteHost,-17)==='.xtremetop100.com');
        echo '<tr><td>'.htmlspecialchars($site['votesite_title'],ENT_QUOTES,'UTF-8').'</td><td>+'.(int)$site['votesite_reward'].'</td><td>';
        if(!empty($eligibility['eligible']) && $availability['available']) {
            if($isXtremeTop100) {
                echo '<form action="" method="post" style="display:inline-block;margin:0">';
                echo '<input type="hidden" name="voting_site_id" value="'.(int)$site['votesite_id'].'">';
                echo '<button type="submit" name="vote_claim" value="1" title="Votar por MU Nexora en XtremeTop100" aria-label="Votar por MU Nexora en XtremeTop100" style="padding:0;margin:0;border:0;background:transparent;cursor:pointer;line-height:0;vertical-align:middle">';
                echo '<img src="https://www.xtremetop100.com/votenew.jpg" alt="Vote for MU Nexora on XtremeTop100" style="display:block;max-width:100%;height:auto;border:0;border-radius:5px">';
                echo '</button></form>';
            } else {
                echo '<form action="" method="post" style="display:inline"><input type="hidden" name="voting_site_id" value="'.(int)$site['votesite_id'].'"><button type="submit" name="vote_claim" value="1" class="btn btn-primary">Votar y sumar puntos</button></form>';
            }
        } elseif(!$availability['available']) {
            echo '<button type="button" class="btn btn-default" disabled>Disponible en '.gmdate('H:i:s',$availability['remaining']).'</button>';
        } else {
            echo '<button type="button" class="btn btn-default" disabled>Sin recompensa</button>';
            if($url!=='') echo ' <a class="btn btn-link" href="'.htmlspecialchars($url,ENT_QUOTES,'UTF-8').'" rel="noopener noreferrer">Votar igualmente</a>';
        }
        echo '</td></tr>';
    }
    echo '</table>';
    if(empty($eligibility['eligible'])) message('warning','Para recibir Vote Points necesitas: '.implode(' / ',$eligibility['reasons']).'. Puedes seguir votando sin recompensa mientras completas los requisitos.');
} catch(Exception $ex) { message('error',$ex->getMessage()); }
