<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
header('Content-Type: text/html; charset=UTF-8');

require_once __DIR__ . '/env_loader.php';
require_once __DIR__ . '/app/models/conexion.php';
require_once __DIR__ . '/app/models/votos.php';
require_once __DIR__ . '/app/models/datos.php';

use app\models\conexion;
use app\models\votos;
use app\models\datos;

$conn = new conexion();
$db   = $conn->DB();
$db->exec("SET NAMES utf8");

// Configuración: usar_poderes
$datosModel  = new datos();
$cfg         = $datosModel->obtenerDatos();
$usarPoderes = isset($cfg->usar_poderes) ? (int)$cfg->usar_poderes : 1;

// Datos de quórum
$votosModel = new votos();
$q          = $votosModel->datosQuorumConsolidado();

$poderPresentes    = $q->poder_presentes;
$poderTotal        = $q->poder_registrados;
$personasPresentes = $q->presentes;
$personasTotal     = $db->query("SELECT COUNT(*) FROM users WHERE activo=1")->fetchColumn();
$porcentaje        = $q->porcentaje;

// Listas
$faltan = $db->query("
    SELECT user_id, name, poder
    FROM users
    WHERE (quorum != 1 OR quorum IS NULL) AND activo = 1
    ORDER BY user_id
")->fetchAll(PDO::FETCH_ASSOC);

$yaRegistrados = $db->query("
    SELECT user_id, name, poder
    FROM users
    WHERE quorum = 1
    ORDER BY user_id
")->fetchAll(PDO::FETCH_ASSOC);

$poderFaltante = array_sum(array_column($faltan, 'poder'));
?>
<!doctype html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <?php require 'head.php'; ?>
    <link href="assets/css/estilos.css" rel="stylesheet">
    <title>Quórum Asamblea</title>
    <style>
        
        .qcard {
            border: none;
            border-radius: 18px;
            box-shadow: 0 4px 24px rgba(0,0,0,.08);
            overflow: hidden;
            margin-bottom: 0;
        }
        .qcard-header {
            padding: 18px 28px 14px;
            background: #fff;
            border-bottom: 1px solid #f0f0f0;
        }
        /* Tarjetas de estadísticas */
        .stat-card {
            border-radius: 16px;
            padding: 22px 20px 18px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        .stat-card.presente {
            background: linear-gradient(135deg, #17c1e8 0%, #1a73e8 100%);
            color: #fff;
        }
        .stat-card.total {
            background: linear-gradient(135deg, #6c757d 0%, #343a40 100%);
            color: #fff;
        }
        .stat-num {
            font-size: 2.8rem;
            font-weight: 800;
            line-height: 1;
            margin-bottom: 4px;
        }
        .stat-label {
            font-size: .82rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: .9;
        }
        .stat-sub {
            font-size: .78rem;
            opacity: .75;
            margin-top: 4px;
        }
        /* Barra */
        .q-bar-wrap {
            background: #e9ecef;
            border-radius: 50px;
            height: 28px;
            overflow: hidden;
            margin: 8px 0 4px;
        }
        .q-bar-fill {
            height: 100%;
            border-radius: 50px;
            background: linear-gradient(90deg, #17c1e8, #1a73e8);
            transition: width .6s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-weight: 700;
            font-size: .88rem;
            min-width: 40px;
        }
        /* Listas */
        .lista-hdr {
            font-size: .8rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: .8px;
            color: #555;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .lista-hdr .badge-count {
            background: #e9ecef;
            color: #444;
            border-radius: 20px;
            padding: 2px 10px;
            font-size: .75rem;
            font-weight: 700;
        }
        .lista-hdr .badge-count.verde {
            background: #d4edda;
            color: #155724;
        }
        .persona-item {
            display: flex;
            align-items: center;
            padding: 6px 4px;
            border-bottom: 1px solid #f3f3f3;
            font-size: .88rem;
        }
        .persona-item:last-child { border-bottom: none; }
        .persona-num {
            color: #aaa;
            font-size: .75rem;
            min-width: 24px;
        }
        .persona-nombre { flex: 1; }
        .badge-poder {
            background: #f67707;
            color: #fff;
            border-radius: 12px;
            padding: 1px 7px;
            font-size: .72rem;
            font-weight: 700;
        }
        .container { max-width: 960px !important; }
    </style>
</head>
<body>
<div class="container py-4">

    <div class="qcard">
        <div class="qcard-header text-center">
            <img src="assets/images/logo.png" style="height:48px; margin-bottom:8px;">
            <h2 style="font-weight:800; color:#1F4E79; font-size:1.6rem; margin:0;">
                QUÓRUM ASAMBLEA
            </h2>
        </div>

        <div style="padding: 24px 28px 20px; background:#fff;">

            <!-- TARJETAS PRINCIPALES -->
            <div class="row g-3 mb-4">
                <div class="col-6">
                    <div class="stat-card presente">
                        <div class="stat-num" id="q-num-presente">
                            <?php echo $usarPoderes ? $poderPresentes : $personasPresentes; ?>
                        </div>
                        <div class="stat-label">
                            <?php echo $usarPoderes ? 'Poderes Presentes' : 'Personas Presentes'; ?>
                        </div>
                        <?php if ($usarPoderes): ?>
                        <div class="stat-sub" id="q-sub-presente">
                            <?php echo $personasPresentes; ?> persona<?php echo $personasPresentes != 1 ? 's' : ''; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-6">
                    <div class="stat-card total">
                        <div class="stat-num">
                            <?php echo $usarPoderes ? $poderTotal : $personasTotal; ?>
                        </div>
                        <div class="stat-label">
                            <?php echo $usarPoderes ? 'Poderes Convocados' : 'Personas Convocadas'; ?>
                        </div>
                        <?php if ($usarPoderes): ?>
                        <div class="stat-sub"><?php echo $personasTotal; ?> personas</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- PORCENTAJE -->
            <div class="text-center mb-1">
                <span id="q-porcentaje" style="font-size:2rem; font-weight:800; color:#1F4E79;">
                    <?php echo round($porcentaje, 2); ?>%
                </span>
                <span style="font-size:1rem; color:#888; font-weight:600;"> de Quórum</span>
            </div>

            <!-- BARRA -->
            <div class="q-bar-wrap mb-4">
                <div class="q-bar-fill" id="q-barra"
                     style="width: <?php echo min(round($porcentaje, 2), 100); ?>%">
                    <span id="q-barra-txt"><?php echo round($porcentaje, 2); ?>%</span>
                </div>
            </div>

            <!-- LISTAS -->
            <div class="row g-4">

                <!-- Faltan -->
                <div class="col-md-6">
                    <div class="lista-hdr">
                        ⏳ Pendientes por Registrar
                        <span class="badge-count" id="q-badge-faltan">
                            <?php echo count($faltan); ?> personas
                            <?php if ($usarPoderes): ?>
                             = <?php echo $poderFaltante; ?> poderes
                            <?php endif; ?>
                        </span>
                    </div>
                    <?php if (count($faltan) === 0): ?>
                        <p style="color:#28a745; font-weight:700; font-size:.9rem;">✓ Todos registrados</p>
                    <?php else: ?>
                        <div style="max-height:380px; overflow-y:auto;">
                            <?php foreach ($faltan as $p): ?>
                            <div class="persona-item">
                                <span class="persona-num"><?php echo $p['user_id']; ?></span>
                                <span class="persona-nombre">
                                    <?php echo htmlspecialchars($p['name'], ENT_QUOTES, 'UTF-8'); ?>
                                </span>
                                <?php if ($usarPoderes && $p['poder'] > 1): ?>
                                    <span class="badge-poder">×<?php echo $p['poder']; ?></span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Ya Registrados -->
                <div class="col-md-6">
                    <div class="lista-hdr">
                        ✅ Ya Registrados
                        <span class="badge-count verde" id="q-badge-registrados">
                            <span id="q-cnt-registrados"><?php echo count($yaRegistrados); ?></span> persona<?php echo count($yaRegistrados) != 1 ? 's' : ''; ?>
                            <?php if ($usarPoderes): ?>
                             = <span id="q-pod-registrados"><?php echo $poderPresentes; ?></span> poderes
                            <?php endif; ?>
                        </span>
                    </div>
                    <?php if (count($yaRegistrados) === 0): ?>
                        <p style="color:#888; font-size:.9rem;">Ninguno registrado aún</p>
                    <?php else: ?>
                        <div style="max-height:380px; overflow-y:auto;" id="q-lista-registrados">
                            <?php foreach ($yaRegistrados as $p): ?>
                            <div class="persona-item">
                                <span class="persona-num"><?php echo $p['user_id']; ?></span>
                                <span class="persona-nombre">
                                    <?php echo htmlspecialchars($p['name'], ENT_QUOTES, 'UTF-8'); ?>
                                </span>
                                <?php if ($usarPoderes && $p['poder'] > 1): ?>
                                    <span class="badge-poder">×<?php echo $p['poder']; ?></span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

            </div><!-- /row listas -->
        </div><!-- /padding -->
    </div><!-- /qcard -->
</div>

<script>
(function(){
    var lastPresentes = <?php echo $personasPresentes; ?>;
    var usarPoderes   = <?php echo $usarPoderes; ?>;

    function poll(){
        var x = new XMLHttpRequest();
        x.open("GET","quorum_api.php?lista=1&_t="+Date.now(),true);
        x.timeout = 4000;
        x.onreadystatechange = function(){
            if(x.readyState===4 && x.status===200){
                try{
                    var d = JSON.parse(x.responseText);
                    if(!d.success) return;

                    var numPresente = usarPoderes ? d.poder_presentes : d.presentes;
                    var numTotal    = usarPoderes ? d.poder_registrados : d.presentes; // total no cambia

                    set("q-num-presente", numPresente);
                    set("q-sub-presente", d.presentes + " persona" + (d.presentes!=1?"s":""));
                    set("q-porcentaje", d.porcentaje+"%");
                    set("q-barra-txt", d.porcentaje+"%");
                    var barra = document.getElementById("q-barra");
                    if(barra){
                        barra.style.width = Math.min(d.porcentaje,100)+"%";
                        barra.style.background = d.quorum_alcanzado
                            ? "linear-gradient(90deg,#28a745,#20c997)"
                            : "linear-gradient(90deg,#17c1e8,#1a73e8)";
                    }
                    set("q-cnt-registrados", d.registrados);
                    set("q-pod-registrados", d.poder_presentes);

                    // Si cambia el número de presentes, recargar para actualizar listas
                    if(lastPresentes !== undefined && lastPresentes !== d.presentes){
                        location.reload();
                    }
                    lastPresentes = d.presentes;
                }catch(e){ console.error("Quorum parse error:",e); }
            }
        };
        x.send();
    }

    function set(id, val){
        var e = document.getElementById(id);
        if(e) e.textContent = val;
    }

    poll();
    setInterval(poll, 5000);
})();
</script>
</body>
</html>
