<?php
/**
 * Voting Interface - For members to cast votes
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/voting.php';

$fromKiosk = isset($_GET['kiosk']);
if (!$fromKiosk) {
    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;
}

// Simulation mode: only manager or admin
$isSimulation = isset($_GET['simulate']) || (isVoting() && ($election['status'] !== 'active' || isset($_GET['simulate'])));
if ($isSimulation && !canManageElection($id)) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('You do not have permission to run simulation for this election.'));
    exit;
}
$allowVoting = $election['status'] === 'active' && !$isSimulation;

// Resolve voter identity — must come from the kiosk session (secure), never from a GET param.
if ($isSimulation) {
    $currentMemberId = 999999; // dummy for simulation
} elseif ($fromKiosk && !empty($_SESSION['kiosk_voter_id']) && (int)($_SESSION['kiosk_election_id'] ?? 0) === (int)$id) {
    $currentMemberId = (int)$_SESSION['kiosk_voter_id'];
} else {
    // Not coming through the kiosk — reject real voting attempts
    if ($allowVoting) {
        header('Location: ' . BASE_PATH . '/voting/kiosk/' . $id . '?error=' . urlencode('Please use the voting kiosk to cast your vote.'));
        exit;
    }
    $currentMemberId = null;
}

// Guards for live (non-simulation) voting
if ($allowVoting && $currentMemberId) {
    // 1. Eligibility
    if (!isVoterEligible($id, $currentMemberId)) {
        unset($_SESSION['kiosk_voter_id'], $_SESSION['kiosk_election_id']);
        header('Location: ' . BASE_PATH . '/voting/kiosk/' . $id . '?error=' . urlencode('You are not on the eligible voter list for this election.'));
        exit;
    }
    // 2. Must have checked in
    if (!hasMemberCheckedIn($id, $currentMemberId)) {
        unset($_SESSION['kiosk_voter_id'], $_SESSION['kiosk_election_id']);
        header('Location: ' . BASE_PATH . '/voting/kiosk/' . $id . '?error=' . urlencode('You must be checked in before you can vote. Please see the check-in desk.'));
        exit;
    }
    // 3. Already voted
    if (hasMemberVoted($id, $currentMemberId)) {
        unset($_SESSION['kiosk_voter_id'], $_SESSION['kiosk_election_id']);
        header('Location: ' . BASE_PATH . '/voting/kiosk/' . $id . '?error=' . urlencode('You have already voted in this election. Thank you!'));
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($allowVoting || ($isSimulation && $election['type'] === 'presbyters'))) {
    if ($election['type'] === 'fellowship') {
        $positions = getElectionPositions($id);
        $allVoted = true;
        foreach ($positions as $pos) {
            $candidateId = (int)($_POST['position_' . $pos['id']] ?? 0);
            if ($candidateId <= 0) {
                $allVoted = false;
                break;
            }
            try {
                $stmt = $pdo->prepare('INSERT INTO election_votes (election_id, voter_member_id, voter_id, position_id, candidate_id) VALUES (?, ?, ?, ?, ?)');
                $stmt->execute([$id, $currentMemberId, $currentMemberId, $pos['id'], $candidateId]);
            } catch (PDOException $e) {
                header('Location: ' . BASE_PATH . '/voting/vote/' . $id . '?toast_error=' . urlencode('Error recording vote.'));
                exit;
            }
        }
        if ($allVoted) {
            markPinUsed($id, $currentMemberId);
            unset($_SESSION['kiosk_voter_id'], $_SESSION['kiosk_election_id']);
            if ($fromKiosk) {
                header('Location: ' . BASE_PATH . '/voting/kiosk/' . $id . '?toast=' . urlencode('Thank you for voting!'));
            } else {
                header('Location: ' . BASE_PATH . '/voting/results/' . $id . '?toast=' . urlencode('Thank you for voting!'));
            }
            exit;
        }
    } else {
        // Presbyters election
        $selectedFemales = array_filter(array_map('intval', $_POST['female_candidates'] ?? []));
        $selectedMales = array_filter(array_map('intval', $_POST['male_candidates'] ?? []));
        $requiredFemales = (int)($election['number_of_females'] ?? 0);
        $requiredMales = (int)($election['number_of_males'] ?? 0);
        
        // Allow up to the required number each (submit with fewer is OK)
        if (count($selectedFemales) > $requiredFemales || count($selectedMales) > $requiredMales) {
            header('Location: ' . BASE_PATH . '/voting/vote/' . $id . ($isSimulation ? '?simulate=1&' : '?') . 'toast_error=' . urlencode("You may select at most {$requiredFemales} female(s) and {$requiredMales} male(s)."));
            exit;
        }
        
        // Build receipt (names and photo URLs for selected candidates)
        $femaleCands = getPresbytersCandidates($id, 'Female');
        $maleCands = getPresbytersCandidates($id, 'Male');
        $idToName = function($list) {
            $out = [];
            foreach ($list as $c) {
                $name = trim(($c['first_name'] ?? '') . ' ' . ($c['middle_name'] ?? '') . ' ' . ($c['last_name'] ?? ''));
                $out[(int)$c['id']] = $name ?: 'Candidate';
            }
            return $out;
        };
        $idToPhoto = function($list, $defaultPath) {
            $out = [];
            foreach ($list as $c) {
                $photo = !empty($c['photo']) ? BASE_PATH . '/public/uploads/members/' . $c['photo'] : BASE_PATH . $defaultPath;
                $out[(int)$c['id']] = $photo;
            }
            return $out;
        };
        $femaleNames = $idToName($femaleCands);
        $maleNames = $idToName($maleCands);
        $femalePhotos = $idToPhoto($femaleCands, '/public/img/female.jpg');
        $malePhotos = $idToPhoto($maleCands, '/public/img/male.jpg');
        $receiptFemales = array_map(function($cid) use ($femaleNames) { return $femaleNames[$cid] ?? '#' . $cid; }, $selectedFemales);
        $receiptMales = array_map(function($cid) use ($maleNames) { return $maleNames[$cid] ?? '#' . $cid; }, $selectedMales);
        $receiptFemalePhotos = array_map(function($cid) use ($femalePhotos) { return $femalePhotos[$cid] ?? BASE_PATH . '/public/img/female.jpg'; }, $selectedFemales);
        $receiptMalePhotos = array_map(function($cid) use ($malePhotos) { return $malePhotos[$cid] ?? BASE_PATH . '/public/img/male.jpg'; }, $selectedMales);
        
        if (!$isSimulation) {
            try {
                foreach ($selectedFemales as $candidateId) {
                    $stmt = $pdo->prepare('INSERT INTO election_votes (election_id, voter_member_id, voter_id, candidate_id) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$id, $currentMemberId, $currentMemberId, $candidateId]);
                }
                foreach ($selectedMales as $candidateId) {
                    $stmt = $pdo->prepare('INSERT INTO election_votes (election_id, voter_member_id, voter_id, candidate_id) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$id, $currentMemberId, $currentMemberId, $candidateId]);
                }
            } catch (PDOException $e) {
                header('Location: ' . BASE_PATH . '/voting/vote/' . $id . '?toast_error=' . urlencode('Error recording vote.'));
                exit;
            }
        }
        
        if (!$isSimulation) {
            markPinUsed($id, $currentMemberId);
        }
        unset($_SESSION['kiosk_voter_id'], $_SESSION['kiosk_election_id']);
        $_SESSION['vote_receipt'] = [
            'election_id'    => (int)$id,
            'election_title' => $election['title'],
            'female_names'   => $receiptFemales,
            'male_names'     => $receiptMales,
            'female_photos'  => $receiptFemalePhotos,
            'male_photos'    => $receiptMalePhotos,
            'simulation'     => $isSimulation,
            'from_kiosk'     => $fromKiosk,
        ];
        $thankUrl = BASE_PATH . '/voting/vote/' . $id . '?thankyou=1';
        if ($isSimulation) $thankUrl .= '&simulate=1';
        if ($fromKiosk)    $thankUrl .= '&kiosk=1';
        header('Location: ' . $thankUrl);
        exit;
    }
}

$pageTitle = 'Vote: ' . htmlspecialchars($election['title']);

if ($fromKiosk) {
    // ── Kiosk: standalone full-screen layout (no sidebar, no nav) ────────────
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($election['title']) ?></title>
    <link rel="icon" href="<?= BASE_PATH ?>/public/img/logo.png" type="image/png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= BASE_PATH ?>/public/css/style.css?v=<?= filemtime(__DIR__ . '/../../public/css/style.css') ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer">
    <style>
        *, *::before, *::after { box-sizing: border-box; }
        html { height: 100%; }
        body {
            margin: 0; min-height: 100vh; background: #f0f4ff;
            font-family: 'Inter', sans-serif;
            display: flex; align-items: center; justify-content: center;
        }

        /* ── Wrap ── */
        .kiosk-vote-wrap {
            width: 100%; max-width: 980px;
            padding: 3rem 2rem;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        /* ── Card reset → clean white panel ── */
        .card {
            width: 100%;
            background: #fff !important;
            border: none !important;
            border-radius: 20px !important;
            padding: 2.5rem 2rem !important;
            box-shadow: 0 4px 32px rgba(11,27,137,0.09) !important;
        }

        /* ── Fellowship step container ── */
        .fellowship-step {
            max-width: 720px;
            margin: 0 auto;
            text-align: center;
        }

        /* ── Step header ── */
        .vote-step-heading {
            display: flex; align-items: center; justify-content: center; gap: 0.65rem;
            margin-bottom: 0.3rem;
        }
        .step-pill {
            background: #0b1b89; color: #fff;
            font-size: 0.6875rem; font-weight: 700;
            letter-spacing: 0.06em; text-transform: uppercase;
            border-radius: 999px; padding: 0.22rem 0.7rem;
            flex-shrink: 0;
        }
        .vote-step-heading h3 {
            font-size: 1.375rem; font-weight: 700;
            color: #0f172a; margin: 0;
        }
        .vote-step-sub {
            display: inline-block;
            font-size: 1rem; font-weight: 700; color: #0b1b89;
            background: #eef2ff; border: 2px solid #c7d2fe;
            border-radius: 8px; padding: 0.5rem 1.25rem;
            margin: 0.5rem auto 1.75rem;
        }

        /* ── Candidate grid ── */
        .cand-grid {
            display: flex !important;
            flex-wrap: wrap !important;
            justify-content: center !important;
            gap: 1.25rem !important;
        }

        /* ── Candidate cards ── */
        .candidate-card {
            width: 215px !important;
            flex-shrink: 0 !important;
            border-radius: 20px !important;
            border: 3px solid #e8edf2 !important;
            padding: 1.75rem 1rem 1.25rem !important;
            min-height: 0 !important;
            transition: border-color 0.15s, box-shadow 0.15s, transform 0.1s !important;
        }
        .candidate-card:hover {
            border-color: #0b1b89 !important;
            box-shadow: 0 8px 24px rgba(11,27,137,0.13) !important;
            transform: translateY(-3px) !important;
        }
        .candidate-card:active { transform: scale(0.97) !important; }

        /* ── Candidate photo ── */
        .candidate-image {
            width: 100% !important; height: 220px !important;
            border: 4px solid #e8edf2 !important;
            border-radius: 14px !important;
            margin-bottom: 1rem !important;
            transition: border-color 0.15s !important;
            filter: none !important;
            object-fit: cover !important;
            object-position: top center !important;
            display: block !important;
        }

        /* ── Candidate name ── */
        .candidate-card > div:last-child {
            font-weight: 700 !important;
            font-size: 1.0625rem !important;
            line-height: 1.35 !important;
            color: #1e293b !important;
            text-align: center !important;
        }

        /* ── Selection indicator ── */
        .selection-indicator {
            top: 0.75rem !important; right: 0.75rem !important;
            width: 34px !important; height: 34px !important;
            border: 3px solid #dde3eb !important;
            background: #f8fafc !important;
        }
        .selection-fill { background: #0b1b89 !important; }

        /* ── Counter ── */
        #female_count, #male_count {
            display: inline-flex !important;
            align-items: center;
            background: #f1f5f9 !important;
            border: 1.5px solid #e2e8f0 !important;
            border-radius: 999px !important;
            padding: 0.3rem 0.9rem !important;
            font-size: 0.8125rem !important;
            font-weight: 600 !important;
            color: #374151 !important;
            margin: 0.25rem 0 1.25rem !important;
        }

        /* ── Nav button row ── */
        .form-actions { display: flex; justify-content: center; }

        /* ── Nav buttons ── */
        .vote-nav-btn {
            width: 54px !important; height: 54px !important;
            border-radius: 50% !important;
            font-size: 1rem !important;
            border: none !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            transition: transform 0.1s, box-shadow 0.15s !important;
        }
        .vote-nav-btn:hover  { transform: scale(1.08) !important; }
        .vote-nav-btn:active { transform: scale(0.93) !important; }
        .vote-nav-next {
            background: #059669 !important; color: #fff !important;
            box-shadow: 0 4px 14px rgba(5,150,105,0.4) !important;
        }
        .vote-nav-prev {
            background: #dc2626 !important; color: #fff !important;
            box-shadow: 0 4px 14px rgba(220,38,38,0.35) !important;
        }

        /* ── Confirmation modal ── */
        .modal-content {
            border-radius: 24px !important;
            padding: 2.5rem !important;
            width: 90vw !important;
            max-width: 780px !important;
        }
        .modal-heading { font-size: 1.375rem !important; font-weight: 700 !important; margin-bottom: 0.5rem !important; }
        .vote-confirm-thumbnails { gap: 1.25rem !important; justify-content: center; }
        .vote-confirm-thumb img  { width: 100px !important; height: 100px !important; border-radius: 50% !important; }

        /* ── Simulation banner ── */
        .sim-banner {
            background: #fff8e1; border-left: 4px solid #f59e0b;
            border-radius: 10px; padding: 0.875rem 1rem;
            margin-bottom: 1.5rem; font-size: 0.9rem;
        }

        /* ── Thank-you card ── */
        .thankyou-card {
            max-width: 520px; margin: 2rem auto; text-align: center;
            background: #fff; border-radius: 20px;
            padding: 2.5rem 2rem; box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        .thankyou-icon {
            font-size: 3rem; margin-bottom: 0.75rem; display: block;
        }
        .receipt-box {
            background: #f8fafc; border: 1.5px solid #e2e8f0;
            border-radius: 12px; padding: 1.25rem;
            margin-bottom: 1.5rem; text-align: left;
        }

        /* Toast */
        .toast-container { position: fixed; bottom: 1rem; right: 1rem; z-index: 9999; }
    </style>
</head>
<body>
<div class="kiosk-vote-wrap">
<?php } else {
    require_once __DIR__ . '/../../includes/header.php';
}

// Thank-you view after voting (Presbyters): receipt + next voter
$showThankYou = isset($_GET['thankyou']) && isset($_SESSION['vote_receipt']) && ($_SESSION['vote_receipt']['election_id'] ?? 0) == (int)$id;
if ($showThankYou && $election['type'] === 'presbyters') {
    $receipt = $_SESSION['vote_receipt'];
    $_SESSION['vote_receipt'] = null;
    $receiptFromKiosk = !empty($receipt['from_kiosk']);
    $simQ = $isSimulation ? '?simulate=1' : '';
    $nextUrl = $receiptFromKiosk
        ? BASE_PATH . '/voting/kiosk/' . (int)$id
        : (BASE_PATH . '/voting/vote/' . (int)$id . $simQ);
?>
<?php if (!$receiptFromKiosk): ?>
<div class="header">
    <h1><?= htmlspecialchars($election['title']) ?><?= $isSimulation ? ' (Simulation)' : '' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/voting" class="link-muted">← Elections</a>
    </div>
</div>
<?php endif; ?>
<div class="card" style="max-width: 560px; margin: 2rem auto; text-align: center;">
    <h2 style="margin-top: 0; color: #059669;">Thank you for voting</h2>
    <p style="font-size: 1.125rem; margin-bottom: 1.5rem;">Your vote has been recorded<?= $isSimulation ? ' (simulation)' : '' ?>.</p>
    <div class="vote-receipt" style="text-align: left; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 1.25rem; margin-bottom: 1.5rem;">
        <p style="margin: 0 0 0.75rem; font-weight: 600;">Receipt</p>
        <?php
        $receiptFemales = $receipt['female_names'] ?? [];
        $receiptMales = $receipt['male_names'] ?? [];
        $receiptFemalePhotos = $receipt['female_photos'] ?? array_fill(0, count($receiptFemales), BASE_PATH . '/public/img/female.jpg');
        $receiptMalePhotos = $receipt['male_photos'] ?? array_fill(0, count($receiptMales), BASE_PATH . '/public/img/male.jpg');
        ?>
        <?php if (!empty($receiptFemales)): ?>
        <p style="margin: 0 0 0.35rem; font-size: 0.875rem; font-weight: 600;">Female<?= count($receiptFemales) > 1 ? 's' : '' ?></p>
        <div class="vote-receipt-thumbnails" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem;">
            <?php foreach (array_values($receiptFemales) as $i => $name): $photo = $receiptFemalePhotos[$i] ?? BASE_PATH . '/public/img/female.jpg'; ?>
            <div style="text-align: center;">
                <img src="<?= htmlspecialchars($photo) ?>" alt="" style="width: 56px; height: 56px; object-fit: cover; border-radius: 50%; display: block;" onerror="this.src='<?= htmlspecialchars(BASE_PATH) ?>/public/img/female.jpg'">
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <?php if (!empty($receiptMales)): ?>
        <p style="margin: 0 0 0.35rem; font-size: 0.875rem; font-weight: 600;">Male<?= count($receiptMales) > 1 ? 's' : '' ?></p>
        <div class="vote-receipt-thumbnails" style="display: flex; flex-wrap: wrap; gap: 0.5rem;">
            <?php foreach (array_values($receiptMales) as $i => $name): $photo = $receiptMalePhotos[$i] ?? BASE_PATH . '/public/img/male.jpg'; ?>
            <div style="text-align: center;">
                <img src="<?= htmlspecialchars($photo) ?>" alt="" style="width: 56px; height: 56px; object-fit: cover; border-radius: 50%; display: block;" onerror="this.src='<?= htmlspecialchars(BASE_PATH) ?>/public/img/male.jpg'">
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
        <?php if (empty($receiptFemales) && empty($receiptMales)): ?>
        <p style="margin: 0; font-size: 0.9375rem; color: #64748b;">No candidates selected.</p>
        <?php endif; ?>
    </div>
    <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 0;" id="receipt-countdown">Redirecting for next voter in <span id="receipt-seconds">10</span> seconds...</p>
</div>
<script>
(function() {
    var nextUrl = '<?= addslashes($nextUrl) ?>';
    var sec = 10;
    var el = document.getElementById('receipt-seconds');
    var countdown = document.getElementById('receipt-countdown');
    var t = setInterval(function() {
        sec--;
        if (el) el.textContent = sec;
        if (sec <= 0) {
            clearInterval(t);
            window.location = nextUrl;
        }
    }, 1000);
    setTimeout(function() { window.location = nextUrl; }, 10000);
})();
</script>
<?php
    if ($receiptFromKiosk) {
        ?>
        <div id="toast-container" class="toast-container" aria-live="polite"></div>
        <script src="<?= BASE_PATH ?>/public/js/main.js"></script>
        </div><!-- /.kiosk-vote-wrap -->
        </body></html>
        <?php
    } else {
        require_once __DIR__ . '/../../includes/footer.php';
    }
    exit;
}
?>

<?php if (!$fromKiosk): ?>
<div class="header">
    <h1><?= htmlspecialchars($election['title']) ?><?= $isSimulation ? ' (Simulation)' : '' ?></h1>
    <div class="header-actions">
        <?php if ($isSimulation): ?>
        <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="btn btn-outline">Back to Manage</a>
        <?php endif; ?>
        <a href="<?= BASE_PATH ?>/voting" class="link-muted">← Elections</a>
    </div>
</div>
<?php else: ?>
<div style="text-align:center; margin-bottom:2rem; width:100%;">
    <div style="display:inline-flex; align-items:center; gap:0.5rem; background:#0b1b89; color:#fff; font-size:0.6875rem; font-weight:700; letter-spacing:0.08em; text-transform:uppercase; border-radius:999px; padding:0.3rem 0.9rem; margin-bottom:0.75rem;">
        <span style="width:8px;height:8px;border-radius:50%;background:#4ade80;display:inline-block;"></span>
        Voting in progress
    </div>
    <h1 style="margin:0; font-size:1.75rem; font-weight:800; color:#0f172a; line-height:1.2;"><?= htmlspecialchars($election['title']) ?></h1>
</div>
<?php endif; ?>

<?php if ($isSimulation): ?>
<div class="card" style="margin-bottom: 1.5rem; background: #fff3cd; border-left: 3px solid #ffc107;">
    <p style="margin: 0;"><strong>Simulation Mode:</strong> This is a preview of how voters will see the voting interface. You cannot submit votes in this mode.</p>
</div>
<?php endif; ?>

<div class="card">
    <?php if ($election['type'] === 'fellowship' && !$fromKiosk): ?><p class="text-muted" style="margin-bottom:1.5rem;">Please select your choices below.</p><?php endif; ?>
    
    <form method="post">
        <!-- Voting configuration for JavaScript -->
        <?php if ($election['type'] === 'presbyters'): ?>
        <?php
        $requiredFemales = (int)($election['number_of_females'] ?? 0);
        $requiredMales = (int)($election['number_of_males'] ?? 0);
        ?>
        <div id="voting-config" 
             data-simulation="<?= $isSimulation ? 'true' : 'false' ?>"
             data-required-females="<?= $requiredFemales ?>"
             data-required-males="<?= $requiredMales ?>"
             style="display: none;"></div>
        <?php else: ?>
        <div id="voting-config" 
             data-simulation="<?= $isSimulation ? 'true' : 'false' ?>"
             data-required-females="0"
             data-required-males="0"
             style="display: none;"></div>
        <?php endif; ?>
        
        <?php if ($election['type'] === 'fellowship'): ?>
        <?php
        $positions = getElectionPositions($id);
        $totalSteps = count($positions);
        ?>

        <?php foreach ($positions as $stepIdx => $pos):
            $stepNum   = $stepIdx + 1;
            $candidates = getPositionCandidates($pos['id']);
        ?>
        <div class="fellowship-step" id="fstep-<?= $stepIdx ?>"
             data-pos-id="<?= $pos['id'] ?>"
             data-pos-name="<?= htmlspecialchars($pos['name'], ENT_QUOTES) ?>"
             style="<?= $stepIdx > 0 ? 'display:none;' : '' ?>margin-bottom: 2rem;">

            <div class="vote-step-heading">
                <span class="step-pill">Position <?= $stepNum ?> of <?= $totalSteps ?></span>
                <h3><?= htmlspecialchars($pos['name']) ?></h3>
            </div>
            <p class="vote-step-sub">Select one candidate</p>

            <?php if (empty($candidates)): ?>
            <p class="text-muted">No candidates for this position.</p>
            <?php else: ?>
            <div class="cand-grid" style="margin-bottom: 1.5rem;">
                <?php foreach ($candidates as $cand):
                    $name   = trim(($cand['first_name'] ?? '') . ' ' . ($cand['middle_name'] ?? '') . ' ' . ($cand['last_name'] ?? ''));
                    $gender = strtolower($cand['gender'] ?? '');
                    $photoUrl = !empty($cand['photo'])
                        ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($cand['photo'])
                        : BASE_PATH . '/public/img/' . (($gender === 'male' || $gender === 'm') ? 'male' : 'female') . '.jpg';
                ?>
                <label class="candidate-card candidate-radio-card"
                       data-candidate-id="<?= $cand['id'] ?>"
                       data-candidate-name="<?= htmlspecialchars($name ?: 'Candidate', ENT_QUOTES) ?>"
                       data-candidate-photo="<?= htmlspecialchars($photoUrl, ENT_QUOTES) ?>"
                       for="position_<?= $pos['id'] ?>_<?= $cand['id'] ?>"
                       style="display:block; padding:1.75rem 1rem 1.25rem; border:3px solid #e8edf2; border-radius:20px; cursor:pointer; text-align:center; transition:all 0.15s; position:relative; background:#fff;">
                    <input type="radio" name="position_<?= $pos['id'] ?>" value="<?= $cand['id'] ?>"
                           id="position_<?= $pos['id'] ?>_<?= $cand['id'] ?>"
                           style="position:absolute;left:-9999px;" class="candidate-radio fellowship-radio">
                    <div class="selection-indicator" style="position:absolute; top:0.75rem; right:0.75rem; width:34px; height:34px; border:3px solid #dde3eb; border-radius:50%; background:#f8fafc; transition:all 0.15s; display:flex; align-items:center; justify-content:center;">
                        <div class="selection-fill" style="width:0; height:0; border-radius:50%; background:#0b1b89; transition:all 0.15s;"></div>
                    </div>
                    <img src="<?= $photoUrl ?>" alt="" class="candidate-image"
                         style="width:100%; height:220px; object-fit:cover; object-position:top center; border-radius:14px; margin-bottom:1rem; display:block; border:4px solid #e8edf2; transition:all 0.15s;"
                         onerror="this.src='<?= BASE_PATH ?>/public/img/<?= ($gender === 'male' || $gender === 'm') ? 'male' : 'female' ?>.jpg'">
                    <div style="font-weight:700; font-size:1rem; line-height:1.35; color:#1e293b;"><?= htmlspecialchars($name ?: 'Candidate') ?></div>
                </label>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="form-actions" style="gap: 1rem; margin-top: 1rem;">
                <?php if ($stepIdx > 0): ?>
                <button type="button" class="vote-nav-btn vote-nav-prev fellowship-prev" data-step="<?= $stepIdx ?>"
                        aria-label="Back" title="Back">
                    <i class="fas fa-times" aria-hidden="true"></i>
                </button>
                <?php endif; ?>
                <?php if ($stepIdx < $totalSteps - 1): ?>
                <button type="button" class="vote-nav-btn vote-nav-next fellowship-next" data-step="<?= $stepIdx ?>"
                        aria-label="Next position" title="Next position">
                    <i class="fas fa-arrow-right" aria-hidden="true"></i>
                </button>
                <?php else: ?>
                <button type="button" class="vote-nav-btn vote-nav-next" id="fellowship-confirm-btn"
                        aria-label="Review and submit" title="Review and submit">
                    <i class="fas fa-check" aria-hidden="true"></i>
                </button>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Fellowship confirm modal -->
        <div id="fellowship-confirm-modal" class="modal" role="dialog" aria-modal="true" hidden>
            <div class="modal-backdrop"></div>
            <div class="modal-content" style="max-width:780px;">
                <h2 class="modal-heading" style="margin-top:0;">Confirm your votes</h2>
                <p class="text-muted" style="margin-bottom:1rem;">Review your selections before submitting.</p>
                <div id="fellowship-confirm-list" style="margin-bottom:1.25rem;"></div>
                <div class="modal-actions" style="display:flex; gap:1rem; justify-content:center; flex-wrap:wrap;">
                    <button type="button" id="fellowship-confirm-back" class="vote-nav-btn vote-nav-prev"
                            aria-label="Back" title="Back to review">
                        <i class="fas fa-times" aria-hidden="true"></i>
                    </button>
                    <button type="submit" class="vote-nav-btn vote-nav-next"
                            aria-label="Submit votes" title="Submit votes">
                        <i class="fas fa-check" aria-hidden="true"></i>
                    </button>
                </div>
            </div>
        </div>

        <script>
        (function () {
            var totalSteps = <?= $totalSteps ?>;

            function getStep(n) { return document.getElementById('fstep-' + n); }

            function showStep(n) {
                for (var i = 0; i < totalSteps; i++) {
                    var s = getStep(i);
                    if (s) s.style.display = (i === n) ? '' : 'none';
                }
                window.scrollTo(0, 0);
            }

            function getSelectedInStep(n) {
                var step = getStep(n);
                if (!step) return null;
                return step.querySelector('.fellowship-radio:checked');
            }

            // Prev buttons
            document.querySelectorAll('.fellowship-prev').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    showStep(parseInt(this.dataset.step) - 1);
                });
            });

            // Next buttons
            document.querySelectorAll('.fellowship-next').forEach(function (btn) {
                btn.addEventListener('click', function () {
                    var step = parseInt(this.dataset.step);
                    if (!getSelectedInStep(step)) {
                        alert('Please select a candidate before continuing.');
                        return;
                    }
                    showStep(step + 1);
                });
            });

            // Radio card visual feedback
            document.querySelectorAll('.fellowship-radio').forEach(function (radio) {
                radio.addEventListener('change', function () {
                    var posName = 'position_' + this.name.split('_').slice(1).join('_'); // same name group
                    document.querySelectorAll('input[name="' + this.name + '"]').forEach(function (r) {
                        var card = r.closest('label');
                        if (!card) return;
                        var ind = card.querySelector('.selection-indicator');
                        var fill = card.querySelector('.selection-fill');
                        if (r.checked) {
                            card.style.borderColor = '#059669';
                            card.style.outline = '4px solid #059669';
                            card.style.outlineOffset = '3px';
                            card.style.background = '#f0fdf4';
                            if (ind) { ind.style.background = '#059669'; ind.style.borderColor = '#059669'; }
                            if (fill) { fill.style.width = '48px'; fill.style.height = '48px'; fill.innerHTML = '<span style="color:#fff;font-size:1.5rem;font-weight:900;line-height:1;pointer-events:none;">&#10003;</span>'; }
                        } else {
                            card.style.borderColor = '#e8edf2';
                            card.style.outline = '';
                            card.style.background = '#fff';
                            if (ind) { ind.style.background = '#f8fafc'; ind.style.borderColor = '#dde3eb'; }
                            if (fill) { fill.style.width = '0'; fill.style.height = '0'; fill.innerHTML = ''; }
                        }
                    });
                });
            });

            // Confirm button — build summary modal
            var confirmBtn = document.getElementById('fellowship-confirm-btn');
            if (confirmBtn) {
                confirmBtn.addEventListener('click', function () {
                    var lastStep = totalSteps - 1;
                    if (!getSelectedInStep(lastStep)) {
                        alert('Please select a candidate before continuing.');
                        return;
                    }
                    // Build list
                    var list = document.getElementById('fellowship-confirm-list');
                    list.innerHTML = '';
                    for (var i = 0; i < totalSteps; i++) {
                        var step = getStep(i);
                        var posName = step.dataset.posName;
                        var radio = step.querySelector('.fellowship-radio:checked');
                        var label = radio ? radio.closest('label') : null;
                        var candName = label ? label.dataset.candidateName : '—';
                        var candPhoto = label ? label.dataset.candidatePhoto : '';
                        var row = document.createElement('div');
                        row.style.cssText = 'display:flex; align-items:center; gap:1rem; padding:.6rem 0; border-bottom:1px solid #f1f5f9;';
                        row.innerHTML = '<img src="' + candPhoto + '" style="width:52px;height:52px;border-radius:8px;object-fit:cover;object-position:top center;flex-shrink:0;">'
                            + '<div><div style="font-size:.75rem;color:#64748b;font-weight:600;text-transform:uppercase;letter-spacing:.05em;">' + posName + '</div>'
                            + '<div style="font-weight:700;color:#1e293b;font-size:.95rem;">' + candName + '</div></div>';
                        list.appendChild(row);
                    }
                    document.getElementById('fellowship-confirm-modal').hidden = false;
                });
            }

            // Back from confirm
            var backBtn = document.getElementById('fellowship-confirm-back');
            if (backBtn) {
                backBtn.addEventListener('click', function () {
                    document.getElementById('fellowship-confirm-modal').hidden = true;
                });
            }
        })();
        </script>

        
        <?php else: ?>
        <!-- Presbyters Election -->
        <?php
        $femaleCandidates = getPresbytersCandidates($id, 'Female');
        $maleCandidates = getPresbytersCandidates($id, 'Male');
        ?>
        
        <div id="vote-step-1" class="vote-step" style="margin-bottom: 2rem;">
            <div class="vote-step-heading">
                <span class="step-pill">Step 1 of 2</span>
                <h3>Female Candidates</h3>
            </div>
            <p class="vote-step-sub">Select up to <?= $requiredFemales ?> female candidate<?= $requiredFemales !== 1 ? 's' : '' ?></p>
            <?php
            $femaleCount = count($femaleCandidates);
            $femalePlaceholders = max(0, $requiredFemales - $femaleCount);
            ?>
            <?php if (empty($femaleCandidates) && $femalePlaceholders === 0): ?>
            <p class="text-muted">No female candidates.</p>
            <div class="form-actions" style="margin-top: 1.5rem;">
                <button type="button" id="vote-continue-to-males-empty" class="vote-nav-btn vote-nav-next vote-continue-to-males" aria-label="Continue to Male Candidates" title="Continue to Male Candidates">
                    <i class="fas fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
            <?php else: ?>
            <div class="cand-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 0.875rem; margin-bottom: 1.25rem;">
                <?php foreach ($femaleCandidates as $cand): ?>
                <?php
                $name = trim(($cand['first_name'] ?? '') . ' ' . ($cand['middle_name'] ?? '') . ' ' . ($cand['last_name'] ?? ''));
                $photoUrl = !empty($cand['photo']) ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($cand['photo']) : BASE_PATH . '/public/img/female.jpg';
                ?>
                <label style="display:block; padding:1.75rem 1rem 1.25rem; border:3px solid #e8edf2; border-radius:20px; cursor:pointer; text-align:center; transition:all 0.15s; position:relative; background:#fff;" class="candidate-card candidate-checkbox-card" data-candidate-id="<?= $cand['id'] ?>" data-gender="female" data-candidate-name="<?= htmlspecialchars($name ?: 'Candidate') ?>" data-candidate-photo="<?= htmlspecialchars($photoUrl) ?>" for="female_<?= $cand['id'] ?>">
                    <input type="checkbox" name="female_candidates[]" value="<?= $cand['id'] ?>" id="female_<?= $cand['id'] ?>" style="position:absolute;left:-9999px;" class="female-candidate-check">
                    <div class="selection-indicator" style="position:absolute; top:0.75rem; right:0.75rem; width:34px; height:34px; border:3px solid #dde3eb; border-radius:50%; background:#f8fafc; transition:all 0.15s; display:flex; align-items:center; justify-content:center;">
                        <div class="selection-fill" style="width:0; height:0; border-radius:50%; background:#0b1b89; transition:all 0.15s;"></div>
                    </div>
                    <img src="<?= $photoUrl ?>" alt="" class="candidate-image" style="width:100%; height:220px; object-fit:cover; object-position:top center; border-radius:14px; margin-bottom:1rem; display:block; border:4px solid #e8edf2; transition:all 0.15s;" onerror="this.src='<?= BASE_PATH ?>/public/img/female.jpg'">
                    <div style="font-weight:700; font-size:1rem; line-height:1.35; color:#1e293b;"><?= htmlspecialchars($name ?: 'Candidate') ?></div>
                </label>
                <?php endforeach; ?>
                
                <?php for ($i = 0; $i < $femalePlaceholders; $i++): ?>
                <div style="display: block; padding: 1.5rem; border: 2px dashed var(--border, #e2e8f0); border-radius: 8px; text-align: center; opacity: 0.6; min-height: 200px; background: #f8f9fa;">
                    <img src="<?= BASE_PATH ?>/public/img/female.jpg" alt="" style="width: 120px; height: 120px; object-fit: cover; border-radius: 50%; margin-bottom: 1rem; display: block; margin-left: auto; margin-right: auto; filter: grayscale(100%);">
                    <div style="font-weight: 500; color: var(--text-muted, #718096); font-size: 1rem;">Placeholder</div>
                </div>
                <?php endfor; ?>
            </div>
            <p class="text-muted" style="margin-top: 0.5rem; font-size: 0.875rem;" id="female_count">Selected: 0 / <?= $requiredFemales ?></p>
            <div class="form-actions" style="margin-top: 1.5rem;">
                <button type="button" id="vote-confirm-females" class="vote-nav-btn vote-nav-next vote-confirm-females-btn" aria-label="Confirm female selections" title="Confirm female selections">
                    <i class="fas fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Modal: Confirm female selections -->
        <div id="vote-confirm-females-modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="vote-confirm-females-modal-title" hidden>
            <div class="modal-backdrop vote-confirm-females-backdrop"></div>
            <div class="modal-content" style="max-width: 780px;">
                <h2 id="vote-confirm-females-modal-title" class="modal-heading" style="margin-top: 0;">Confirm your female selections</h2>
                <p class="text-muted" style="margin-bottom: 1rem;">Review your choices below.</p>
                <div id="vote-confirm-females-only" class="vote-confirm-thumbnails" style="display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: center; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 1rem; margin-bottom: 1.25rem; min-height: 60px;"></div>
                <div class="modal-actions" style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                    <button type="button" id="vote-back-from-female-confirm" class="vote-nav-btn vote-nav-prev" aria-label="Back to edit" title="Back to edit">
                        <i class="fas fa-times" aria-hidden="true"></i>
                    </button>
                    <button type="button" id="vote-continue-after-female-confirm" class="vote-nav-btn vote-nav-next" aria-label="Continue to Male Candidates" title="Continue to Male Candidates">
                        <i class="fas fa-arrow-right" aria-hidden="true"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <div id="vote-step-2" class="vote-step" style="margin-bottom: 2rem; display: none;">
            <div class="vote-step-heading">
                <span class="step-pill">Step 2 of 2</span>
                <h3>Male Candidates</h3>
            </div>
            <p class="vote-step-sub">Select up to <?= $requiredMales ?> male candidate<?= $requiredMales !== 1 ? 's' : '' ?></p>
            <?php
            $maleCount = count($maleCandidates);
            $malePlaceholders = max(0, $requiredMales - $maleCount);
            ?>
            <?php if (empty($maleCandidates) && $malePlaceholders === 0): ?>
            <p class="text-muted">No male candidates.</p>
            <div class="form-actions" style="margin-top: 1.5rem;">
                <?php if ($isSimulation): ?>
                <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="vote-nav-btn vote-nav-prev" aria-label="Back to Manage" title="Back to Manage">
                    <i class="fas fa-times" aria-hidden="true"></i>
                </a>
                <?php else: ?>
                <a href="<?= BASE_PATH ?>/voting" class="vote-nav-btn vote-nav-prev" aria-label="Cancel" title="Cancel">
                    <i class="fas fa-times" aria-hidden="true"></i>
                </a>
                <?php endif; ?>
                <button type="button" id="vote-confirm-votes" class="vote-nav-btn vote-nav-next" aria-label="Confirm my votes" title="Confirm my votes">
                    <i class="fas fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
            <?php else: ?>
            <div class="cand-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 0.875rem; margin-bottom: 1.25rem;">
                <?php foreach ($maleCandidates as $cand): ?>
                <?php
                $name = trim(($cand['first_name'] ?? '') . ' ' . ($cand['middle_name'] ?? '') . ' ' . ($cand['last_name'] ?? ''));
                $photoUrl = !empty($cand['photo']) ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($cand['photo']) : BASE_PATH . '/public/img/male.jpg';
                ?>
                <label style="display:block; padding:1.75rem 1rem 1.25rem; border:3px solid #e8edf2; border-radius:20px; cursor:pointer; text-align:center; transition:all 0.15s; position:relative; background:#fff;" class="candidate-card candidate-checkbox-card" data-candidate-id="<?= $cand['id'] ?>" data-gender="male" data-candidate-name="<?= htmlspecialchars($name ?: 'Candidate') ?>" data-candidate-photo="<?= htmlspecialchars($photoUrl) ?>" for="male_<?= $cand['id'] ?>">
                    <input type="checkbox" name="male_candidates[]" value="<?= $cand['id'] ?>" id="male_<?= $cand['id'] ?>" style="position:absolute;left:-9999px;" class="male-candidate-check">
                    <div class="selection-indicator" style="position:absolute; top:0.75rem; right:0.75rem; width:34px; height:34px; border:3px solid #dde3eb; border-radius:50%; background:#f8fafc; transition:all 0.15s; display:flex; align-items:center; justify-content:center;">
                        <div class="selection-fill" style="width:0; height:0; border-radius:50%; background:#0b1b89; transition:all 0.15s;"></div>
                    </div>
                    <img src="<?= $photoUrl ?>" alt="" class="candidate-image" style="width:100%; height:220px; object-fit:cover; object-position:top center; border-radius:14px; margin-bottom:1rem; display:block; border:4px solid #e8edf2; transition:all 0.15s;" onerror="this.src='<?= BASE_PATH ?>/public/img/male.jpg'">
                    <div style="font-weight:700; font-size:1rem; line-height:1.35; color:#1e293b;"><?= htmlspecialchars($name ?: 'Candidate') ?></div>
                </label>
                <?php endforeach; ?>
                
                <?php for ($i = 0; $i < $malePlaceholders; $i++): ?>
                <div style="display: block; padding: 1.5rem; border: 2px dashed var(--border, #e2e8f0); border-radius: 8px; text-align: center; opacity: 0.6; min-height: 200px; background: #f8f9fa;">
                    <img src="<?= BASE_PATH ?>/public/img/male.jpg" alt="" style="width: 120px; height: 120px; object-fit: cover; border-radius: 50%; margin-bottom: 1rem; display: block; margin-left: auto; margin-right: auto; filter: grayscale(100%);">
                    <div style="font-weight: 500; color: var(--text-muted, #718096); font-size: 1rem;">Placeholder</div>
                </div>
                <?php endfor; ?>
            </div>
            <p class="text-muted" style="margin-top: 0.5rem; font-size: 0.875rem;" id="male_count">Selected: 0 / <?= $requiredMales ?></p>
            <div class="form-actions" id="vote-form-actions" style="margin-top: 1.5rem; display: flex; gap: 1rem; flex-wrap: wrap;">
                <?php if ($isSimulation): ?>
                <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="vote-nav-btn vote-nav-prev" aria-label="Back to Manage" title="Back to Manage">
                    <i class="fas fa-times" aria-hidden="true"></i>
                </a>
                <?php else: ?>
                <a href="<?= BASE_PATH ?>/voting" class="vote-nav-btn vote-nav-prev" aria-label="Cancel" title="Cancel">
                    <i class="fas fa-times" aria-hidden="true"></i>
                </a>
                <?php endif; ?>
                <button type="button" id="vote-confirm-votes" class="vote-nav-btn vote-nav-next" aria-label="Confirm my votes" title="Confirm my votes">
                    <i class="fas fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Modal: Confirm all votes before submit -->
        <div id="vote-confirm-final-modal" class="modal" role="dialog" aria-modal="true" aria-labelledby="vote-confirm-final-modal-title" hidden>
            <div class="modal-backdrop vote-confirm-final-backdrop"></div>
            <div class="modal-content" style="max-width: 780px;">
                <h2 id="vote-confirm-final-modal-title" class="modal-heading" style="margin-top: 0;">Confirm your votes</h2>
                <p class="text-muted" style="margin-bottom: 1rem;">Please review your selections below.</p>
                <div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 1rem; margin-bottom: 1.25rem; font-size: 0.9375rem;">
                    <p style="margin: 0 0 0.5rem; font-weight: 600;">Female candidates</p>
                    <div id="vote-confirm-females" class="vote-confirm-thumbnails" style="display: flex; flex-wrap: wrap; gap: 0.75rem; margin-bottom: 0.75rem; min-height: 40px;"></div>
                    <p style="margin: 0 0 0.5rem; font-weight: 600;">Male candidates</p>
                    <div id="vote-confirm-males" class="vote-confirm-thumbnails" style="display: flex; flex-wrap: wrap; gap: 0.75rem; min-height: 40px;"></div>
                </div>
                <div class="modal-actions" style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
                    <button type="button" id="vote-back-to-edit" class="vote-nav-btn vote-nav-prev" aria-label="Back to edit" title="Back to edit">
                        <i class="fas fa-times" aria-hidden="true"></i>
                    </button>
                    <button type="submit" id="vote-submit-from-modal" class="vote-nav-btn vote-nav-next" aria-label="<?= $isSimulation ? 'Submit Vote (Simulation)' : 'Submit Vote' ?>" title="<?= $isSimulation ? 'Submit Vote (Simulation)' : 'Submit Vote' ?>">
                        <i class="fas fa-arrow-right" aria-hidden="true"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <style>
        .candidate-card {
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
        }
        .candidate-card:active {
            transform: scale(0.98);
        }
        </style>
        <script src="<?= BASE_PATH ?>/public/js/voting.js"></script>
        <?php endif; ?>
        
        <?php if ($election['type'] === 'fellowship' && !$fromKiosk): ?>
        <div class="form-actions" style="margin-top: 2rem;">
            <button type="submit" class="btn">Submit Vote</button>
            <a href="<?= BASE_PATH ?>/voting" class="btn btn-ghost">Cancel</a>
        </div>
        <?php endif; ?>
    </form>
</div>

<?php
if ($fromKiosk) {
    ?>
    <div id="toast-container" class="toast-container" aria-live="polite"></div>
    <script src="<?= BASE_PATH ?>/public/js/main.js"></script>
    </div><!-- /.kiosk-vote-wrap -->
    </body>
    </html>
    <?php
} else {
    require_once __DIR__ . '/../../includes/footer.php';
}
?>
