<?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: view_results.php?id=$id&error=AlreadyVoted");
    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: #6366f1;
        --primary-hover: #4f46e5;
        --bg: #f8fafc;
        --text: #0f172a;
        --text-muted: #64748b;
        --glass: rgba(255, 255, 255, 0.7);
        --glass-border: rgba(255, 255, 255, 0.5);
    }

    body { 
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        color: var(--text);
        font-family: 'Plus Jakarta Sans', sans-serif;
        margin: 0;
        min-height: 100vh;
    }

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

    .timer-banner {
        background: var(--text);
        color: white;
        padding: 12px 24px;
        border-radius: 100px;
        display: inline-flex;
        align-items: center;
        gap: 12px;
        font-weight: 700;
        font-size: 0.875rem;
        margin-bottom: 32px;
        box-shadow: 0 10px 25px -5px rgba(15, 23, 42, 0.2);
    }

    #countdown {
        color: #fbbf24;
        font-variant-numeric: tabular-nums;
    }

    .ballot-header { 
        margin-bottom: 64px; 
    }

    .ballot-header h1 { 
        font-size: 3rem; 
        font-weight: 800; 
        color: var(--text); 
        margin: 0 0 16px 0; 
        letter-spacing: -0.05em;
        line-height: 1;
    }

    .ballot-header p { 
        color: var(--text-muted); 
        font-size: 1.25rem; 
        max-width: 500px;
        margin: 0;
        line-height: 1.6;
    }

    .position-group { 
        margin-bottom: 48px; 
        background: var(--glass);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border-radius: 32px; 
        border: 1px solid var(--glass-border); 
        padding: 40px; 
        box-shadow: 0 20px 40px -15px rgba(0,0,0,0.05);
    }

    .position-title { 
        font-size: 1.5rem; 
        font-weight: 800; 
        color: var(--text); 
        margin-bottom: 32px; 
        display: flex; 
        align-items: center; 
        gap: 16px; 
    }

    .position-title i { 
        padding: 10px;
        background: white;
        border-radius: 14px;
        color: var(--primary);
        box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
    }

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

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

    .candidate-card {
        border: 2px solid transparent;
        border-radius: 24px;
        padding: 24px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        display: flex;
        align-items: center;
        gap: 20px;
        background: white;
        position: relative;
    }

    .candidate-card:hover { 
        transform: translateY(-2px);
        box-shadow: 0 12px 20px -8px rgba(0,0,0,0.1);
    }
    
    input[type="radio"]:checked + .candidate-card, 
    input[type="checkbox"]:checked + .candidate-card {
        border-color: var(--primary);
        background: #f5f3ff;
    }
    
    input[type="radio"]:checked + .candidate-card .check-icon,
    input[type="checkbox"]:checked + .candidate-card .check-icon {
        background: var(--primary);
        color: white;
        border-color: var(--primary);
    }

    input[type="radio"]:checked + .candidate-card .avatar-placeholder {
        background: var(--primary);
        color: white;
    }

    input[type="radio"], input[type="checkbox"] { display: none; }
    
    .avatar-placeholder {
        width: 64px;
        height: 64px;
        background: #f1f5f9;
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 800;
        color: var(--primary);
        font-size: 1.5rem;
        transition: all 0.3s;
    }
    
    .candidate-info h3 { 
        margin: 0; 
        font-size: 1.25rem; 
        font-weight: 800; 
        color: var(--text); 
    }

    .candidate-info p { 
        margin: 4px 0 0 0; 
        font-size: 1rem; 
        color: var(--text-muted); 
        font-weight: 600; 
    }
    
    .check-icon {
        margin-left: auto;
        width: 28px;
        height: 28px;
        border: 2px solid #e2e8f0;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: transparent;
        transition: all 0.3s;
    }

    .submit-bar {
        position: fixed;
        bottom: 32px;
        left: 50%;
        transform: translateX(-50%);
        width: calc(100% - 40px);
        max-width: 800px;
        background: var(--text);
        padding: 20px 40px;
        border-radius: 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: white;
        box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
        z-index: 100;
        backdrop-filter: blur(12px);
    }

    .submit-bar p { margin: 0; font-size: 0.875rem; color: #94a3b8; }
    .submit-bar h4 { margin: 4px 0 0 0; font-size: 1.125rem; font-weight: 700; }

    .btn-submit {
        background: var(--primary);
        color: white;
        border: none;
        padding: 14px 32px;
        border-radius: 16px;
        font-size: 1rem;
        font-weight: 800;
        cursor: pointer;
        transition: all 0.2s;
    }

    .btn-submit:hover { 
        background: var(--primary-hover);
        transform: scale(1.05);
    }

    @media (max-width: 640px) {
        .submit-bar {
            flex-direction: column;
            gap: 16px;
            text-align: center;
            padding: 24px;
        }
        .btn-submit { width: 100%; }
        .ballot-header h1 { font-size: 2.25rem; }
    }
  </style>
</head>
<body>
  <div class="ballot-container">
    <div style="text-align: center;">
        <div class="timer-banner">
            <i data-lucide="clock" style="width: 18px;"></i>
            <span>TIME REMAINING:</span>
            <span id="countdown">00:00:00</span>
        </div>
    </div>

    <div class="ballot-header">
        <h1><?= htmlspecialchars($election['title']) ?></h1>
        <p>Your choice matters. Review the candidates carefully and cast your secure vote below.</p>
    </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">
                    <i data-lucide="shield-check"></i>
                    <?= 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: 32px; background: white; border-radius: 20px; text-align: center; border: 2px dashed #e2e8f0;">
                        <p style="margin: 0; color: var(--text-muted); font-weight: 600;">No candidates available for your track.</p>
                    </div>
                <?php else: ?>
                    <div class="candidates-grid">
                        <?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="avatar-placeholder">
                                        <?= substr($cand['name'], 0, 1) ?>
                                    </div>
                                    <div class="candidate-info">
                                        <h3><?= htmlspecialchars($cand['name']) ?></h3>
                                        <p><?= htmlspecialchars($cand['party_name'] ?: 'Independent') ?></p>
                                    </div>
                                    <div class="check-icon">
                                        <i data-lucide="check" style="width: 16px;"></i>
                                    </div>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>

        <div class="submit-bar">
            <div>
                <p>READY TO SUBMIT?</p>
                <h4>Review your selections</h4>
            </div>
            <button type="submit" class="btn-submit">
                Cast My Vote
            </button>
        </div>
    </form>
  </div>

  <script>
    lucide.createIcons();

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

    document.getElementById('ballotForm').onsubmit = function() {
        return confirm('Are you sure you want to cast your vote? This action is permanent.');
    };
  </script>
</body>
</html>
