<?php
/**
 * Encuesta - Voting and Results Display
 * Original: 2006 Martin Schenk
 * Modernized: 21.01.2026 (Modern UI, animated bars, responsive)
 */
@session_start();

require_once("ppconfig.php");
require_once("sql-connect.php");

if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $_SERVER['HTTP_ACCEPT_LANGUAGE']="";

if(!isset($_SESSION['idiom'])){
    if( isset($_REQUEST['idiom']) && ($_REQUEST['idiom'] == "es"
                                        || $_REQUEST['idiom'] == "en"
                                        || $_REQUEST['idiom'] == "de")
        ){
        $_SESSION['idiom'] = $_REQUEST['idiom'];

    }elseif( substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) == 'es'){
        $_SESSION['idiom'] = "es";
    }elseif( substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) == 'de'){
        $_SESSION['idiom'] = "de";
    }elseif( substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) == 'en'){
        $_SESSION['idiom'] = "en";
    }else{
        $_SESSION['idiom'] = "en";
    }
}

// Mehrsprachigkeit Palimpalem
require($ppApliDirAbs."idiom/ppidiom.php");

// Get page background COLOR from form submission (simplified - only color, no images)
$pageBgColor = isset($_POST['pp_bg_color']) ? htmlspecialchars($_POST['pp_bg_color'], ENT_QUOTES, 'UTF-8') : '';

// Get encuesta design from submission (for consistent card styling)
$designColorfondo = isset($_POST['pp_design_colorfondo']) ? htmlspecialchars($_POST['pp_design_colorfondo'], ENT_QUOTES, 'UTF-8') : '';
$designColormarco = isset($_POST['pp_design_colormarco']) ? htmlspecialchars($_POST['pp_design_colormarco'], ENT_QUOTES, 'UTF-8') : '';
$designColortextopreg = isset($_POST['pp_design_colortextopreg']) ? htmlspecialchars($_POST['pp_design_colortextopreg'], ENT_QUOTES, 'UTF-8') : '';
$designColortextoresp = isset($_POST['pp_design_colortextoresp']) ? htmlspecialchars($_POST['pp_design_colortextoresp'], ENT_QUOTES, 'UTF-8') : '';
$designFontn = isset($_POST['pp_design_fontn']) ? htmlspecialchars($_POST['pp_design_fontn'], ENT_QUOTES, 'UTF-8') : '';
$designFonts = isset($_POST['pp_design_fonts']) ? htmlspecialchars($_POST['pp_design_fonts'], ENT_QUOTES, 'UTF-8') : '';
$designRahmenart = isset($_POST['pp_design_rahmenart']) ? htmlspecialchars($_POST['pp_design_rahmenart'], ENT_QUOTES, 'UTF-8') : '';
$designRahmendicke = isset($_POST['pp_design_rahmendicke']) ? htmlspecialchars($_POST['pp_design_rahmendicke'], ENT_QUOTES, 'UTF-8') : '';
$designBorderradius = isset($_POST['pp_design_borderradius']) ? htmlspecialchars($_POST['pp_design_borderradius'], ENT_QUOTES, 'UTF-8') : '';
$designBoxshadow = isset($_POST['pp_design_boxshadow']) ? htmlspecialchars($_POST['pp_design_boxshadow'], ENT_QUOTES, 'UTF-8') : '';
$designButtonbg = isset($_POST['pp_design_buttonbg']) ? htmlspecialchars($_POST['pp_design_buttonbg'], ENT_QUOTES, 'UTF-8') : '';
$designButtontext = isset($_POST['pp_design_buttontext']) ? htmlspecialchars($_POST['pp_design_buttontext'], ENT_QUOTES, 'UTF-8') : '';
$designButtonborder = isset($_POST['pp_design_buttonborder']) ? htmlspecialchars($_POST['pp_design_buttonborder'], ENT_QUOTES, 'UTF-8') : '';
$designButtonbordercolor = isset($_POST['pp_design_buttonbordercolor']) ? htmlspecialchars($_POST['pp_design_buttonbordercolor'], ENT_QUOTES, 'UTF-8') : '';

// Check if we have custom design
$hasCustomDesign = !empty($designColorfondo);

// Build background CSS (simplified - only color)
$bodyBgStyle = '';
if ($pageBgColor && $pageBgColor !== '#ffffff' && $pageBgColor !== 'transparent') {
    $bodyBgStyle = 'background-color: ' . $pageBgColor . '; ';
} else {
    // Fallback: light gradient
    $bodyBgStyle = 'background: linear-gradient(135deg, #f0fff4 0%, #fffff8 100%); ';
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['idiom']; ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo __("Palimpalem - resultado Encuesta");?></title>
    <!-- Chart.js for beautiful charts -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <style>
    /* ==========================================
       PALIMPALEM ENCUESTA RESULTS - MODERN UI
       ========================================== */
    * {
        box-sizing: border-box;
    }
    body {
        margin: 0;
        padding: 20px;
        font-family: Arial, sans-serif;
        <?php echo $bodyBgStyle; ?>
        min-height: 100vh;
    }
    .encu-container {
        max-width: 600px;
        margin: 0 auto;
    }

    /* Back Button */
    .encu-back-btn {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        <?php if ($hasCustomDesign): ?>
        background: <?php echo $designButtonbg; ?>;
        border: <?php echo $designButtonborder; ?>px solid <?php echo $designButtonbordercolor; ?>;
        color: <?php echo $designButtontext; ?>;
        border-radius: <?php echo $designBorderradius; ?>px;
        font-family: <?php echo $designFontn; ?>, sans-serif;
        font-size: <?php echo $designFonts; ?>;
        <?php else: ?>
        background: white;
        border: 2px solid #5B8C50;
        color: #464646;
        border-radius: 8px;
        font-size: 14px;
        <?php endif; ?>
        padding: 10px 20px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        text-decoration: none;
        margin-bottom: 24px;
    }
    .encu-back-btn:hover {
        <?php if ($hasCustomDesign): ?>
        opacity: 0.9;
        <?php else: ?>
        background: #5B8C50;
        color: white;
        <?php endif; ?>
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(149, 242, 125, 0.4);
    }
    .encu-back-btn svg {
        width: 18px;
        height: 18px;
    }

    /* Warning Message */
    .encu-warning {
        background: linear-gradient(135deg, #fff1f2 0%, #ffe4e6 100%);
        border: 2px solid #fb7185;
        border-radius: 12px;
        padding: 16px 20px;
        margin-bottom: 24px;
        display: flex;
        align-items: flex-start;
        gap: 12px;
    }
    .encu-warning-icon {
        width: 24px;
        height: 24px;
        background: #ff3366;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 14px;
        flex-shrink: 0;
    }
    .encu-warning-text {
        font-size: 14px;
        color: #881337;
        line-height: 1.5;
    }
    .encu-warning-text b {
        color: #ff3366;
    }

    /* Results Title */
    .encu-title {
        text-align: center;
        font-size: 18px;
        color: #464646;
        margin-bottom: 20px;
        font-weight: 600;
    }
    .encu-title-icon {
        display: inline-block;
        margin-right: 8px;
    }

    /* Results Card */
    .encu-results-card {
        <?php if ($hasCustomDesign): ?>
        background: <?php echo $designColorfondo; ?>;
        border: <?php echo $designRahmendicke . ' ' . $designRahmenart . ' ' . $designColormarco; ?>;
        border-radius: <?php echo $designBorderradius; ?>px;
        box-shadow: <?php echo $designBoxshadow; ?>;
        font-family: <?php echo $designFontn; ?>, sans-serif;
        color: <?php echo $designColortextoresp; ?>;
        <?php else: ?>
        background: white;
        border-radius: 16px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        <?php endif; ?>
        overflow: hidden;
    }
    .encu-question {
        padding: 20px 24px;
        text-align: center;
        font-weight: bold;
        line-height: 1.4;
        <?php if ($hasCustomDesign): ?>
        color: <?php echo $designColortextopreg; ?>;
        font-size: <?php echo $designFonts; ?>;
        <?php endif; ?>
    }
    .encu-answers {
        padding: 0 24px 24px 24px;
    }
    .encu-answer-row {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 0;
        <?php if ($hasCustomDesign): ?>
        border-bottom: 1px solid <?php echo $designColormarco; ?>40;
        <?php else: ?>
        border-bottom: 1px solid #f0f0f0;
        <?php endif; ?>
    }
    .encu-answer-row:last-child {
        border-bottom: none;
    }
    .encu-answer-text {
        flex: 1;
        min-width: 0;
        <?php if ($hasCustomDesign): ?>
        font-size: <?php echo $designFonts; ?>;
        color: <?php echo $designColortextoresp; ?>;
        <?php else: ?>
        font-size: 14px;
        <?php endif; ?>
        word-break: break-word;
    }
    .encu-answer-votes {
        font-size: 14px;
        font-weight: 600;
        min-width: 30px;
        text-align: right;
    }
    .encu-answer-bar-container {
        width: 120px;
        height: 24px;
        background: #f0f0f0;
        border-radius: 12px;
        overflow: hidden;
        flex-shrink: 0;
    }
    .encu-answer-bar {
        height: 100%;
        border-radius: 12px;
        transition: width 1s ease-out;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: 8px;
        min-width: 0;
    }
    .encu-answer-bar.winner {
        animation: pulse 2s ease-in-out infinite;
    }
    @keyframes pulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.8; }
    }
    .encu-answer-percent {
        font-size: 12px;
        font-weight: 700;
        color: white;
        text-shadow: 0 1px 2px rgba(0,0,0,0.2);
        white-space: nowrap;
    }
    .encu-answer-percent-outside {
        font-size: 12px;
        font-weight: 600;
        color: #888;
        min-width: 40px;
        text-align: right;
    }

    /* Total */
    .encu-total {
        padding: 16px 24px;
        text-align: center;
        font-weight: 600;
        border-top: 2px solid #f0f0f0;
    }
    .encu-total-number {
        font-size: 24px;
        font-weight: 700;
    }
    .encu-total-label {
        font-size: 12px;
        color: #888;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    /* Footer */
    .encu-footer {
        text-align: center;
        margin-top: 32px;
        padding: 20px;
    }
    .encu-footer-logo {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        color: #5B8C50;
        font-weight: 600;
        font-size: 14px;
        text-decoration: none;
        transition: all 0.2s;
    }
    .encu-footer-logo:hover {
        color: #4A7A40;
        transform: scale(1.05);
    }
    .encu-footer-logo svg {
        width: 24px;
        height: 24px;
    }

    /* Error Page */
    .encu-error {
        text-align: center;
        padding: 40px 20px;
    }
    .encu-error-icon {
        width: 64px;
        height: 64px;
        background: linear-gradient(135deg, #ff3366 0%, #ff6699 100%);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px auto;
        color: white;
        font-size: 32px;
        font-weight: bold;
    }
    .encu-error-title {
        font-size: 24px;
        color: #ff3366;
        margin-bottom: 12px;
    }
    .encu-error-text {
        font-size: 14px;
        color: #666;
        line-height: 1.6;
    }

    /* Chart Container */
    .encu-chart-container {
        padding: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .encu-chart-canvas {
        max-width: 100%;
        max-height: 300px;
    }
    .encu-chart-legend {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 12px;
        padding: 16px 20px;
        border-top: 1px solid #f0f0f0;
    }
    .encu-legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
    }
    .encu-legend-color {
        width: 12px;
        height: 12px;
        border-radius: 2px;
    }

    /* Responsive */
    @media (max-width: 500px) {
        body {
            padding: 12px;
        }
        .encu-answer-bar-container {
            width: 80px;
        }
        .encu-answer-row {
            flex-wrap: wrap;
        }
        .encu-answer-text {
            width: 100%;
            margin-bottom: 8px;
        }
        .encu-chart-canvas {
            max-height: 250px;
        }
    }
    </style>
</head>
<body>
<div class="encu-container">

<?php

// ===== HANDLE GET REQUEST (Direct link to results) =====
if(isset($_GET['encucode'])){
    $encucode = $_GET['encucode'];
    if (settype($encucode,"integer") == true){
        if (strlen($encucode) == 9){
            encugrafik($encucode, "");
        }else{
            mostrarError(__("La encuesta no existe o ha sido eliminada."));
        }
    }else{
        mostrarError(__("La encuesta no existe o ha sido eliminada."));
    }
}

// ===== HANDLE POST REQUEST (Vote submission) =====
if (isset($_POST['submitButton'])){

    // ============================================================
    // ANTI-SPAM CHECKS (Added 31.01.2026)
    // ============================================================
    $isSpam = false;

    // Check 1: Honeypot field - must be empty (bots fill hidden fields)
    if (!empty($_POST['pp_website_url'])) {
        error_log("SPAM blocked (encuesta): Honeypot field filled. IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        $isSpam = true;
    }

    // Check 2: Timestamp - form must be open for at least 2 seconds
    $encuTs = intval($_POST['pp_encu_ts'] ?? 0);
    $nowTs = round(microtime(true) * 1000);
    $timeDiff = $nowTs - $encuTs;
    if ($encuTs > 0 && $timeDiff < 2000) { // Less than 2 seconds
        error_log("SPAM blocked (encuesta): Vote submitted too fast ({$timeDiff}ms). IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
        $isSpam = true;
    }

    if ($isSpam) {
        // Silently ignore spam - show generic error
        mostrarError(__("No se puede mostrar el resultado de la encuesta."));
        exit;
    }
    // ============================================================
    // END ANTI-SPAM CHECKS
    // ============================================================

    if (isset($_POST['antwort'])){
        reset($_POST['antwort']);
        $resparray = array();
        foreach ($_POST['antwort'] as $respnr => $respuesta){
            $resparray[$respnr] = $respuesta;
        }

        if(count($resparray) == 1){
            $antwort = $resparray[0];
            $encucode = substr($antwort,0,9);

            if (settype($encucode,"integer") == true){
                if (strlen($encucode) == 9){
                    $orden = substr($antwort,19);

                    if (settype($orden,"integer") == true){

                        // Check if encucode exists in ppencu1 and get sperrzeit
                        $sql = "SELECT encucode, sperrzeit FROM ppencu1 WHERE encucode = '".$encucode."' ";
                        $result = mysqli_query($conid, $sql);

                        if (mysqli_num_rows($result) == 1){
                            $row = mysqli_fetch_assoc($result);
                            $sperrzeit = $row['sperrzeit'];

                            // Check if encucode exists in ppencu2
                            $sql = "SELECT encucode FROM ppencu2 WHERE encucode = '".$encucode."' ";
                            $result = mysqli_query($conid, $sql);

                            if (mysqli_num_rows($result) >= 2){
                                // Clean old votes from ppencuip
                                $zeitraum = time() - $sperrzeit;
                                $sql = "DELETE FROM ppencuip WHERE encucode = '".$encucode."' AND abgestimmt <= '$zeitraum'";
                                mysqli_query($conid, $sql);

                                // Check if user already voted
                                $safe_ip = mysqli_real_escape_string($conid, $_SERVER['REMOTE_ADDR']);
                                $BereitsAbgestimmt = mysqli_num_rows(mysqli_query($conid,
                                    "SELECT counter FROM ppencuip WHERE encucode = '".$encucode."' AND ip='".$safe_ip."'")) > 0;

                                if ($BereitsAbgestimmt){
                                    // Convert sperrzeit to readable format
                                    $sperrwort = convertirSperrzeit($sperrzeit);
                                    $TextBereitsAbgestimmt = '<div class="encu-warning">
                                        <div class="encu-warning-icon">!</div>
                                        <div class="encu-warning-text">'.__("Voto no válido.").'<br>'.__("Se puede votar").' <b>'.__("una vez").'</b> '.__("cada").' <b>'.$sperrwort.'</b>.</div>
                                    </div>';
                                    encugrafik($encucode, $TextBereitsAbgestimmt);

                                }else{
                                    // Update vote count
                                    $sql = "UPDATE ppencu2 SET votos = votos+1 WHERE encucode = '".$encucode."' AND orden = '".$orden."'";

                                    if($result = mysqli_query($conid, $sql)){
                                        if(mysqli_affected_rows($conid) == 1){
                                            // Record user's IP
                                            mysqli_query($conid,"INSERT INTO ppencuip (abgestimmt, ip, encucode) VALUES ('".time()."', '".$safe_ip."', '".$encucode."')");
                                            encugrafik($encucode, "");
                                        }else{
                                            mostrarError(__("No se puede mostrar el resultado de la encuesta."));
                                        }
                                    }else{
                                        mostrarError(__("No se puede mostrar el resultado de la encuesta."));
                                    }
                                }
                            }else{
                                mostrarError(__("La encuesta no existe o ha sido eliminada."));
                            }
                        }else{
                            mostrarError(__("La encuesta no existe o ha sido eliminada."));
                        }
                    }else{
                        mostrarError(__("No se puede mostrar el resultado de la encuesta."));
                    }
                }else{
                    mostrarError(__("No se puede mostrar el resultado de la encuesta."));
                }
            }else{
                mostrarError(__("No se puede mostrar el resultado de la encuesta."));
            }
        }else{
            mostrarError(__("No se puede mostrar el resultado de la encuesta."));
        }
    }else{
        // User forgot to select an answer
        ?>
        <button type="button" class="encu-back-btn" onclick="history.go(-1)">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
            <?php echo __("Volver");?>
        </button>

        <div class="encu-error">
            <div class="encu-error-icon">?</div>
            <div class="encu-error-title">Uups...</div>
            <div class="encu-error-text">
                <?php echo __("Has <b>olvidado votar</b>.");?><br><br>
                <?php echo __("Para votar, pincha uno de los círculos a la derecha de las respuestas.");?>
            </div>
        </div>
        <?php
    }
}

// ===== FUNCTION: Convert sperrzeit to readable text =====
function convertirSperrzeit($sperrzeit) {
    $map = [
        10 => __("10 Segundos"),
        30 => __("30 Segundos"),
        60 => __("1 Minuto"),
        1800 => __("30 Minutos"),
        3600 => __("1 Hora"),
        43200 => __("12 Horas"),
        86400 => __("1 Día"),
        172800 => __("2 Días"),
        604800 => __("1 Semana"),
        1209600 => __("2 Semanas"),
        2592000 => __("1 Mes"),
        5184000 => __("2 Meses"),
        15552000 => __("6 Meses"),
        31104000 => __("1 Año")
    ];
    return isset($map[$sperrzeit]) ? $map[$sperrzeit] : __("un tiempo");
}

// ===== FUNCTION: Display Results =====
function encugrafik($encucode, $textba){
    global $ppApliDirAbs;
    include("ppconfig.php");
    include("sql-connect.php");

    // Load ppencu1 data
    $sql1 = "SELECT * FROM ppencu1 WHERE encucode = '".$encucode."' ";
    $result1 = mysqli_query($conid, $sql1);

    if (!$result1 || mysqli_num_rows($result1) != 1){
        mostrarError(__("La encuesta no existe o ha sido eliminada."));
        return;
    }

    $row1 = mysqli_fetch_assoc($result1);

    // Load ppencu2 data (answers)
    $sql2 = "SELECT * FROM ppencu2 WHERE encucode = '".$encucode."' ORDER BY orden ASC";
    $result2 = mysqli_query($conid, $sql2);

    if (!$result2 || mysqli_num_rows($result2) < 2){
        mostrarError(__("La encuesta no existe o ha sido eliminada."));
        return;
    }

    // Calculate totals
    $votostotal = 0;
    $maxwert = 0;
    $answers = [];

    while ($row2 = mysqli_fetch_assoc($result2)) {
        $answers[] = $row2;
        $votostotal += $row2['votos'];
        if ($row2['votos'] > $maxwert) $maxwert = $row2['votos'];
    }

    // Design values from stored encuesta
    $colorfondo = $row1['colorfondo'] ?: '#ffffcc';
    $colormarco = $row1['colormarco'] ?: '#5B8C50';
    $colortextopreg = $row1['colortextopreg'] ?: '#ff3366';
    $colortextoresp = $row1['colortextoresp'] ?: '#464646';
    $fontn = $row1['fontn'] ?: 'Arial';
    $fonts = $row1['fonts'] ?: '14px';
    $rahmendicke = $row1['rahmendicke'] ?: '2px';
    $rahmenart = $row1['rahmenart'] ?: 'solid';

    // Chart type (bar = horizontal bars, donut = pie/donut, vertical = vertical bars)
    $chartType = $row1['chart_type'] ?? 'bar';

    // Process question for line breaks
    $pregunta = $row1['pregunta'];
    if (strlen($pregunta) > 40){
        $pregunta = wordwrap($pregunta, 40, "<br>", true);
    }
    ?>

    <button type="button" class="encu-back-btn" onclick="history.go(-1)">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
        <?php echo __("Volver");?>
    </button>

    <?php echo $textba; ?>

    <div class="encu-title">
        <span class="encu-title-icon">📊</span>
        <?php echo __("Resultado actual de la Encuesta");?>
    </div>

    <div class="encu-results-card" style="border: <?php echo $rahmendicke.' '.$rahmenart.' '.$colormarco; ?>; border-radius: 16px;">

        <!-- Question -->
        <div class="encu-question" style="background: <?php echo $colorfondo; ?>; color: <?php echo $colortextopreg; ?>; font-family: <?php echo $fontn; ?>, Arial, sans-serif; font-size: <?php echo $fonts; ?>;">
            <?php echo $pregunta; ?>
        </div>

        <!-- Answers / Chart -->
        <?php if ($chartType === 'donut' || $chartType === 'vertical'): ?>
        <!-- Chart.js visualization -->
        <div class="encu-chart-container" style="background: <?php echo $colorfondo; ?>;">
            <canvas id="encuestaChart" class="encu-chart-canvas"></canvas>
        </div>
        <div class="encu-chart-legend" style="background: <?php echo $colorfondo; ?>; font-family: <?php echo $fontn; ?>, Arial, sans-serif;">
            <?php
            // Generate colors for each answer
            $chartColors = ['#ff6384', '#36a2eb', '#ffce56', '#4bc0c0', '#9966ff', '#ff9f40', '#c9cbcf', '#7bc043', '#ee4035', '#0392cf'];
            foreach ($answers as $i => $answer):
                $respuesta = $answer['respuesta'];
                $votos = $answer['votos'];
                $percent = $votostotal > 0 ? round(($votos / $votostotal) * 100) : 0;
                $color = $chartColors[$i % count($chartColors)];
            ?>
            <div class="encu-legend-item">
                <span class="encu-legend-color" style="background: <?php echo $color; ?>;"></span>
                <span style="color: <?php echo $colortextoresp; ?>; font-size: <?php echo $fonts; ?>;">
                    <?php echo htmlspecialchars($respuesta); ?> (<?php echo $votos; ?> - <?php echo $percent; ?>%)
                </span>
            </div>
            <?php endforeach; ?>
        </div>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            var ctx = document.getElementById('encuestaChart').getContext('2d');
            var chartType = '<?php echo $chartType === 'donut' ? 'doughnut' : 'bar'; ?>';
            var chartData = {
                labels: [<?php echo implode(',', array_map(function($a) { return "'" . addslashes($a['respuesta']) . "'"; }, $answers)); ?>],
                datasets: [{
                    data: [<?php echo implode(',', array_column($answers, 'votos')); ?>],
                    backgroundColor: [<?php echo "'" . implode("','", array_slice($chartColors, 0, count($answers))) . "'"; ?>],
                    borderWidth: 0,
                    borderRadius: chartType === 'bar' ? 4 : 0
                }]
            };
            var chartOptions = {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                var total = context.dataset.data.reduce((a, b) => a + b, 0);
                                var percent = total > 0 ? Math.round((context.raw / total) * 100) : 0;
                                return context.label + ': ' + context.raw + ' (' + percent + '%)';
                            }
                        }
                    }
                }
            };
            <?php if ($chartType === 'vertical'): ?>
            chartOptions.indexAxis = 'x';
            chartOptions.scales = {
                y: { beginAtZero: true, ticks: { stepSize: 1 } }
            };
            <?php endif; ?>
            <?php if ($chartType === 'donut'): ?>
            chartOptions.cutout = '50%';
            <?php endif; ?>
            new Chart(ctx, { type: chartType, data: chartData, options: chartOptions });
        });
        </script>
        <?php else: ?>
        <!-- Classic horizontal bars -->
        <div class="encu-answers" style="background: <?php echo $colorfondo; ?>; font-family: <?php echo $fontn; ?>, Arial, sans-serif;">
            <?php foreach ($answers as $answer):
                $votos = $answer['votos'];
                $respuesta = $answer['respuesta'];
                if (strlen($respuesta) > 30){
                    $respuesta = wordwrap($respuesta, 30, "<br>", true);
                }

                // Calculate percentage
                $percent = $votostotal > 0 ? round(($votos / $votostotal) * 100) : 0;

                // Calculate bar width (relative to max)
                $barWidth = $maxwert > 0 ? round(($votos / $maxwert) * 100) : 0;

                // Is this the winner?
                $isWinner = ($votos == $maxwert && $votos > 0);
            ?>
            <div class="encu-answer-row">
                <div class="encu-answer-text" style="color: <?php echo $colortextoresp; ?>; font-size: <?php echo $fonts; ?>;">
                    <?php echo $respuesta; ?>
                </div>
                <div class="encu-answer-votes" style="color: <?php echo $colortextoresp; ?>;">
                    <?php echo $votos; ?>
                </div>
                <div class="encu-answer-bar-container">
                    <div class="encu-answer-bar <?php echo $isWinner ? 'winner' : ''; ?>" style="width: <?php echo $barWidth; ?>%; background: <?php echo $colormarco; ?>;"></div>
                </div>
                <div class="encu-answer-percent-outside"><?php echo $percent; ?>%</div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Total -->
        <div class="encu-total" style="background: <?php echo $colorfondo; ?>; color: <?php echo $colortextopreg; ?>;">
            <div class="encu-total-number"><?php echo $votostotal; ?></div>
            <div class="encu-total-label"><?php echo __("votos totales"); ?></div>
        </div>
    </div>

    <!-- Footer -->
    <div class="encu-footer">
        <a href="https://palimpalem.com" target="_blank" class="encu-footer-logo">
            <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>
            palimpalem.com
        </a>
    </div>

    <?php
    mysqli_free_result($result1);
    exit();
}

// ===== FUNCTION: Display Error =====
function mostrarError($mensaje){
    ?>
    <button type="button" class="encu-back-btn" onclick="history.go(-1)">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
        <?php echo __("Volver");?>
    </button>

    <div class="encu-error">
        <div class="encu-error-icon">!</div>
        <div class="encu-error-title">Uups...</div>
        <div class="encu-error-text"><?php echo $mensaje; ?></div>
    </div>
    <?php
    exit();
}
?>

</div>
</body>
</html>
