<?php
/**
 * Election Day Check-in Screen
 * The voting manager physically verifies a member's identity, then checks them in here.
 * A member must be checked in before they can use the voting kiosk.
 */

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();

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: check-in / undo ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['action'] ?? '';
    $memberId   = (int)($_POST['member_id'] ?? 0);

    if (($postAction === 'checkin' || $postAction === 'undo_checkin') && $election['status'] !== 'active') {
        header('Location: ' . BASE_PATH . '/voting/checkin/' . $id . '?toast_error=' . urlencode('This election has ended. Check-in is no longer available.'));
        exit;
    }

    if ($postAction === 'checkin' && $memberId > 0) {
        $pin = checkInMember($id, $memberId, currentUserId());
        // Fetch member name for the PIN modal
        $mRow = $pdo->prepare("SELECT first_name, middle_name, last_name FROM members WHERE id = ?");
        $mRow->execute([$memberId]);
        $mData = $mRow->fetch();
        $mName = $mData ? trim(($mData['first_name'] ?? '') . ' ' . ($mData['middle_name'] ?? '') . ' ' . ($mData['last_name'] ?? '')) : 'Member';
        // Store PIN flash in session so we can show the modal on the next page load
        $_SESSION['checkin_pin_flash'] = [
            'pin'         => $pin,
            'member_name' => $mName,
            'member_id'   => $memberId,
        ];
        header('Location: ' . BASE_PATH . '/voting/checkin/' . $id . '?q=' . urlencode($_POST['q'] ?? ''));
        exit;
    }

    if ($postAction === 'undo_checkin' && $memberId > 0) {
        undoCheckIn($id, $memberId);
        header('Location: ' . BASE_PATH . '/voting/checkin/' . $id . '?toast=' . urlencode('Check-in undone.') . '&q=' . urlencode($_POST['q'] ?? ''));
        exit;
    }
}

// Consume PIN flash from session (show once)
$pinFlash = null;
if (!empty($_SESSION['checkin_pin_flash'])) {
    $pinFlash = $_SESSION['checkin_pin_flash'];
    unset($_SESSION['checkin_pin_flash']);
}

// ── Voter data ────────────────────────────────────────────────────────────────
$hasVoterList = electionHasVoterList($id);
$stats        = getVoterStats($id);

// Build full voter list with status for client-side filtering
$voterRows = [];
if ($hasVoterList) {
    $stmt = $pdo->prepare("
        SELECT m.id as member_id, m.first_name, m.middle_name, m.last_name,
               m.photo, m.gender, m.date_of_birth,
               ec.id as checkin_id, ec.pin_code,
               (SELECT COUNT(*) FROM election_votes WHERE election_id = ? AND voter_member_id = m.id) as vote_count
        FROM election_voters ev
        JOIN members m ON m.id = ev.member_id
        LEFT JOIN election_checkins ec ON ec.election_id = ev.election_id AND ec.member_id = m.id
        WHERE ev.election_id = ?
        ORDER BY m.last_name, m.first_name
    ");
    $stmt->execute([$id, $id]);
    $voterRows = $stmt->fetchAll();
} else {
    // No voter list — show all active members
    $stmt = $pdo->prepare("
        SELECT m.id as member_id, m.first_name, m.middle_name, m.last_name,
               m.photo, m.gender, m.date_of_birth,
               ec.id as checkin_id, ec.pin_code,
               (SELECT COUNT(*) FROM election_votes WHERE election_id = ? AND voter_member_id = m.id) as vote_count
        FROM members m
        LEFT JOIN election_checkins ec ON ec.election_id = ? AND ec.member_id = m.id
        WHERE (m.status != 'deceased' OR m.status IS NULL) AND m.date_of_death IS NULL
        ORDER BY m.last_name, m.first_name
    ");
    $stmt->execute([$id, $id]);
    $voterRows = $stmt->fetchAll();
}

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

<style>
.checkin-stats { display: flex; gap: 1rem; flex-wrap: wrap; margin-bottom: 1.5rem; }
.stat-box { flex: 1; min-width: 120px; background: #fff; border: 1px solid var(--border,#e2e8f0); border-radius: 8px; padding: 1rem; text-align: center; }
.stat-box .stat-num { font-size: 2rem; font-weight: 700; line-height: 1; }
.stat-box .stat-label { font-size: 0.75rem; color: var(--text-muted,#718096); margin-top: 0.25rem; }
.stat-eligible   .stat-num { color: #1e40af; }
.stat-checkedin  .stat-num { color: #b45309; }
.stat-voted      .stat-num { color: #059669; }
.stat-pending    .stat-num { color: #6b7280; }

.voter-card { display: flex; align-items: center; gap: 1rem; padding: 0.75rem 1rem; border-bottom: 1px solid var(--border,#e2e8f0); transition: background 0.15s; }
.voter-card:last-child { border-bottom: none; }
.voter-card:hover { background: #f8fafc; }
.voter-photo { width: 48px; height: 48px; border-radius: 50%; object-fit: cover; flex-shrink: 0; background: #e2e8f0; }
.voter-info { flex: 1; min-width: 0; }
.voter-name { font-weight: 500; font-size: 0.9375rem; }
.voter-meta { font-size: 0.8125rem; color: var(--text-muted,#718096); }
.voter-status { font-size: 0.75rem; font-weight: 600; padding: 0.2rem 0.6rem; border-radius: 999px; white-space: nowrap; }
.status-eligible   { background: #eff6ff; color: #1e40af; }
.status-checkedin  { background: #fef3c7; color: #b45309; }
.status-voted      { background: #dcfce7; color: #166534; }
.status-not-eligible { background: #f1f5f9; color: #64748b; }

.checkin-search-wrap { position: relative; margin-bottom: 1rem; }
.checkin-search-wrap input { width: 100%; padding: 0.6rem 2.5rem 0.6rem 1rem; border: 1px solid var(--border,#e2e8f0); border-radius: 8px; font-size: 1rem; }
.checkin-filter-tabs { display: flex; gap: 0.5rem; margin-bottom: 1rem; flex-wrap: wrap; }
.filter-tab { padding: 0.35rem 0.85rem; border: 1px solid var(--border,#e2e8f0); border-radius: 999px; font-size: 0.8125rem; cursor: pointer; background: #fff; transition: all 0.15s; }
.filter-tab.active { background: var(--primary,#1e3a5f); color: #fff; border-color: var(--primary,#1e3a5f); }

/* PIN modal */
.pin-overlay {
    position: fixed; inset: 0; background: rgba(0,0,0,0.6);
    display: flex; align-items: center; justify-content: center;
    z-index: 2000; padding: 1rem;
}
.pin-box {
    background: #fff; border-radius: 16px; padding: 2rem 2.5rem;
    max-width: 380px; width: 100%; text-align: center;
    box-shadow: 0 8px 40px rgba(0,0,0,0.22);
}
.pin-box .pin-member { font-size: 1.125rem; font-weight: 700; margin-bottom: 0.25rem; }
.pin-box .pin-subtitle { font-size: 0.875rem; color: var(--text-muted,#718096); margin-bottom: 1.5rem; }
.pin-digits {
    display: flex; gap: 0.5rem; justify-content: center; margin-bottom: 0.75rem;
}
.pin-digit {
    width: 52px; height: 60px; border-radius: 10px;
    background: #1e3a5f; color: #fff;
    font-size: 1.75rem; font-weight: 800; letter-spacing: 0;
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 2px 6px rgba(30,58,95,0.35);
    user-select: none;
}
.pin-hint { font-size: 0.8125rem; color: #b45309; margin-bottom: 1.75rem; font-weight: 500; }
</style>

<?php if ($pinFlash): ?>
<div class="pin-overlay" id="pin-modal">
    <div class="pin-box">
        <div class="pin-member"><?= htmlspecialchars($pinFlash['member_name']) ?></div>
        <div class="pin-subtitle">Checked in successfully</div>
        <div class="pin-digits">
            <?php foreach (str_split($pinFlash['pin'] ?: '-----') as $ch): ?>
            <div class="pin-digit"><?= htmlspecialchars($ch) ?></div>
            <?php endforeach; ?>
        </div>
        <p class="pin-hint">&#128274; Hand this PIN to the voter</p>
        <button class="btn" onclick="document.getElementById('pin-modal').style.display='none';this.blur();" style="width:100%;">
            Done — Next Voter
        </button>
    </div>
</div>
<?php endif; ?>

<div class="header">
    <h1>Check-in Desk</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/voting/kiosk/<?= $id ?>" class="btn" target="_blank">Open Voting Kiosk</a>
        <a href="<?= BASE_PATH ?>/voting/manage/<?= $id ?>" class="link-muted">← Back to Manage</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="card" style="margin-bottom: 1rem;">
    <p style="margin: 0 0 0.25rem;"><strong><?= htmlspecialchars($election['title']) ?></strong></p>
    <p style="margin: 0;" class="text-muted">
        <?= $election['type'] === 'fellowship' ? 'Group' : "Presbyters' Elections" ?>
        &nbsp;·&nbsp;
        <span class="badge <?= $election['status'] === 'active' ? 'badge-success' : 'badge-outline' ?>">
            <?= ucfirst($election['status']) ?>
        </span>
        <?php if (!$hasVoterList): ?>
        &nbsp;·&nbsp;<span class="badge badge-outline" style="color: #b45309; border-color: #b45309;">No voter list — showing all members</span>
        <?php endif; ?>
    </p>
</div>

<!-- Live stats -->
<?php if ($hasVoterList): ?>
<div class="checkin-stats">
    <div class="stat-box stat-eligible">
        <div class="stat-num" id="stat-eligible"><?= $stats['eligible'] ?></div>
        <div class="stat-label">Eligible</div>
    </div>
    <div class="stat-box stat-checkedin">
        <div class="stat-num" id="stat-checkedin"><?= $stats['checked_in'] ?></div>
        <div class="stat-label">Checked in</div>
    </div>
    <div class="stat-box stat-voted">
        <div class="stat-num" id="stat-voted"><?= $stats['voted'] ?></div>
        <div class="stat-label">Voted</div>
    </div>
    <div class="stat-box stat-pending">
        <div class="stat-num" id="stat-pending"><?= $stats['pending_checkin'] ?></div>
        <div class="stat-label">Not yet checked in</div>
    </div>
</div>
<?php endif; ?>

<!-- Search + filter tabs -->
<div class="card">
    <div class="checkin-search-wrap">
        <input type="text" id="checkin-search" placeholder="Search by name…" autocomplete="off" autocorrect="off" spellcheck="false">
    </div>

    <div class="checkin-filter-tabs">
        <button class="filter-tab active" data-filter="all">All</button>
        <button class="filter-tab" data-filter="eligible">Not checked in</button>
        <button class="filter-tab" data-filter="checkedin">Checked in</button>
        <button class="filter-tab" data-filter="voted">Voted</button>
    </div>

    <div id="voter-list">
    <?php foreach ($voterRows as $v):
        $name       = trim(($v['first_name'] ?? '') . ' ' . ($v['middle_name'] ?? '') . ' ' . ($v['last_name'] ?? ''));
        $fellowship = getMemberFellowship($v['date_of_birth'] ?? null, $v['gender'] ?? '');
        $photoUrl   = !empty($v['photo'])
            ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($v['photo'])
            : BASE_PATH . '/public/img/' . (strtolower($v['gender'] ?? '') === 'female' ? 'female' : 'male') . '.jpg';
        $hasCheckin = !empty($v['checkin_id']);
        $hasVoted   = (int)($v['vote_count'] ?? 0) > 0;

        if ($hasVoted)       $statusKey = 'voted';
        elseif ($hasCheckin) $statusKey = 'checkedin';
        else                 $statusKey = 'eligible';

        $statusLabel = ['eligible' => 'Not checked in', 'checkedin' => 'Checked in — not yet voted', 'voted' => 'Voted'];
        $statusClass = ['eligible' => 'status-eligible', 'checkedin' => 'status-checkedin', 'voted' => 'status-voted'];
    ?>
    <div class="voter-card" data-name="<?= htmlspecialchars(strtolower($name)) ?>" data-status="<?= $statusKey ?>">
        <img src="<?= $photoUrl ?>" alt="" class="voter-photo"
             onerror="this.src='<?= BASE_PATH ?>/public/img/<?= strtolower($v['gender'] ?? '') === 'female' ? 'female' : 'male' ?>.jpg'">
        <div class="voter-info">
            <div class="voter-name"><?= htmlspecialchars($name) ?></div>
            <div class="voter-meta"><?= htmlspecialchars($fellowship ?? ucfirst(strtolower($v['gender'] ?? ''))) ?></div>
        </div>
        <span class="voter-status <?= $statusClass[$statusKey] ?>"><?= $statusLabel[$statusKey] ?></span>
        <div style="flex-shrink: 0; margin-left: 0.5rem;">
        <?php if ($hasVoted): ?>
            <span class="badge badge-success" style="font-size: 0.75rem;">&#10003; Voted</span>
        <?php elseif ($hasCheckin): ?>
            <?php if (!empty($v['pin_code'])): ?>
            <button type="button" class="btn btn-sm" style="background:#b45309;color:#fff;border-color:#b45309;"
                    onclick="showPin(<?= $v['member_id'] ?>,<?= htmlspecialchars(json_encode($name)) ?>,<?= htmlspecialchars(json_encode($v['pin_code'])) ?>)">
                Show PIN
            </button>
            <?php endif; ?>
            <form method="post" style="display:inline;">
                <input type="hidden" name="action" value="undo_checkin">
                <input type="hidden" name="member_id" value="<?= $v['member_id'] ?>">
                <input type="hidden" name="q" value="">
                <button type="submit" class="btn btn-sm btn-outline" title="Undo check-in" data-confirm="Undo check-in for <?= htmlspecialchars($name) ?>?">Undo</button>
            </form>
        <?php else: ?>
            <form method="post" style="display:inline;">
                <input type="hidden" name="action" value="checkin">
                <input type="hidden" name="member_id" value="<?= $v['member_id'] ?>">
                <input type="hidden" name="q" value="">
                <button type="submit" class="btn btn-sm" style="background:#059669;color:#fff;border-color:#059669;">Check in</button>
            </form>
        <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php if (empty($voterRows)): ?>
    <p class="text-muted" style="padding: 1.5rem; font-size: 0.875rem;">No voters found. Add an eligible voter list first.</p>
    <?php endif; ?>
    </div>
    <p id="no-results" style="display:none; padding: 1rem; color: var(--text-muted,#718096); font-size: 0.875rem;">No members match your search.</p>
</div>

<script>
(function () {
    var search     = document.getElementById('checkin-search');
    var cards      = document.querySelectorAll('.voter-card');
    var noResults  = document.getElementById('no-results');
    var filterTabs = document.querySelectorAll('.filter-tab');
    var activeFilter = 'all';

    function applyFilters() {
        var q = search ? search.value.toLowerCase().trim() : '';
        var visible = 0;
        cards.forEach(function (c) {
            var nameMatch   = !q || c.dataset.name.includes(q);
            var statusMatch = activeFilter === 'all' || c.dataset.status === activeFilter;
            var show = nameMatch && statusMatch;
            c.style.display = show ? '' : 'none';
            if (show) visible++;
        });
        if (noResults) noResults.style.display = visible === 0 ? '' : 'none';
    }

    if (search) search.addEventListener('input', applyFilters);

    filterTabs.forEach(function (tab) {
        tab.addEventListener('click', function () {
            filterTabs.forEach(function (t) { t.classList.remove('active'); });
            this.classList.add('active');
            activeFilter = this.dataset.filter;
            applyFilters();
        });
    });

    // Auto-focus search on load
    if (search) search.focus();
})();

// Inline PIN viewer (for already-checked-in members)
var pinViewModal = null;

function showPin(memberId, memberName, pin) {
    if (!pinViewModal) {
        pinViewModal = document.createElement('div');
        pinViewModal.className = 'pin-overlay';
        pinViewModal.innerHTML = '<div class="pin-box">'
            + '<div class="pin-member" id="pv-name"></div>'
            + '<div class="pin-subtitle">Voting PIN</div>'
            + '<div class="pin-digits" id="pv-digits"></div>'
            + '<p class="pin-hint">&#128274; Hand this PIN to the voter</p>'
            + '<button class="btn" onclick="pinViewModal.style.display=\'none\';" style="width:100%;">Close</button>'
            + '</div>';
        pinViewModal.addEventListener('click', function(e){ if (e.target === this) this.style.display = 'none'; });
        document.body.appendChild(pinViewModal);
    }
    document.getElementById('pv-name').textContent = memberName;
    var digitsEl = document.getElementById('pv-digits');
    digitsEl.innerHTML = '';
    pin.split('').forEach(function(ch) {
        var d = document.createElement('div');
        d.className = 'pin-digit';
        d.textContent = ch;
        digitsEl.appendChild(d);
    });
    pinViewModal.style.display = 'flex';
}
</script>

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