<?php
/**
 * Election Results — live-updating dashboard
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/voting.php';
requireAuth();

if (!isVotingEnabled()) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Voting system is currently disabled.'));
    exit;
}

$election = getElection($id);
if (!$election) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Election not found.'));
    exit;
}

if (!canManageElection($id)) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('You do not have permission to view these results.'));
    exit;
}

$voterStats = getVoterStats($id);
$rollCount  = $voterStats['eligible'];  // 0 = open mode (no roll)

$pageTitle = 'Results: ' . htmlspecialchars($election['title']);
require_once __DIR__ . '/../../includes/header.php';
?>

<?php
$castNow    = getTotalVotesCast($id);
$turnoutPct = $rollCount > 0 ? round(($castNow / $rollCount) * 100, 1) : 0;
$isActive   = $election['status'] === 'active';
$results    = getElectionResults($id);
$totalVotes = $castNow;
$photoBase  = BASE_PATH . '/public/uploads/members/';
$defaultF   = BASE_PATH . '/public/img/female.jpg';
$defaultM   = BASE_PATH . '/public/img/male.jpg';
?>
<style>
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.3} }

/* ── Page top ── */
.r-top { display:flex; align-items:baseline; justify-content:space-between; gap:1rem; flex-wrap:wrap; padding-bottom:1rem; border-bottom:2px solid #0f172a; margin-bottom:1.5rem; }
.r-title { font-size:1.625rem; font-weight:900; color:#0f172a; margin:0; }
.r-meta  { display:flex; align-items:center; gap:.75rem; flex-wrap:wrap; }
.r-live  { display:inline-flex; align-items:center; gap:.35rem; font-size:.75rem; font-weight:700; color:#059669; }
.r-live-dot { width:7px;height:7px;border-radius:50%;background:#059669; animation:pulse 1.4s infinite; }
.r-status { font-size:.75rem; font-weight:600; color:#64748b; }
.r-updated { font-size:.75rem; color:#94a3b8; }
.r-nav { display:flex; gap:.6rem; align-items:center; }

/* ── Turnout strip ── */
.r-turnout { display:flex; align-items:center; gap:1rem; margin-bottom:1.75rem; flex-wrap:wrap; }
.r-turnout-pct { font-size:2.25rem; font-weight:900; color:#0f172a; line-height:1; min-width:70px; }
.r-turnout-right { flex:1; min-width:180px; }
.r-turnout-label { font-size:.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:.07em; margin-bottom:.4rem; }
.r-turnout-track { background:#e2e8f0; height:6px; }
.r-turnout-fill  { height:100%; background:#0f172a; transition:width .7s ease; }
.r-turnout-sub   { display:flex; justify-content:space-between; margin-top:.35rem; font-size:.75rem; color:#94a3b8; }

/* ── Position section ── */
.r-section { margin-bottom:2rem; }
.r-section-head { display:flex; align-items:baseline; justify-content:space-between; margin-bottom:.75rem; }
.r-section-title { font-size:.6875rem; font-weight:700; color:#94a3b8; text-transform:uppercase; letter-spacing:.1em; }
.r-section-sub   { font-size:.75rem; color:#cbd5e1; }

/* ── Candidate row ── */
.r-row { display:grid; grid-template-columns:48px 1fr auto; align-items:center; gap:.875rem; padding:.625rem 0; border-bottom:1px solid #f1f5f9; }
.r-row:last-child { border-bottom:none; }
.r-photo { width:48px; height:56px; object-fit:cover; object-position:top center; display:block; filter:grayscale(15%); }
.r-row.leading .r-photo { filter:none; }
.r-info { min-width:0; }
.r-name { font-size:.9375rem; font-weight:700; color:#0f172a; margin-bottom:.3rem; }
.r-row.leading .r-name { color:#059669; }
.r-bar-track { height:4px; background:#f1f5f9; }
.r-bar-fill  { height:100%; background:#cbd5e1; transition:width .7s ease; }
.r-row.leading .r-bar-fill { background:#059669; }
.r-right { text-align:right; display:flex; flex-direction:column; align-items:flex-end; gap:.1rem; min-width:56px; }
.r-votes { font-size:1.375rem; font-weight:900; color:#0f172a; line-height:1; }
.r-pct   { font-size:.75rem; color:#94a3b8; }
.r-tick  { font-size:.75rem; font-weight:700; color:#059669; }

/* ── Presbyters grid ── */
.r-pres-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:1px; background:#f1f5f9; }
.r-pres-card { background:#fff; padding:1.25rem 1rem; text-align:center; position:relative; }
.r-pres-card.elected { background:#f0fdf4; }
.r-pres-badge { position:absolute; top:.5rem; right:.5rem; font-size:.625rem; font-weight:700; color:#059669; text-transform:uppercase; letter-spacing:.05em; }
.r-pres-photo { width:64px; height:72px; object-fit:cover; object-position:top center; display:block; margin:0 auto .6rem; }
.r-pres-name  { font-size:.8125rem; font-weight:700; color:#0f172a; margin-bottom:.5rem; line-height:1.3; }
.r-pres-votes { font-size:1.625rem; font-weight:900; color:#0f172a; line-height:1; }
.r-pres-lbl   { font-size:.625rem; color:#94a3b8; margin-bottom:.4rem; }
.r-pres-track { background:#e2e8f0; height:3px; margin-bottom:.25rem; }
.r-pres-fill  { height:100%; background:#cbd5e1; transition:width .7s ease; }
.r-pres-card.elected .r-pres-fill { background:#059669; }
.r-pres-pct   { font-size:.6875rem; color:#94a3b8; text-align:right; }
</style>

<!-- ── Header ── -->
<div class="r-top">
    <div>
        <h1 class="r-title"><?= htmlspecialchars($election['title']) ?></h1>
    </div>
    <div class="r-meta">
        <?php if ($isActive): ?>
        <span class="r-live"><span class="r-live-dot"></span>Live</span>
        <?php else: ?>
        <span class="r-status"><?= ucfirst($election['status']) ?></span>
        <?php endif; ?>
        <span class="r-updated">Updated <span id="last-updated">—</span></span>
        <span class="r-updated" style="color:#0f172a;font-weight:700;"><span id="total-votes"><?= $castNow ?></span><?php if ($rollCount>0): ?> / <?= $rollCount ?><?php endif; ?> votes cast</span>
        <span class="r-nav">
            <a href="<?= BASE_PATH ?>/voting" class="link-muted" style="font-size:.8rem;">← Elections</a>
            <?php if (isVoting() || isAdmin()): ?>
            <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="btn btn-outline btn-sm">Manage</a>
            <?php endif; ?>
        </span>
    </div>
</div>

<!-- ── Turnout ── -->
<?php if ($rollCount > 0): ?>
<div class="r-turnout">
    <div class="r-turnout-pct" id="turnout-pct"><?= $turnoutPct ?>%</div>
    <div class="r-turnout-right">
        <div class="r-turnout-label">Voter turnout</div>
        <div class="r-turnout-track"><div class="r-turnout-fill" id="turnout-bar" style="width:<?= $turnoutPct ?>%"></div></div>
        <div class="r-turnout-sub">
            <span><span id="turnout-cast"><?= $castNow ?></span> voted</span>
            <span><?= $rollCount - $castNow ?> remaining</span>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ── Results ── -->
<div id="results-body">

<?php if ($election['type'] === 'presbyters'):
    $nF = (int)($election['number_of_females'] ?? 0);
    $nM = (int)($election['number_of_males']   ?? 0);
    foreach ([
        'females' => ['label'=>'Female Candidates','n'=>$nF,'def'=>$defaultF],
        'males'   => ['label'=>'Male Candidates',  'n'=>$nM,'def'=>$defaultM],
    ] as $key => $cfg):
    $list = $results[$key] ?? [];
?>
<div class="r-section">
    <div class="r-section-head">
        <span class="r-section-title"><?= $cfg['label'] ?></span>
        <?php if ($cfg['n'] > 0): ?><span class="r-section-sub">Top <?= $cfg['n'] ?> to be elected</span><?php endif; ?>
    </div>
    <?php if (empty($list)): ?>
    <p class="text-muted">No candidates.</p>
    <?php else: ?>
    <div class="r-pres-grid" id="grid-<?= $key ?>">
    <?php foreach ($list as $idx => $r):
        $c = $r['candidate'];
        $votes = $r['votes'];
        $pct = $totalVotes > 0 ? round(($votes / $totalVotes) * 100, 1) : 0;
        $elected = $idx < $cfg['n'];
        $name  = trim(($c['first_name'] ?? '') . ' ' . ($c['middle_name'] ?? '') . ' ' . ($c['last_name'] ?? ''));
        $photo = !empty($c['photo']) ? $photoBase . htmlspecialchars($c['photo']) : $cfg['def'];
    ?>
    <div class="r-pres-card <?= $elected ? 'elected' : '' ?>" data-id="<?= $c['id'] ?>">
        <?php if ($elected): ?><div class="r-pres-badge">✓ Elected</div><?php endif; ?>
        <img src="<?= $photo ?>" alt="" class="r-pres-photo" onerror="this.src='<?= $cfg['def'] ?>'">
        <div class="r-pres-name"><?= htmlspecialchars($name) ?></div>
        <div class="r-pres-votes" data-votes><?= $votes ?></div>
        <div class="r-pres-lbl">votes</div>
        <div class="r-pres-track"><div class="r-pres-fill" data-bar style="width:<?= $pct ?>%"></div></div>
        <div class="r-pres-pct" data-pct><?= $pct ?>%</div>
    </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<?php else: /* fellowship */
foreach ($results as $result):
    $posName = $result['position']['name'];
    $posId   = $result['position']['id'];
    $cands   = $result['candidates'] ?? [];
?>
<div class="r-section" id="pos-<?= $posId ?>">
    <div class="r-section-head">
        <span class="r-section-title"><?= htmlspecialchars($posName) ?></span>
        <span class="r-section-sub"><?= count($cands) ?> candidate<?= count($cands) !== 1 ? 's' : '' ?></span>
    </div>
    <?php if (empty($cands)): ?>
    <p class="text-muted">No candidates.</p>
    <?php else:
    foreach ($cands as $idx => $r):
        $c = $r['candidate'];
        $votes = $r['votes'];
        $pct = $totalVotes > 0 ? round(($votes / $totalVotes) * 100, 1) : 0;
        $leading = $idx === 0 && $votes > 0;
        $name  = trim(($c['first_name'] ?? '') . ' ' . ($c['middle_name'] ?? '') . ' ' . ($c['last_name'] ?? ''));
        $gender = strtolower($c['gender'] ?? '');
        $defPhoto = ($gender === 'male' || $gender === 'm') ? $defaultM : $defaultF;
        $photo = !empty($c['photo']) ? $photoBase . htmlspecialchars($c['photo']) : $defPhoto;
    ?>
    <div class="r-row <?= $leading ? 'leading' : '' ?>" data-cand-id="<?= $c['id'] ?>">
        <img src="<?= $photo ?>" alt="" class="r-photo" onerror="this.src='<?= $defPhoto ?>'">
        <div class="r-info">
            <div class="r-name"><?= htmlspecialchars($name) ?></div>
            <div class="r-bar-track"><div class="r-bar-fill" data-bar style="width:<?= $pct ?>%"></div></div>
        </div>
        <div class="r-right">
            <div class="r-votes" data-votes><?= $votes ?></div>
            <div class="r-pct" data-pct><?= $pct ?>%</div>
            <?php if ($leading): ?><div class="r-tick">✓ Elected</div><?php endif; ?>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>

</div>

<script>
(function () {
    var apiUrl    = '<?= BASE_PATH ?>/voting/results-data/<?= $id ?>';
    var isActive  = <?= $isActive ? 'true' : 'false' ?>;
    var type      = '<?= $election['type'] ?>';
    var rollCount = <?= (int)$rollCount ?>;

    function qs(sel) { return document.querySelector(sel); }

    function applyData(data) {
        var tv = document.getElementById('total-votes');
        if (tv) tv.textContent = data.total_votes;
        var lu = document.getElementById('last-updated');
        if (lu) lu.textContent = data.updated_at;

        if (rollCount > 0) {
            var pct = Math.round((data.total_votes / rollCount) * 1000) / 10;
            var bar = document.getElementById('turnout-bar');
            if (bar) bar.style.width = pct + '%';
            var tp = document.getElementById('turnout-pct');
            if (tp) tp.textContent = pct + '%';
            var tc = document.getElementById('turnout-cast');
            if (tc) tc.textContent = data.total_votes;
        }

        if (type === 'presbyters') {
            ['females','males'].forEach(function(g) {
                var grid = document.getElementById('grid-' + g);
                if (!grid) return;
                (data[g] || []).forEach(function(cd) {
                    var card = grid.querySelector('[data-id="' + cd.id + '"]');
                    if (!card) return;
                    var v = card.querySelector('[data-votes]'); if (v) v.textContent = cd.votes;
                    var b = card.querySelector('[data-bar]');   if (b) b.style.width = cd.pct + '%';
                    var p = card.querySelector('[data-pct]');   if (p) p.textContent = cd.pct + '%';
                    card.classList.toggle('elected', cd.elected);
                    var badge = card.querySelector('.r-pres-badge');
                    if (cd.elected && !badge) {
                        badge = document.createElement('div');
                        badge.className = 'r-pres-badge';
                        badge.textContent = '✓ Elected';
                        card.insertBefore(badge, card.firstChild);
                    } else if (!cd.elected && badge) { badge.remove(); }
                });
                var cards = Array.from(grid.querySelectorAll('.r-pres-card'));
                cards.sort(function(a,b){
                    return parseInt(b.querySelector('[data-votes]').textContent||0) -
                           parseInt(a.querySelector('[data-votes]').textContent||0);
                });
                cards.forEach(function(c){ grid.appendChild(c); });
            });
        }
    }

    function poll() {
        fetch(apiUrl).then(function(r){return r.json();}).then(applyData).catch(function(){});
    }

    var lu = document.getElementById('last-updated');
    if (lu) lu.textContent = new Date().toLocaleTimeString();
    setInterval(poll, isActive ? 5000 : 30000);
})();
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
