<?php
include_once('../config.php');
include_once('../header.php');

$pid = intval($_GET['partida']);
if (!$pid) { header("Location: mexemexe.php"); exit(); }

// Processa o Ponto (AJAX ou Background)
if (isset($_POST['salvar_ponto'])) {
    $jid = intval($_POST['jid']);
    $pts = intval($_POST['pts']);
    if ($jid > 0 && $pts != 0) {
        $conn->query("INSERT INTO mexe_pontos (jogador_id, pontos) VALUES ('$jid', '$pts')");
    }
    exit();
}

$sala = $conn->query("SELECT local FROM mexe_partidas WHERE id = $pid")->fetch_assoc();
?>

<style>
    body { font-family: sans-serif; background: #f0f2f5; text-transform: uppercase; }
    .placar-card { max-width: 500px; margin: 30px auto; background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
    .linha-jogador { display: flex; align-items: center; justify-content: space-between; padding: 15px 0; border-bottom: 1px solid #eee; }
    .nome { font-weight: bold; flex: 1; }
    .pts-total { color: #00569e; font-size: 18px; margin: 0 15px; width: 40px; text-align: center; }
    .input-box { width: 60px; padding: 10px; border: 2px solid #ddd; border-radius: 6px; text-align: center; font-weight: bold; }
    .btn-add { background: #28a745; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; margin-left: 5px; }
    .salvo-anim { background: #d4edda !important; transition: 0.4s; }
</style>

<div class="placar-card">
    <div style="display:flex; justify-content:space-between; margin-bottom:20px;">
        <h2 style="margin:0">📍 <?php echo $sala['local']; ?></h2>
        <a href="mexemexe.php" style="text-decoration:none; font-weight:bold; color:#666">VOLTAR</a>
    </div>

    <?php
    $jogadores = $conn->query("SELECT j.id, j.nome, IFNULL(SUM(p.pontos), 0) as total 
                              FROM mexe_jogadores j 
                              LEFT JOIN mexe_pontos p ON j.id = p.jogador_id 
                              WHERE j.partida_id = '$pid' 
                              GROUP BY j.id ORDER BY j.nome ASC");
    while($j = $jogadores->fetch_assoc()):
    ?>
    <div class="linha-jogador">
        <div class="nome"><?php echo $j['nome']; ?></div>
        <div class="pts-total" id="total-<?php echo $j['id']; ?>"><?php echo $j['total']; ?></div>
        <div style="display:flex;">
            <input type="number" id="input-<?php echo $j['id']; ?>" class="input-box" placeholder="0">
            <button type="button" class="btn-add" onclick="enviarPonto('<?php echo $j['id']; ?>')">+</button>
        </div>
    </div>
    <?php endwhile; ?>
</div>

<script>
function enviarPonto(jid) {
    const input = document.getElementById('input-' + jid);
    const valor = parseInt(input.value);
    if (!valor) return;

    const fd = new FormData();
    fd.append('salvar_ponto', '1');
    fd.append('jid', jid);
    fd.append('pts', valor);

    fetch(window.location.href, { method: 'POST', body: fd })
    .then(() => {
        const display = document.getElementById('total-' + jid);
        display.innerText = parseInt(display.innerText) + valor;
        input.value = '';
        input.classList.add('salvo-anim');
        setTimeout(() => input.classList.remove('salvo-anim'), 500);
    });
}

// SALVAR AUTOMÁTICO AO SAIR (Se esqueceu de clicar no +)
window.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'hidden') {
        document.querySelectorAll('.input-box').forEach(input => {
            const val = parseInt(input.value);
            if (val) {
                const jid = input.id.replace('input-', '');
                const fd = new FormData();
                fd.append('salvar_ponto', '1');
                fd.append('jid', jid);
                fd.append('pts', val);
                navigator.sendBeacon(window.location.href, fd); // Envia mesmo fechando a aba
                input.value = '';
            }
        });
    }
});
</script>