<?php
declare(strict_types=1);
require_once __DIR__ . '/auth_helper.php';
require_login();
$user = get_user();

$id = $_GET['id'] ?? '';
if (!$id) {
    header("Location: index.php");
    exit;
}

$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM elections WHERE id = ?");
$stmt->execute([$id]);
$election = $stmt->fetch();

if (!$election || $election['status'] !== 'Ongoing') {
    die("Election is not currently ongoing.");
}

// Check if already voted
$check = $pdo->prepare("SELECT COUNT(*) FROM votes WHERE election_id = ? AND voter_id = ?");
$check->execute([$id, $user['id']]);
if ($check->fetchColumn() > 0) {
    header("Location: index.php?error=already_voted");
    exit;
}

$positions = $pdo->prepare("SELECT * FROM positions WHERE election_id = ? ORDER BY sort_order ASC");
$positions->execute([$id]);
$positions = $positions->fetchAll();

$endTime = strtotime($election['end_date_and_time']) * 1000;
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Ballot: <?= htmlspecialchars($election['title']) ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <script src="https://unpkg.com/lucide@latest"></script>
  <style>
    :root {
        --primary: #4f46e5;
        --primary-hover: #4338ca;
        --primary-light: #eef2ff;
        --bg: #f8fafc;
        --text: #1e293b;
        --text-muted: #64748b;
        --border: #e2e8f0;
    }

    body { 
        background-color: var(--bg);
        color: var(--text);
        font-family: 'Plus Jakarta Sans', sans-serif;
        margin: 0;
        line-height: 1.5;
    }

    .navbar {
        background: white;
        padding: 1rem 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid var(--border);
        position: sticky;
        top: 0;
        z-index: 1000;
    }

    .brand {
        font-weight: 800;
        font-size: 1.25rem;
        color: var(--primary);
        text-decoration: none;
        letter-spacing: -0.025em;
    }

    .ballot-container { 
        max-width: 900px; 
        margin: 0 auto; 
        padding: 40px 20px 120px; 
    }

    .ballot-title-area {
        margin-bottom: 40px;
    }

    .ballot-title-area h1 {
        font-size: 1.875rem;
        font-weight: 700;
        margin: 0 0 8px 0;
        color: #1e293b;
    }

    .ballot-title-area p {
        color: #64748b;
        margin: 0;
        font-size: 1rem;
    }

    .voter-info-card {
        background: white;
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 24px;
        margin-bottom: 32px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }

    .voter-info-title {
        font-size: 1rem;
        font-weight: 600;
        color: #475569;
        margin-bottom: 16px;
    }

    .voter-info-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 20px;
    }

    .info-item label {
        display: block;
        font-size: 0.75rem;
        font-weight: 500;
        color: #94a3b8;
        text-transform: uppercase;
        margin-bottom: 4px;
    }

    .info-item span {
        font-size: 0.875rem;
        font-weight: 600;
        color: #1e293b;
    }

    .timer-container {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #ef4444;
        font-weight: 700;
        font-size: 0.875rem;
        background: #fef2f2;
        padding: 8px 16px;
        border-radius: 8px;
        border: 1px solid #fee2e2;
    }

    .position-group { 
        background: white;
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 32px;
        margin-bottom: 24px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }

    .position-title { 
        font-size: 1.25rem; 
        font-weight: 700; 
        color: #1e293b; 
        margin-bottom: 24px; 
    }

    .candidates-list { 
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .candidate-label { 
        cursor: pointer; 
        display: block; 
    }

    .candidate-card {
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 16px 20px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        gap: 16px;
        background: white;
    }

    .candidate-card:hover { 
        border-color: var(--primary);
        background: #fcfdff;
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
    }
    
    input[type="radio"]:checked + .candidate-card {
        border-color: var(--primary);
        background: white;
        box-shadow: 0 0 0 1px var(--primary);
    }
    
    .radio-circle {
        width: 20px;
        height: 20px;
        border: 2px solid #cbd5e1;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
    }

    input[type="radio"]:checked + .candidate-card .radio-circle {
        border-color: var(--primary);
    }

    input[type="radio"]:checked + .candidate-card .radio-circle::after {
        content: '';
        width: 10px;
        height: 10px;
        background: var(--primary);
        border-radius: 50%;
    }

    .candidate-avatar {
        width: 48px;
        height: 48px;
        background: #f1f5f9;
        border-radius: 50%;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        color: #64748b;
    }

    .candidate-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .candidate-info h3 { 
        margin: 0; 
        font-size: 1rem; 
        font-weight: 600; 
        color: #1e293b; 
    }

    .candidate-info p { 
        margin: 2px 0 0 0; 
        font-size: 0.875rem; 
        color: #64748b; 
    }

    .submit-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: white;
        padding: 16px 40px;
        border-top: 1px solid var(--border);
        display: flex;
        justify-content: center;
        z-index: 100;
        box-shadow: 0 -10px 15px -3px rgba(0,0,0,0.05);
    }

    .submit-container {
        max-width: 900px;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .submit-text p {
        margin: 0;
        font-size: 0.75rem;
        font-weight: 800;
        color: var(--text-muted);
        letter-spacing: 0.05em;
        text-transform: uppercase;
    }

    .submit-text h4 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 700;
        color: var(--text);
    }

    .btn-submit {
        background: var(--primary);
        color: white;
        border: none;
        padding: 14px 40px;
        border-radius: 12px;
        font-size: 1rem;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.2s;
        box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.2);
    }

    .btn-submit:hover { 
        background: var(--primary-hover);
        transform: translateY(-1px);
        box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3);
    }

    .btn-submit:active {
        transform: translateY(0);
    }

    /* Modal Styles */
    .modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(15, 23, 42, 0.6);
        backdrop-filter: blur(4px);
        z-index: 2000;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }

    .modal-overlay.active {
        display: flex;
    }

    .confirm-modal {
        background: white;
        border-radius: 20px;
        max-width: 450px;
        width: 100%;
        padding: 32px;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        animation: modalIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    }

    @keyframes modalIn {
        from { transform: scale(0.9) translateY(20px); opacity: 0; }
        to { transform: scale(1) translateY(0); opacity: 1; }
    }

    .modal-icon {
        width: 64px;
        height: 64px;
        background: #eef2ff;
        color: #4f46e5;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 24px;
    }

    .confirm-modal h2 {
        margin: 0 0 12px 0;
        font-size: 1.5rem;
        font-weight: 800;
        color: #1e293b;
    }

    .confirm-modal p {
        margin: 0 0 32px 0;
        color: #64748b;
        font-size: 1rem;
        line-height: 1.6;
    }

    .modal-actions {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }

    .btn-modal {
        padding: 12px 24px;
        border-radius: 12px;
        font-size: 0.875rem;
        font-weight: 700;
        cursor: pointer;
        transition: all 0.2s;
        border: none;
        text-align: center;
    }

    .btn-modal-cancel {
        background: #f1f5f9;
        color: #64748b;
    }

    .btn-modal-cancel:hover {
        background: #e2e8f0;
        color: #1e293b;
    }

    .btn-modal-confirm {
        background: #4f46e5;
        color: white;
        box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.2);
    }

    .btn-modal-confirm:hover {
        background: #4338ca;
        box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3);
    }

    input[type="radio"] { display: none; }

    @media (max-width: 768px) {
        .voter-info-grid {
            grid-template-columns: 1fr 1fr;
        }
    }
  </style>
</head>
<body class="<?= ($user['theme'] ?? 'light') === 'dark' ? 'dark-theme' : '' ?>">
  <nav class="navbar">
    <a href="index.php" class="brand">Click to Vote</a>
    <div>
      <span style="margin-right: 1rem; color: var(--text-muted); font-size: 0.875rem; font-weight: 600;"><?= htmlspecialchars($user['name']) ?></span>
      <a href="logout.php" style="color: #ef4444; font-size: 0.875rem; font-weight: 700; text-decoration: none;">Logout</a>
    </div>
  </nav>

  <div class="ballot-container">
    <div class="ballot-title-area">
        <h1><?= htmlspecialchars($election['title']) ?></h1>
        <p>Review the candidates carefully and cast your secure vote below.</p>
    </div>

    <div class="voter-info-card">
        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;">
            <div class="voter-info-title">Voter Information</div>
            <div class="timer-container">
                <i data-lucide="clock" style="width: 16px;"></i>
                <span id="countdown">00:00:00</span>
            </div>
        </div>
        <div class="voter-info-grid">
            <div class="info-item">
                <label>Email</label>
                <span><?= htmlspecialchars($user['email']) ?></span>
            </div>
            <div class="info-item">
                <label>Grade Level</label>
                <span>Grade <?= htmlspecialchars((string)($user['grade_level'] ?? 'N/A')) ?></span>
            </div>
            <div class="info-item">
                <label>Track/Cluster</label>
                <span><?= htmlspecialchars($user['track'] ?? 'N/A') ?></span>
            </div>
            <div class="info-item">
                <label>Section</label>
                <span><?= htmlspecialchars($user['section'] ?? 'N/A') ?></span>
            </div>
        </div>
    </div>

    <form id="ballotForm" action="api/submit_vote.php" method="POST">
        <input type="hidden" name="election_id" value="<?= $id ?>">
        
        <?php foreach ($positions as $index => $pos): ?>
            <div class="position-group">
                <div class="position-title">
                    <?= htmlspecialchars($pos['name']) ?>
                </div>
                
                <?php
                    $sql = "SELECT c.*, u.name, u.track FROM candidates c JOIN users u ON c.user_id = u.id WHERE c.position_id = ? AND c.approved = TRUE";
                    $params = [$pos['id']];
                    
                    if ($pos['type'] === 'Track Specific') {
                        $sql .= " AND u.track = ?";
                        $params[] = $user['track'];
                    }
                    
                    $cStmt = $pdo->prepare($sql);
                    $cStmt->execute($params);
                    $candidates = $cStmt->fetchAll();
                ?>
                
                <?php if (empty($candidates)): ?>
                    <div style="padding: 24px; background: #f8fafc; border-radius: 12px; text-align: center; border: 1px dashed #cbd5e1;">
                        <p style="margin: 0; color: #64748b; font-size: 0.875rem;">No candidates available for your track.</p>
                    </div>
                <?php else: ?>
                    <div class="candidates-list">
                        <?php foreach ($candidates as $cand): ?>
                            <label class="candidate-label">
                                <input type="radio" name="votes[<?= $pos['id'] ?>]" value="<?= $cand['id'] ?>" required>
                                <div class="candidate-card">
                                    <div class="radio-circle"></div>
                                    <div class="candidate-avatar">
                                        <?= substr($cand['name'], 0, 1) ?>
                                    </div>
                                    <div class="candidate-info">
                                        <h3><?= htmlspecialchars($cand['name']) ?></h3>
                                        <p><?= htmlspecialchars($cand['party_name'] ?: 'Independent') ?></p>
                                    </div>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>

        <div class="submit-bar">
            <div class="submit-container">
                <div class="submit-text">
                    <p>Ready to submit?</p>
                    <h4>Review your selections</h4>
                </div>
                <button type="button" class="btn-submit" onclick="openConfirmModal()">
                    Cast My Vote
                </button>
            </div>
        </div>
    </form>
  </div>

  <!-- Confirmation Modal -->
  <div id="confirmModal" class="modal-overlay">
    <div class="confirm-modal">
        <div class="modal-icon">
            <i data-lucide="shield-check" style="width: 32px; height: 32px;"></i>
        </div>
        <h2>Cast your vote?</h2>
        <p>You are about to submit your choices. This action is permanent and cannot be undone. Are you sure you want to proceed?</p>
        <div class="modal-actions">
            <button type="button" class="btn-modal btn-modal-cancel" onclick="closeConfirmModal()">Review Choices</button>
            <button type="button" class="btn-modal btn-modal-confirm" onclick="submitBallot()">Yes, Cast My Vote</button>
        </div>
    </div>
  </div>

  <footer style="text-align: center; color: var(--text-muted); padding: 4rem 2rem; background: white; border-top: 1px solid var(--border);">
    &copy; <?= date('Y') ?> Click to Vote | High School Online Election System
  </footer>

  <script>
    lucide.createIcons();

    function openConfirmModal() {
        // Basic validation: check if all required radios are checked
        const form = document.getElementById('ballotForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        document.getElementById('confirmModal').classList.add('active');
    }

    function closeConfirmModal() {
        document.getElementById('confirmModal').classList.remove('active');
    }

    function submitBallot() {
        document.getElementById('ballotForm').submit();
    }

    // Countdown Timer
    const endTime = <?= $endTime ?>;
    
    function updateCountdown() {
        const now = new Date().getTime();
        const distance = endTime - now;

        if (distance < 0) {
            document.getElementById("countdown").innerHTML = "EXPIRED";
            document.getElementById("ballotForm").style.opacity = "0.5";
            document.getElementById("ballotForm").style.pointerEvents = "none";
            return;
        }

        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("countdown").innerHTML = 
            (hours < 10 ? "0" : "") + hours + ":" + 
            (minutes < 10 ? "0" : "") + minutes + ":" + 
            (seconds < 10 ? "0" : "") + seconds;
    }

    setInterval(updateCountdown, 1000);
    updateCountdown();
  </script>
</body>
</html>
