<?php
/**
 * Eligible Voter List — manage which members can vote in this election
 */

if (!defined('BASE_PATH')) {
    require_once __DIR__ . '/../../config/app.php';
    require_once __DIR__ . '/../../includes/session-bootstrap.php';
    nazareth_bootstrap_session_cookie();
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    require_once __DIR__ . '/../../config/database.php';
}

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

// $id is set by the router; when accessed directly, redirect to the voting list
if (empty($id)) {
    header('Location: ' . BASE_PATH . '/voting');
    exit;
}

if (!isVoting() && !isAdmin()) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Access denied.'));
    exit;
}

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 manage this election.'));
    exit;
}

// ── POST actions ──────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'auto_populate') {
        clearVoterList($id);
        $added = autoPopulateVoters($id, currentUserId());
        header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast=' . urlencode("Voter list populated with {$added} eligible members."));
        exit;
    }

    if ($action === 'clear_list') {
        clearVoterList($id);
        header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast=' . urlencode('Voter list cleared.'));
        exit;
    }

    if ($action === 'add_voter') {
        $memberId = (int)($_POST['member_id'] ?? 0);
        if ($memberId > 0) {
            if (addVoterToElection($id, $memberId, currentUserId())) {
                header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast=' . urlencode('Member added to voter list.'));
            } else {
                header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast_error=' . urlencode('Could not add member.'));
            }
        } else {
            header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast_error=' . urlencode('Please select a member.'));
        }
        exit;
    }

    if ($action === 'remove_voter') {
        $memberId = (int)($_POST['member_id'] ?? 0);
        if ($memberId > 0) {
            removeVoterFromElection($id, $memberId);
            header('Location: ' . BASE_PATH . '/voting/voters/' . $id . '?toast=' . urlencode('Member removed from voter list.'));
            exit;
        }
    }
}

// ── Data ──────────────────────────────────────────────────────────────────────
$voters      = getElectionVoters($id);
$voterIds    = array_column($voters, 'member_id');
$hasVoterList = !empty($voters);

// All eligible-to-add members (active, non-deceased, not already on list)
$placeholders = $hasVoterList && !empty($voterIds)
    ? implode(',', array_fill(0, count($voterIds), '?'))
    : null;

if ($placeholders) {
    $allMembersStmt = $pdo->prepare("
        SELECT id, first_name, middle_name, last_name, gender, date_of_birth
        FROM members
        WHERE (status != 'deceased' OR status IS NULL) AND date_of_death IS NULL
          AND id NOT IN ({$placeholders})
        ORDER BY last_name, first_name
    ");
    $allMembersStmt->execute($voterIds);
} else {
    $allMembersStmt = $pdo->query("
        SELECT id, first_name, middle_name, last_name, gender, date_of_birth
        FROM members
        WHERE (status != 'deceased' OR status IS NULL) AND date_of_death IS NULL
        ORDER BY last_name, first_name
    ");
}
$allMembers = $allMembersStmt->fetchAll();

// Candidate member IDs for this election (to show © badge)
$candidateStmt = $pdo->prepare("SELECT DISTINCT member_id FROM election_candidates WHERE election_id = ?");
$candidateStmt->execute([$id]);
$candidateMemberIds = array_flip($candidateStmt->fetchAll(PDO::FETCH_COLUMN));

// Determine auto-populate label based on election type and group assignment
if ($election['type'] === 'presbyters') {
    $autoLabel = 'All active members aged 18+ (excluding Children\'s Service & Junior Youth)';
} elseif (($election['group_type'] ?? '') === 'service_grp' && !empty($election['group_id'])) {
    $svcStmt = $pdo->prepare("SELECT name FROM ministries WHERE id = ?");
    $svcStmt->execute([$election['group_id']]);
    $svcName = $svcStmt->fetchColumn();
    $autoLabel = 'All active members of the ' . ($svcName ?: 'assigned service group');
} elseif (($election['group_type'] ?? '') === 'gen_grp' && !empty($election['group_name'])) {
    $autoLabel = 'All active members in the ' . $election['group_name'] . ' fellowship group';
} else {
    $autoLabel = 'All active members (no specific group assigned)';
}

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

<div class="header">
    <h1>Voter Roll — <?= htmlspecialchars($election['title']) ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="link-muted">← Back to Manage</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<!-- ── Current voter roll status ─────────────────────────────────────────── -->
<?php if ($hasVoterList): ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    showToast('success', 'Restricted voter roll active — <?= count($voters) ?> member<?= count($voters) !== 1 ? 's' : '' ?> may vote');
});
</script>
<?php else: ?>
<div style="background:#fffbeb; border:1.5px solid #fcd34d; border-radius:10px; padding:1.1rem 1.4rem; margin-bottom:1.5rem; display:flex; align-items:flex-start; gap:1rem;">
    <span style="font-size:1.5rem; line-height:1;">⚠️</span>
    <div>
        <strong style="font-size:1rem; color:#92400e;">Open mode — no voter roll configured</strong>
        <p style="margin:0.25rem 0 0; font-size:0.875rem; color:#92400e;">
            Any member who is checked in at the desk can currently vote.
            To restrict voting to specific members, use <strong>Auto-populate</strong> or add members manually below.
        </p>
    </div>
</div>
<?php endif; ?>

<!-- ── Setup actions ──────────────────────────────────────────────────────── -->
<div class="card" style="margin-bottom:1.5rem;">
    <h2 style="margin-top:0; font-size:1rem;">Build / Rebuild Voter Roll</h2>
    <p class="text-muted" style="margin-bottom:1rem; font-size:0.875rem;">
        Auto-populate fills the roll using the eligibility rule for this election:<br>
        <strong><?= htmlspecialchars($autoLabel) ?></strong>
    </p>
    <div style="display:flex; gap:0.75rem; flex-wrap:wrap;">
        <form method="post" style="display:inline;">
            <input type="hidden" name="action" value="auto_populate">
            <button type="submit" class="btn"
                data-confirm="<?= $hasVoterList ? 'This will clear the current voter roll and re-populate it from scratch. Continue?' : 'Auto-populate the voter roll now?' ?>"
                data-confirm-btn="<?= $hasVoterList ? 'Yes, rebuild' : 'Yes, auto-populate' ?>">
                <?= $hasVoterList ? '↺ Re-populate (clear &amp; rebuild)' : 'Auto-populate voter roll' ?>
            </button>
        </form>
        <?php if ($hasVoterList): ?>
        <form method="post" style="display:inline;">
            <input type="hidden" name="action" value="clear_list">
            <button type="submit" class="btn btn-outline-danger"
                data-confirm="This will delete the entire voter roll and switch the election back to Open mode. Continue?"
                data-confirm-btn="Yes, remove roll">
                Remove voter roll (switch to open mode)
            </button>
        </form>
        <?php endif; ?>
    </div>
</div>

<!-- ── Current voter list ─────────────────────────────────────────────────── -->
<div class="card" style="margin-bottom:1.5rem;">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
        <h2 style="margin:0; font-size:1rem;">
            Members on the Voter Roll
            <span class="badge badge-outline" style="margin-left:0.5rem;"><?= count($voters) ?></span>
        </h2>
        <?php if ($hasVoterList): ?>
        <input type="text" id="voter-search" placeholder="Filter…"
            style="width:200px; padding:0.4rem 0.75rem; border:1px solid var(--border,#e2e8f0); border-radius:6px; font-size:0.875rem;">
        <?php endif; ?>
    </div>

    <?php if (!$hasVoterList): ?>
    <p class="text-muted" style="font-size:0.875rem; margin:0;">
        No voter roll configured. Use <strong>Auto-populate</strong> above or add members one by one below.
    </p>
    <?php else: ?>
    <div class="table-wrap">
        <table id="voters-table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Fellowship</th>
                    <th>Gender</th>
                    <th style="width:100px;"></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($voters as $v):
                $name       = trim(($v['first_name'] ?? '') . ' ' . ($v['middle_name'] ?? '') . ' ' . ($v['last_name'] ?? ''));
                $fellowship = getMemberFellowship($v['date_of_birth'] ?? null, $v['gender'] ?? '');
                $gender     = ucfirst(strtolower($v['gender'] ?? '—'));
                $isCandidate = isset($candidateMemberIds[$v['member_id']]);
            ?>
            <tr class="voter-row" data-name="<?= htmlspecialchars(strtolower($name)) ?>">
                <td>
                    <?= htmlspecialchars($name) ?>
                    <?php if ($isCandidate): ?>
                    <span title="Standing as a candidate" style="
                        display:inline-flex; align-items:center; justify-content:center;
                        width:1.2em; height:1.2em; border-radius:50%;
                        background:#0b1b89; color:#fff;
                        font-size:0.65rem; font-weight:700; letter-spacing:0;
                        margin-left:0.35rem; vertical-align:middle;
                        flex-shrink:0;
                    ">C</span>
                    <?php endif; ?>
                </td>
                <td><?= htmlspecialchars($fellowship ?? '—') ?></td>
                <td><?= htmlspecialchars($gender) ?></td>
                <td>
                    <form method="post">
                        <input type="hidden" name="action" value="remove_voter">
                        <input type="hidden" name="member_id" value="<?= $v['member_id'] ?>">
                        <button type="submit" class="btn btn-sm btn-outline-danger"
                            data-confirm="Remove this member from the voter roll?">Remove</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- Manual add -->
<?php if (!empty($allMembers)):
    $memberJson = json_encode(array_map(function($m) use (&$getMemberFellowship) {
        $name = trim(($m['first_name'] ?? '') . ' ' . ($m['middle_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
        $fellowship = getMemberFellowship($m['date_of_birth'] ?? null, $m['gender'] ?? '');
        return ['id' => $m['id'], 'name' => $name, 'fellowship' => $fellowship ?? ''];
    }, $allMembers), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);
?>
<div class="card">
    <h2 style="margin-top: 0; font-size: 1rem;">Add a Member Manually</h2>
    <form method="post" id="add-voter-form">
        <input type="hidden" name="action" value="add_voter">
        <input type="hidden" name="member_id" id="add-voter-id">
        <div class="form-row" style="align-items: flex-start;">
            <div class="form-group" style="flex: 1; position: relative;">
                <input type="text" id="add-voter-search" placeholder="Start typing a name…"
                    autocomplete="off"
                    style="width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--border, #e2e8f0); border-radius: 6px; font-size: 0.9375rem;">
                <ul id="add-voter-suggestions" style="
                    display: none; position: absolute; top: 100%; left: 0; right: 0; z-index: 999;
                    margin: 2px 0 0; padding: 0; list-style: none;
                    background: #fff; border: 1px solid var(--border, #e2e8f0);
                    border-radius: 6px; box-shadow: 0 4px 16px rgba(0,0,0,0.10);
                    max-height: 260px; overflow-y: auto;
                "></ul>
            </div>
            <div class="form-group">
                <button type="submit" class="btn" id="add-voter-btn" disabled>Add to Voter List</button>
            </div>
        </div>
    </form>
</div>
<script>
(function () {
    var members = <?= $memberJson ?>;
    var searchInput = document.getElementById('add-voter-search');
    var hiddenId    = document.getElementById('add-voter-id');
    var suggestions = document.getElementById('add-voter-suggestions');
    var addBtn      = document.getElementById('add-voter-btn');

    function resetSelection() {
        hiddenId.value = '';
        addBtn.disabled = true;
    }

    function showSuggestions(matches) {
        suggestions.innerHTML = '';
        if (!matches.length) {
            suggestions.style.display = 'none';
            return;
        }
        matches.forEach(function (m) {
            var li = document.createElement('li');
            li.textContent = m.name + (m.fellowship ? ' (' + m.fellowship + ')' : '');
            li.style.cssText = 'padding: 0.55rem 0.9rem; cursor: pointer; font-size: 0.9rem; border-bottom: 1px solid #f1f5f9;';
            li.addEventListener('mousedown', function (e) {
                e.preventDefault();
                searchInput.value = m.name + (m.fellowship ? ' (' + m.fellowship + ')' : '');
                hiddenId.value = m.id;
                addBtn.disabled = false;
                suggestions.style.display = 'none';
            });
            li.addEventListener('mouseover',  function () { li.style.background = '#f0f9ff'; });
            li.addEventListener('mouseout',   function () { li.style.background = ''; });
            suggestions.appendChild(li);
        });
        suggestions.style.display = 'block';
    }

    searchInput.addEventListener('input', function () {
        resetSelection();
        var q = this.value.trim().toLowerCase();
        if (q.length < 1) { suggestions.style.display = 'none'; return; }
        var matches = members.filter(function (m) {
            return m.name.toLowerCase().includes(q) || m.fellowship.toLowerCase().includes(q);
        }).slice(0, 20);
        showSuggestions(matches);
    });

    searchInput.addEventListener('blur', function () {
        setTimeout(function () { suggestions.style.display = 'none'; }, 150);
    });

    document.getElementById('add-voter-form').addEventListener('submit', function (e) {
        if (!hiddenId.value) { e.preventDefault(); searchInput.focus(); }
    });
})();
</script>
<?php endif; ?>

<script>
(function () {
    var input = document.getElementById('voter-search');
    if (!input) return;
    input.addEventListener('input', function () {
        var q = this.value.toLowerCase().trim();
        document.querySelectorAll('.voter-row').forEach(function (row) {
            row.style.display = (!q || row.dataset.name.includes(q)) ? '' : 'none';
        });
    });
})();
</script>

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