<?php
/**
 * Real-time results API — returns JSON for the live dashboard.
 * Accessed via /voting/results-data/{id}
 */

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

if (!canManageElection($id)) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied.']);
    exit;
}

$election = getElection($id);
if (!$election) {
    http_response_code(404);
    echo json_encode(['error' => 'Election not found.']);
    exit;
}

$results    = getElectionResults($id);
$totalVotes = getTotalVotesCast($id);
$stats      = getVoterStats($id);
$rollCount  = $stats['eligible'];

$photoBase = BASE_PATH . '/public/uploads/members/';

function buildCandidate($cand, $votes, $totalVotes, $isElected, $photoBase) {
    $name = trim(($cand['first_name'] ?? '') . ' ' . ($cand['middle_name'] ?? '') . ' ' . ($cand['last_name'] ?? ''));
    $pct  = $totalVotes > 0 ? round(($votes / $totalVotes) * 100, 1) : 0;
    return [
        'id'        => $cand['id'],
        'name'      => $name,
        'photo'     => !empty($cand['photo']) ? $photoBase . $cand['photo'] : null,
        'gender'    => strtolower($cand['gender'] ?? ''),
        'votes'     => (int)$votes,
        'pct'       => $pct,
        'elected'   => $isElected,
    ];
}

$payload = [
    'total_votes' => $totalVotes,
    'roll_count'  => $rollCount,
    'status'      => $election['status'],
    'type'        => $election['type'],
    'updated_at'  => date('H:i:s'),
];

if ($election['type'] === 'presbyters') {
    $nF = (int)($election['number_of_females'] ?? 0);
    $nM = (int)($election['number_of_males']   ?? 0);

    $females = [];
    foreach ($results['females'] as $idx => $r) {
        $females[] = buildCandidate($r['candidate'], $r['votes'], $totalVotes, $idx < $nF, $photoBase);
    }
    $males = [];
    foreach ($results['males'] as $idx => $r) {
        $males[] = buildCandidate($r['candidate'], $r['votes'], $totalVotes, $idx < $nM, $photoBase);
    }
    $payload['females']          = $females;
    $payload['males']            = $males;
    $payload['number_of_females'] = $nF;
    $payload['number_of_males']   = $nM;
} else {
    $positions = [];
    foreach ($results as $result) {
        $cands = [];
        foreach ($result['candidates'] as $idx => $r) {
            $cands[] = buildCandidate($r['candidate'], $r['votes'], $totalVotes, $idx === 0, $photoBase);
        }
        $positions[] = [
            'name'       => $result['position']['name'],
            'candidates' => $cands,
        ];
    }
    $payload['positions'] = $positions;
}

header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode($payload);
