<?php

session_start();
include("../includes/auth.php");
include("../config/db.php");

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

if(
    !isset($_SESSION['can_view_ranking']) ||
    intval($_SESSION['can_view_ranking']) !== 1
){
    // Si no tiene permiso explícito, verificar si es admin
    if(!isset($_SESSION['can_manage_users']) || intval($_SESSION['can_manage_users']) !== 1){
        header("Location: /pages/dashboard.php");
        exit;
    }
}

$user_id  = intval($_SESSION['user_id']);
$is_admin = intval($_SESSION['can_manage_users'] ?? 0) === 1;

// Filtros
$periodo    = $_GET['periodo']    ?? 'mes';
$campaign_f = intval($_GET['campaign_id'] ?? 0);
$office_f   = intval($_GET['office_id']   ?? 0);
$vista      = $_GET['vista']      ?? 'agentes';

// Rango de fechas
switch($periodo){
    case 'hoy':
        $date_from = date('Y-m-d 00:00:00');
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Hoy';
        break;
    case 'semana':
        $date_from = date('Y-m-d 00:00:00', strtotime('monday this week'));
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Esta semana';
        break;
    case 'mes':
        $date_from = date('Y-m-01 00:00:00');
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Este mes';
        break;
    case 'trimestre':
        $month     = date('n');
        $q_start   = date('Y-m-d', mktime(0,0,0, floor(($month-1)/3)*3+1, 1));
        $date_from = $q_start.' 00:00:00';
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Este trimestre';
        break;
    case 'año':
        $date_from = date('Y-01-01 00:00:00');
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Este año';
        break;
    default:
        $date_from = date('Y-m-01 00:00:00');
        $date_to   = date('Y-m-d 23:59:59');
        $label     = 'Este mes';
}

// WHERE adicional
$where_campaign = $campaign_f > 0 ? "AND c.campaign_id = '$campaign_f'" : "";
$where_office   = $office_f > 0   ? "AND c.office_id = '$office_f'"     : "";

// Jerarquía — si no es admin, solo ve su equipo
$where_user = "";
if(!$is_admin){
    include("../includes/hierarchy.php");
    $visible = visibleUsersToSql($conn, $user_id);
    $where_user = "AND c.assigned_user_id IN ($visible)";
}

/*
|--------------------------------------------------------------------------
| RANKING POR AGENTE
|--------------------------------------------------------------------------
*/
$ranking_agentes = $conn->query("
SELECT
    u.id,
    u.name,
    u.visual_role,
    o.office_name,
    COUNT(c.id)          AS total_ventas,
    SUM(c.amount)        AS total_monto,
    cam.campaign_name
FROM contracts c
INNER JOIN users u ON u.id = c.assigned_user_id
LEFT JOIN offices o ON o.id = c.office_id
LEFT JOIN campaigns cam ON cam.id = c.campaign_id
WHERE c.created_at BETWEEN '$date_from' AND '$date_to'
$where_campaign
$where_office
$where_user
GROUP BY c.assigned_user_id
ORDER BY total_ventas DESC, total_monto DESC
LIMIT 20
");

/*
|--------------------------------------------------------------------------
| RANKING POR OFICINA
|--------------------------------------------------------------------------
*/
$ranking_oficinas = $conn->query("
SELECT
    o.id,
    o.office_name,
    COUNT(c.id)     AS total_ventas,
    SUM(c.amount)   AS total_monto,
    COUNT(DISTINCT c.assigned_user_id) AS total_agentes
FROM contracts c
LEFT JOIN offices o ON o.id = c.office_id
WHERE c.created_at BETWEEN '$date_from' AND '$date_to'
$where_campaign
$where_user
GROUP BY c.office_id
ORDER BY total_ventas DESC
LIMIT 10
");

/*
|--------------------------------------------------------------------------
| RANKING POR CAMPAÑA
|--------------------------------------------------------------------------
*/
$ranking_campañas = $conn->query("
SELECT
    cam.id,
    cam.campaign_name,
    COUNT(c.id)     AS total_ventas,
    SUM(c.amount)   AS total_monto,
    COUNT(DISTINCT c.assigned_user_id) AS total_agentes
FROM contracts c
LEFT JOIN campaigns cam ON cam.id = c.campaign_id
WHERE c.created_at BETWEEN '$date_from' AND '$date_to'
$where_office
$where_user
GROUP BY c.campaign_id
ORDER BY total_ventas DESC
LIMIT 10
");

// KPIs globales
$kpis = $conn->query("
SELECT
    COUNT(*)          AS total_ventas,
    SUM(amount)       AS total_monto,
    COUNT(DISTINCT assigned_user_id) AS total_agentes
FROM contracts
WHERE created_at BETWEEN '$date_from' AND '$date_to'
$where_campaign
$where_office
$where_user
")->fetch_assoc();

// Mi posición
$mi_pos = $conn->query("
SELECT COUNT(*)+1 AS posicion
FROM (
    SELECT assigned_user_id, COUNT(*) AS v
    FROM contracts
    WHERE created_at BETWEEN '$date_from' AND '$date_to'
    $where_campaign $where_office $where_user
    GROUP BY assigned_user_id
    HAVING v > (
        SELECT COUNT(*) FROM contracts
        WHERE assigned_user_id = '$user_id'
        AND created_at BETWEEN '$date_from' AND '$date_to'
        $where_campaign $where_office $where_user
    )
) t
")->fetch_assoc();

$mis_ventas = $conn->query("
SELECT COUNT(*) AS v, SUM(amount) AS m
FROM contracts
WHERE assigned_user_id = '$user_id'
AND created_at BETWEEN '$date_from' AND '$date_to'
$where_campaign $where_office
")->fetch_assoc();

// Campañas y oficinas para filtros
$campañas_list = $conn->query("SELECT id, campaign_name FROM campaigns WHERE campaign_status != 'inactive' ORDER BY campaign_name");
$oficinas_list = $conn->query("SELECT id, office_name FROM offices WHERE status = 'active' ORDER BY office_name");

// Última venta para popup
$ultima_venta = $conn->query("
SELECT c.customer_name, u.name AS agent_name, cam.campaign_name, c.created_at
FROM contracts c
LEFT JOIN users u ON u.id = c.assigned_user_id
LEFT JOIN campaigns cam ON cam.id = c.campaign_id
WHERE c.created_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
ORDER BY c.created_at DESC
LIMIT 1
")->fetch_assoc();

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🏆 Ranking de Ventas</title>
<link rel="stylesheet" href="/assets/css/style.css">
<style>

.content-area{
    margin-left:260px;
    padding:32px 40px;
    min-height:100vh;
    background:#f8fafc;
}

.page-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    margin-bottom:28px;
    flex-wrap:wrap;
    gap:16px;
}

.page-title{
    font-size:32px;
    font-weight:800;
    color:#02122c;
}

.periodo-tabs{
    display:flex;
    gap:8px;
    background:#fff;
    padding:6px;
    border-radius:14px;
    box-shadow:0 2px 8px rgba(0,0,0,.06);
}

.periodo-tab{
    padding:8px 16px;
    border-radius:10px;
    font-size:13px;
    font-weight:700;
    color:#64748b;
    text-decoration:none;
    transition:.2s;
}

.periodo-tab.active{
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
}

.kpi-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
    gap:16px;
    margin-bottom:28px;
}

.kpi-card{
    background:#fff;
    border-radius:16px;
    padding:20px 24px;
    box-shadow:0 2px 12px rgba(0,0,0,.06);
    border-left:4px solid #5b4bff;
}

.kpi-card.gold  { border-color:#f59e0b; }
.kpi-card.green { border-color:#10b981; }
.kpi-card.blue  { border-color:#3b82f6; }

.kpi-value{
    font-size:32px;
    font-weight:800;
    color:#02122c;
}

.kpi-label{
    font-size:13px;
    color:#64748b;
    margin-top:4px;
}

.mi-posicion{
    background:linear-gradient(135deg,#5b4bff,#7b61ff);
    border-radius:16px;
    padding:20px 24px;
    color:#fff;
    display:flex;
    align-items:center;
    gap:16px;
}

.mi-pos-num{
    font-size:48px;
    font-weight:900;
    line-height:1;
}

.filtros{
    display:flex;
    gap:12px;
    margin-bottom:24px;
    flex-wrap:wrap;
}

.filtro-select{
    height:40px;
    border:1.5px solid #e2e8f0;
    border-radius:10px;
    padding:0 14px;
    font-size:14px;
    color:#02122c;
    background:#fff;
    cursor:pointer;
}

.vista-tabs{
    display:flex;
    gap:8px;
    margin-bottom:24px;
}

.vista-tab{
    padding:8px 20px;
    border-radius:10px;
    font-size:14px;
    font-weight:700;
    color:#64748b;
    text-decoration:none;
    background:#fff;
    border:1.5px solid #e2e8f0;
    transition:.2s;
}

.vista-tab.active{
    background:#02122c;
    color:#fff;
    border-color:#02122c;
}

.ranking-table{
    background:#fff;
    border-radius:20px;
    overflow:hidden;
    box-shadow:0 4px 20px rgba(0,0,0,.06);
}

.ranking-row{
    display:grid;
    grid-template-columns:60px 1fr auto auto auto;
    align-items:center;
    padding:16px 24px;
    border-bottom:1px solid #f1f5f9;
    transition:.15s;
    gap:12px;
}

.ranking-row:last-child{ border-bottom:none; }
.ranking-row:hover{ background:#f8fafc; }

.ranking-row.top1{ background:linear-gradient(135deg,#fef9c3,#fff); }
.ranking-row.top2{ background:linear-gradient(135deg,#f1f5f9,#fff); }
.ranking-row.top3{ background:linear-gradient(135deg,#fff7ed,#fff); }
.ranking-row.yo  { background:linear-gradient(135deg,#ede9fe,#fff); border-left:4px solid #5b4bff; }

.pos-badge{
    width:44px;
    height:44px;
    border-radius:14px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:20px;
    font-weight:900;
}

.pos-1{ background:linear-gradient(135deg,#f59e0b,#fbbf24); color:#fff; }
.pos-2{ background:linear-gradient(135deg,#94a3b8,#cbd5e1); color:#fff; }
.pos-3{ background:linear-gradient(135deg,#cd7c2f,#e8a85a); color:#fff; }
.pos-n{ background:#f1f5f9; color:#64748b; font-size:16px; }

.agent-name{
    font-size:16px;
    font-weight:700;
    color:#02122c;
}

.agent-role{
    font-size:12px;
    color:#94a3b8;
}

.ventas-num{
    font-size:28px;
    font-weight:900;
    color:#5b4bff;
    text-align:right;
}

.ventas-label{
    font-size:11px;
    color:#94a3b8;
    text-align:right;
}

.monto{
    font-size:14px;
    font-weight:700;
    color:#10b981;
    text-align:right;
    white-space:nowrap;
}

.progress-bar{
    height:6px;
    background:#f1f5f9;
    border-radius:3px;
    overflow:hidden;
    margin-top:4px;
    width:120px;
}

.progress-fill{
    height:100%;
    border-radius:3px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
}

/* POPUP CELEBRACIÓN */
.celebracion-overlay{
    display:none;
    position:fixed;
    inset:0;
    z-index:9999;
    pointer-events:none;
}

.celebracion-overlay.show{
    display:block;
}

.celebracion-card{
    position:fixed;
    bottom:32px;
    right:32px;
    background:linear-gradient(135deg,#5b4bff,#7b61ff);
    color:#fff;
    border-radius:24px;
    padding:24px 28px;
    box-shadow:0 20px 60px rgba(91,75,255,.4);
    max-width:340px;
    animation:slideIn .5s cubic-bezier(.34,1.56,.64,1);
    pointer-events:all;
    z-index:9999;
}

@keyframes slideIn{
    from{ transform:translateX(120%); opacity:0; }
    to  { transform:translateX(0);    opacity:1; }
}

.celebracion-emoji{ font-size:40px; margin-bottom:8px; }
.celebracion-titulo{ font-size:18px; font-weight:800; margin-bottom:4px; }
.celebracion-texto{ font-size:14px; opacity:.85; }
.celebracion-close{
    position:absolute;
    top:12px;
    right:16px;
    background:none;
    border:none;
    color:#fff;
    font-size:20px;
    cursor:pointer;
    opacity:.7;
}

/* CONFETTI */
.confetti-piece{
    position:fixed;
    width:10px;
    height:10px;
    border-radius:2px;
    animation:confetti-fall 3s linear forwards;
    z-index:9998;
}

@keyframes confetti-fall{
    0%  { transform:translateY(-20px) rotate(0deg);   opacity:1; }
    100%{ transform:translateY(100vh) rotate(720deg); opacity:0; }
}

.ranking-header{
    display:grid;
    grid-template-columns:60px 1fr auto auto auto;
    padding:12px 24px;
    background:#f8fafc;
    font-size:12px;
    font-weight:700;
    color:#94a3b8;
    text-transform:uppercase;
    letter-spacing:.5px;
    gap:12px;
}

.empty-state{
    text-align:center;
    padding:60px 20px;
    color:#94a3b8;
    font-size:16px;
}

.empty-state .emoji{ font-size:48px; margin-bottom:12px; }

</style>
</head>
<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-header">

        <div class="page-title">🏆 Ranking de Ventas</div>

        <div class="periodo-tabs">
            <?php foreach(['hoy'=>'Hoy','semana'=>'Semana','mes'=>'Mes','trimestre'=>'Trimestre','año'=>'Año'] as $k=>$v): ?>
            <a href="?periodo=<?= $k ?>&campaign_id=<?= $campaign_f ?>&office_id=<?= $office_f ?>&vista=<?= $vista ?>"
               class="periodo-tab <?= $periodo==$k?'active':'' ?>">
               <?= $v ?>
            </a>
            <?php endforeach; ?>
        </div>

    </div>

    <!-- KPIs -->
    <div class="kpi-grid">

        <div class="kpi-card gold">
            <div class="kpi-value"><?= number_format($kpis['total_ventas'] ?? 0) ?></div>
            <div class="kpi-label">Ventas totales — <?= $label ?></div>
        </div>

        <div class="kpi-card green">
            <div class="kpi-value">€<?= number_format($kpis['total_monto'] ?? 0, 0, ',', '.') ?></div>
            <div class="kpi-label">Facturación total</div>
        </div>

        <div class="kpi-card blue">
            <div class="kpi-value"><?= $kpis['total_agentes'] ?? 0 ?></div>
            <div class="kpi-label">Agentes con ventas</div>
        </div>

        <div class="mi-posicion">
            <div class="mi-pos-num">#<?= $mi_pos['posicion'] ?? '—' ?></div>
            <div>
                <div style="font-size:15px;font-weight:800;">Tu posición</div>
                <div style="font-size:13px;opacity:.85;"><?= $mis_ventas['v'] ?? 0 ?> ventas · €<?= number_format($mis_ventas['m'] ?? 0, 0, ',', '.') ?></div>
            </div>
        </div>

    </div>

    <!-- Filtros -->
    <div class="filtros">

        <form method="GET" style="display:flex;gap:12px;flex-wrap:wrap;">
            <input type="hidden" name="periodo" value="<?= htmlspecialchars($periodo) ?>">
            <input type="hidden" name="vista"   value="<?= htmlspecialchars($vista) ?>">

            <select name="campaign_id" class="filtro-select" onchange="this.form.submit()">
                <option value="0">Todas las campañas</option>
                <?php while($c = $campañas_list->fetch_assoc()): ?>
                <option value="<?= $c['id'] ?>" <?= $campaign_f==$c['id']?'selected':'' ?>>
                    <?= htmlspecialchars($c['campaign_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>

            <select name="office_id" class="filtro-select" onchange="this.form.submit()">
                <option value="0">Todas las oficinas</option>
                <?php while($o = $oficinas_list->fetch_assoc()): ?>
                <option value="<?= $o['id'] ?>" <?= $office_f==$o['id']?'selected':'' ?>>
                    <?= htmlspecialchars($o['office_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>

        </form>

    </div>

    <!-- Vista tabs -->
    <div class="vista-tabs">
        <a href="?periodo=<?= $periodo ?>&campaign_id=<?= $campaign_f ?>&office_id=<?= $office_f ?>&vista=agentes"
           class="vista-tab <?= $vista=='agentes'?'active':'' ?>">👤 Agentes</a>
        <a href="?periodo=<?= $periodo ?>&campaign_id=<?= $campaign_f ?>&office_id=<?= $office_f ?>&vista=oficinas"
           class="vista-tab <?= $vista=='oficinas'?'active':'' ?>">🏢 Oficinas</a>
        <a href="?periodo=<?= $periodo ?>&campaign_id=<?= $campaign_f ?>&office_id=<?= $office_f ?>&vista=campañas"
           class="vista-tab <?= $vista=='campañas'?'active':'' ?>">📣 Campañas</a>
    </div>

    <!-- TABLA -->
    <div class="ranking-table">

        <?php if($vista === 'agentes'): ?>

        <div class="ranking-header">
            <span>Pos.</span>
            <span>Agente</span>
            <span style="text-align:right">Ventas</span>
            <span style="text-align:right">Facturación</span>
            <span style="text-align:right">Progreso</span>
        </div>

        <?php
        $rows = [];
        while($r = $ranking_agentes->fetch_assoc()) $rows[] = $r;
        $max_ventas = $rows[0]['total_ventas'] ?? 1;

        if(empty($rows)):
        ?>
        <div class="empty-state">
            <div class="emoji">📊</div>
            No hay ventas registradas en este período
        </div>
        <?php else: ?>
        <?php foreach($rows as $i => $r):
            $pos   = $i + 1;
            $es_yo = $r['id'] == $user_id;
            $clase = $es_yo ? 'yo' : ($pos==1?'top1':($pos==2?'top2':($pos==3?'top3':'')));
            $pos_clase = $pos==1?'pos-1':($pos==2?'pos-2':($pos==3?'pos-3':'pos-n'));
            $emoji = $pos==1?'🥇':($pos==2?'🥈':($pos==3?'🥉':$pos));
            $pct   = round(($r['total_ventas'] / $max_ventas) * 100);
        ?>
        <div class="ranking-row <?= $clase ?>">
            <div class="pos-badge <?= $pos_clase ?>"><?= $emoji ?></div>
            <div>
                <div class="agent-name"><?= htmlspecialchars($r['name']) ?> <?= $es_yo ? '<span style="font-size:11px;background:#5b4bff;color:#fff;padding:2px 8px;border-radius:20px;">Tú</span>' : '' ?></div>
                <div class="agent-role"><?= htmlspecialchars($r['visual_role'] ?? '') ?> · <?= htmlspecialchars($r['office_name'] ?? 'Sin oficina') ?></div>
            </div>
            <div>
                <div class="ventas-num"><?= $r['total_ventas'] ?></div>
                <div class="ventas-label">ventas</div>
            </div>
            <div class="monto">€<?= number_format($r['total_monto'] ?? 0, 0, ',', '.') ?></div>
            <div>
                <div class="progress-bar">
                    <div class="progress-fill" style="width:<?= $pct ?>%"></div>
                </div>
                <div style="font-size:11px;color:#94a3b8;text-align:right;margin-top:2px;"><?= $pct ?>%</div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php elseif($vista === 'oficinas'): ?>

        <div class="ranking-header">
            <span>Pos.</span>
            <span>Oficina</span>
            <span style="text-align:right">Ventas</span>
            <span style="text-align:right">Facturación</span>
            <span style="text-align:right">Agentes</span>
        </div>

        <?php
        $rows = [];
        while($r = $ranking_oficinas->fetch_assoc()) $rows[] = $r;
        if(empty($rows)):
        ?>
        <div class="empty-state"><div class="emoji">🏢</div>No hay datos de oficinas</div>
        <?php else: ?>
        <?php foreach($rows as $i => $r):
            $pos = $i+1;
            $emoji = $pos==1?'🥇':($pos==2?'🥈':($pos==3?'🥉':$pos));
            $pos_clase = $pos==1?'pos-1':($pos==2?'pos-2':($pos==3?'pos-3':'pos-n'));
        ?>
        <div class="ranking-row <?= $pos<=3?'top'.$pos:'' ?>">
            <div class="pos-badge <?= $pos_clase ?>"><?= $emoji ?></div>
            <div>
                <div class="agent-name"><?= htmlspecialchars($r['office_name'] ?? 'Sin oficina') ?></div>
                <div class="agent-role"><?= $r['total_agentes'] ?> agentes activos</div>
            </div>
            <div>
                <div class="ventas-num"><?= $r['total_ventas'] ?></div>
                <div class="ventas-label">ventas</div>
            </div>
            <div class="monto">€<?= number_format($r['total_monto'] ?? 0, 0, ',', '.') ?></div>
            <div style="text-align:right;font-size:14px;color:#64748b;"><?= $r['total_agentes'] ?> 👤</div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php else: // campañas ?>

        <div class="ranking-header">
            <span>Pos.</span>
            <span>Campaña</span>
            <span style="text-align:right">Ventas</span>
            <span style="text-align:right">Facturación</span>
            <span style="text-align:right">Agentes</span>
        </div>

        <?php
        $rows = [];
        while($r = $ranking_campañas->fetch_assoc()) $rows[] = $r;
        if(empty($rows)):
        ?>
        <div class="empty-state"><div class="emoji">📣</div>No hay datos de campañas</div>
        <?php else: ?>
        <?php foreach($rows as $i => $r):
            $pos = $i+1;
            $emoji = $pos==1?'🥇':($pos==2?'🥈':($pos==3?'🥉':$pos));
            $pos_clase = $pos==1?'pos-1':($pos==2?'pos-2':($pos==3?'pos-3':'pos-n'));
        ?>
        <div class="ranking-row <?= $pos<=3?'top'.$pos:'' ?>">
            <div class="pos-badge <?= $pos_clase ?>"><?= $emoji ?></div>
            <div>
                <div class="agent-name"><?= htmlspecialchars($r['campaign_name'] ?? 'Sin campaña') ?></div>
                <div class="agent-role"><?= $r['total_agentes'] ?> agentes activos</div>
            </div>
            <div>
                <div class="ventas-num"><?= $r['total_ventas'] ?></div>
                <div class="ventas-label">ventas</div>
            </div>
            <div class="monto">€<?= number_format($r['total_monto'] ?? 0, 0, ',', '.') ?></div>
            <div style="text-align:right;font-size:14px;color:#64748b;"><?= $r['total_agentes'] ?> 👤</div>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>

        <?php endif; ?>

    </div>

</div>

<!-- POPUP CELEBRACIÓN -->
<?php if($ultima_venta): ?>
<div class="celebracion-overlay show" id="celebracion">
    <div class="celebracion-card">
        <button class="celebracion-close" onclick="cerrarCelebracion()">✕</button>
        <div class="celebracion-emoji">🎉</div>
        <div class="celebracion-titulo">¡Nueva venta!</div>
        <div class="celebracion-texto">
            <strong><?= htmlspecialchars($ultima_venta['agent_name']) ?></strong> acaba de cerrar una venta<br>
            Cliente: <?= htmlspecialchars($ultima_venta['customer_name']) ?><br>
            Campaña: <?= htmlspecialchars($ultima_venta['campaign_name'] ?? '') ?>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
// Confetti al cargar si hay popup
<?php if($ultima_venta): ?>
window.addEventListener('load', () => {
    lanzarConfetti();
    setTimeout(cerrarCelebracion, 8000);
});
<?php endif; ?>

function lanzarConfetti(){
    const colores = ['#5b4bff','#f59e0b','#10b981','#ef4444','#3b82f6','#ec4899'];
    for(let i=0; i<80; i++){
        const el = document.createElement('div');
        el.className = 'confetti-piece';
        el.style.cssText = `
            left:${Math.random()*100}vw;
            top:-20px;
            background:${colores[Math.floor(Math.random()*colores.length)]};
            animation-delay:${Math.random()*2}s;
            animation-duration:${2+Math.random()*2}s;
            transform:rotate(${Math.random()*360}deg);
            width:${6+Math.random()*10}px;
            height:${6+Math.random()*10}px;
        `;
        document.body.appendChild(el);
        setTimeout(()=>el.remove(), 5000);
    }
}

function cerrarCelebracion(){
    const el = document.getElementById('celebracion');
    if(el) el.style.display = 'none';
}

// Auto-refrescar cada 60 segundos
setTimeout(()=>location.reload(), 60000);
</script>

</body>
</html>
