<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user     = getConnectedUser($pdo);
$userId   = (int)$user['id'];
$circleId = (int)($_SESSION['circle_id'] ?? 1);

$msg = ''; $error = '';

// Créer table votes si absente
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS oracle_votes (
        id         INT(11)    NOT NULL AUTO_INCREMENT PRIMARY KEY,
        circle_id  INT(11)    NOT NULL,
        voter_id   INT(11)    NOT NULL,
        candidate_id INT(11)  NOT NULL,
        created_at TIMESTAMP  DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_vote (circle_id, voter_id)
    )");
} catch (Exception $e) {}

// Infos du cercle
$circleStmt = $pdo->prepare("SELECT * FROM circles WHERE id=?");
$circleStmt->execute([$circleId]);
$circle = $circleStmt->fetch();

if (!$circle) { header("Location: index.php"); exit; }

$creatorId    = (int)($circle['creator_id'] ?? 0);
$currentOracle= (int)($circle['oracle_id']  ?? 0);
$isCreator    = $creatorId === $userId;
$isAdmin      = isAdmin($user);

// Vérifier que l'user est membre
$memberChk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id=? AND user_id=?");
$memberChk->execute([$circleId, $userId]);
if (!$memberChk->fetch() && !$isAdmin) { header("Location: index.php"); exit; }

// Voter
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['vote_for'])) {
    $candidateId = (int)$_POST['vote_for'];
    if ($candidateId && $candidateId !== $userId) {
        try {
            $pdo->prepare("INSERT INTO oracle_votes (circle_id,voter_id,candidate_id) VALUES (?,?,?)
                           ON DUPLICATE KEY UPDATE candidate_id=?, created_at=NOW()")
                ->execute([$circleId, $userId, $candidateId, $candidateId]);
            $msg = "Vote enregistre !";
        } catch (Exception $e) { $error = $e->getMessage(); }
    }
}

// Réinitialiser le vote (créateur/admin seulement)
if (isset($_GET['reset_votes']) && ($isCreator || $isAdmin)) {
    $pdo->prepare("DELETE FROM oracle_votes WHERE circle_id=?")->execute([$circleId]);
    $msg = "Votes réinitialisés.";
}

// Appliquer l'élu (créateur/admin)
if (isset($_GET['apply_winner']) && ($isCreator || $isAdmin)) {
    $winnerId = (int)$_GET['apply_winner'];
    $pdo->prepare("UPDATE circles SET oracle_id=? WHERE id=?")->execute([$winnerId, $circleId]);
    $pdo->prepare("DELETE FROM oracle_votes WHERE circle_id=?")->execute([$circleId]);
    $winnerName = $pdo->prepare("SELECT username FROM users WHERE id=?");
    $winnerName->execute([$winnerId]);
    $wn = $winnerName->fetchColumn();
    addNotification($pdo, $winnerId, "Tu es le nouvel Oracle de \"{$circle['name']}\" !", "oracle_judge.php");
    $msg = htmlspecialchars($wn) . " est maintenant l'Oracle !";
    // Recharger
    $circleStmt->execute([$circleId]);
    $circle = $circleStmt->fetch();
    $currentOracle = $winnerId;
}

// Membres du cercle
$membersStmt = $pdo->prepare("
    SELECT u.id, u.username, u.tier, u.points,
           CASE WHEN c.oracle_id=u.id THEN 1 ELSE 0 END as is_oracle,
           CASE WHEN c.creator_id=u.id THEN 1 ELSE 0 END as is_creator
    FROM users u
    JOIN circle_members cm ON cm.user_id=u.id
    JOIN circles c ON c.id=cm.circle_id
    WHERE cm.circle_id=?
    ORDER BY is_creator DESC, is_oracle DESC, u.username ASC
");
$membersStmt->execute([$circleId]);
$members = $membersStmt->fetchAll();

// Résultats des votes
$votesStmt = $pdo->prepare("
    SELECT candidate_id, COUNT(*) as nb, u.username
    FROM oracle_votes ov
    JOIN users u ON u.id = ov.candidate_id
    WHERE ov.circle_id=?
    GROUP BY candidate_id ORDER BY nb DESC
");
$votesStmt->execute([$circleId]);
$voteResults = $votesStmt->fetchAll();
$totalVotes  = array_sum(array_column($voteResults, 'nb'));

// Mon vote actuel
$myVoteStmt = $pdo->prepare("SELECT candidate_id FROM oracle_votes WHERE circle_id=? AND voter_id=?");
$myVoteStmt->execute([$circleId, $userId]);
$myVote = $myVoteStmt->fetchColumn();

include 'header.php';
?>

<div class="container mt-4 px-4" style="max-width:700px;">
    <div class="d-flex align-items-center gap-3 mb-3">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-warning fw-bold mb-0">Vote Oracle — <?= htmlspecialchars($circle['name']) ?></h5>
    </div>

    <?php if ($msg):   ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger  small py-2"><?= $error ?></div><?php endif; ?>

    <div class="row g-3">
        <!-- VOTER -->
        <div class="col-md-6">
            <div class="card bg-dark border-info shadow">
                <div class="card-header text-info fw-bold small py-2">Voter pour l'Oracle</div>
                <div class="card-body py-2">
                    <?php
                    $oracleInfo = $pdo->prepare("SELECT username FROM users WHERE id=?");
                    $oracleInfo->execute([$currentOracle]);
                    $oracleName = $oracleInfo->fetchColumn() ?: '—';
                    ?>
                    <div class="d-flex justify-content-between mb-3 small">
                        <span style="color:#aaa;">Oracle actuel</span>
                        <span class="text-warning fw-bold"><?= htmlspecialchars($oracleName) ?></span>
                    </div>
                    <?php if ($myVote): ?>
                    <div class="alert alert-info small py-2 mb-2">
                        <?php
                        $myVoteNameStmt = $pdo->prepare("SELECT username FROM users WHERE id=?");
                        $myVoteNameStmt->execute([$myVote]);
                        $myVoteName = $myVoteNameStmt->fetchColumn();
                        ?>
                        Ton vote : <strong><?= htmlspecialchars($myVoteName) ?></strong>
                        <small style="color:#aaa;display:block;font-size:0.6rem;">Tu peux changer ton vote</small>
                    </div>
                    <?php endif; ?>
                    <form method="POST">
                        <select name="vote_for" class="form-select form-select-sm bg-dark text-white border-secondary mb-2">
                            <option value="">-- Choisir un membre --</option>
                            <?php foreach ($members as $m):
                                if ($m['id'] === $userId) continue; ?>
                            <option value="<?= $m['id'] ?>" <?= $myVote==$m['id']?'selected':'' ?>>
                                <?= htmlspecialchars($m['username']) ?>
                                <?= $m['is_oracle'] ? ' (Oracle actuel)' : '' ?>
                                <?= $m['is_creator'] ? ' (Proprietaire)' : '' ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <button type="submit" name="vote_for" class="btn btn-info btn-sm fw-bold w-100">VOTER</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- RÉSULTATS -->
        <div class="col-md-6">
            <div class="card bg-dark border-warning shadow">
                <div class="card-header text-warning fw-bold small py-2 d-flex justify-content-between">
                    <span>Résultats (<?= $totalVotes ?> votes)</span>
                    <?php if ($isCreator || $isAdmin): ?>
                    <a href="?reset_votes=1" class="btn btn-xs btn-outline-danger py-0"
                       onclick="return confirm('Reinitialiser tous les votes ?')">Reset</a>
                    <?php endif; ?>
                </div>
                <div class="card-body py-2">
                    <?php if (empty($voteResults)): ?>
                    <p style="color:#aaa;font-size:0.75rem;">Aucun vote encore.</p>
                    <?php endif; ?>
                    <?php foreach ($voteResults as $i => $v):
                        $pct = $totalVotes > 0 ? round($v['nb'] / $totalVotes * 100) : 0;
                        $isLeader = $i === 0;
                    ?>
                    <div class="mb-2">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="<?= $isLeader?'text-warning fw-bold':'text-white' ?>" style="font-size:0.75rem;">
                                <?= $isLeader ? '&#9733; ' : '' ?><?= htmlspecialchars($v['username']) ?>
                            </span>
                            <div class="d-flex align-items-center gap-2">
                                <span class="text-info" style="font-size:0.7rem;"><?= $v['nb'] ?> vote<?= $v['nb']>1?'s':'' ?></span>
                                <?php if (($isCreator || $isAdmin) && $isLeader && $v['nb'] > 0): ?>
                                <a href="?apply_winner=<?= $v['candidate_id'] ?>"
                                   class="btn btn-xs btn-warning py-0" style="font-size:0.55rem;"
                                   onclick="return confirm('Nommer <?= htmlspecialchars($v['username']) ?> comme Oracle ?')">Elire</a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="progress" style="height:6px;background:#222;">
                            <div class="progress-bar bg-warning" style="width:<?= $pct ?>%;"></div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (($isCreator || $isAdmin) && !empty($voteResults)): ?>
                    <hr class="border-secondary my-2">
                    <small style="color:#aaa;font-size:0.62rem;">Le proprietaire/admin peut élire le candidat en tête.</small>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
