<?php
require_once 'auth_helper.php';
$user = get_user();

if (!$user) {
    include 'landing.php';
    exit;
}

if (in_array($user['role'], ['Admin', 'Adviser', 'Officer'])) {
    include 'dashboard.php';
    exit;
}

$pdo = db();

// Voter redirection logic
if ($user['role'] === 'Voter') {
    // Find ongoing elections that this voter is assigned to
    $stmt = $pdo->prepare("
        SELECT e.* FROM elections e
        JOIN election_assignments ea ON e.id = ea.election_id
        WHERE ea.user_id = ? 
        AND e.status = 'Ongoing' 
        AND e.archived = FALSE
        AND e.end_date_and_time > CURRENT_TIMESTAMP
    ");
    $stmt->execute([$user['id']]);
    $activeElections = $stmt->fetchAll();

    // Filter out elections where the user has already voted
    $votedElectionsStmt = $pdo->prepare("SELECT election_id FROM votes WHERE voter_id = ?");
    $votedElectionsStmt->execute([$user['id']]);
    $votedIds = $votedElectionsStmt->fetchAll(PDO::FETCH_COLUMN);

    $eligibleElections = array_filter($activeElections, function($e) use ($votedIds) {
        return !in_array($e['id'], $votedIds);
    });

    if (count($eligibleElections) === 1) {
        $singleElection = reset($eligibleElections);
        header("Location: ballot.php?id=" . $singleElection['id']);
        exit;
    }
    
    // For voters, only show their assigned elections in the list
    $elections = $activeElections;
} else {
    $elections = $pdo->query("SELECT * FROM elections WHERE archived = FALSE ORDER BY created_at DESC")->fetchAll();
}

$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Online Election System for Senior High School';
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Election Dashboard | <?= htmlspecialchars($projectDescription) ?></title>
  <meta name="description" content="<?= htmlspecialchars($projectDescription) ?>" />
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/style.css?v=<?= time() ?>">
</head>
<body>
  <nav class="navbar">
    <a href="index.php" class="brand">E-Vote Pro</a>
    <div>
      <span style="margin-right: 1rem; color: var(--text-muted);"><?= htmlspecialchars($user['name']) ?> (<?= $user['role'] ?>)</span>
      <a href="logout.php" class="btn btn-outline">Logout</a>
    </div>
  </nav>

  <div class="container">
    <?php if (isset($_GET['success'])): ?>
      <div style="background: #dcfce7; color: #166534; padding: 1rem; border-radius: var(--radius); border: 1px solid #bbf7d0; margin-bottom: 1.5rem; font-size: 0.875rem;">
        Action completed successfully.
      </div>
    <?php endif; ?>
    <div class="header-actions">
      <div>
        <h1 style="margin: 0; font-size: 1.5rem;">Elections</h1>
        <p style="margin: 0; color: var(--text-muted);">Manage your school elections and voting sessions.</p>
      </div>
      <?php if (in_array($user['role'], ['Admin', 'Adviser', 'Officer'])): ?>
        <a href="create_election.php" class="btn btn-primary">+ New Election</a>
      <?php endif; ?>
    </div>

    <div class="card">
      <?php if (empty($elections)): ?>
        <div style="text-align: center; padding: 2rem;">
          <p style="color: var(--text-muted);">No elections found. Create your first election to get started.</p>
          <?php if (in_array($user['role'], ['Admin', 'Adviser', 'Officer'])): ?>
            <a href="create_election.php" class="btn btn-outline" style="margin-top: 1rem;">Setup Election</a>
          <?php endif; ?>
        </div>
      <?php else: ?>
        <table class="table">
          <thead>
            <tr>
              <th>Title</th>
              <th>Status</th>
              <th>Period</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($elections as $election): ?>
              <tr>
                <td>
                  <div style="font-weight: 600;"><?= htmlspecialchars($election['title']) ?></div>
                  <div style="font-size: 0.75rem; color: var(--text-muted);"><?= htmlspecialchars($election['description']) ?></div>
                </td>
                <td>
                  <span class="badge badge-<?= strtolower($election['status']) ?>">
                    <?= htmlspecialchars($election['status']) ?>
                  </span>
                </td>
                <td>
                  <div style="font-size: 0.875rem;">
                    <?= date('M d, H:i', strtotime($election['start_date_and_time'])) ?> - 
                    <?= date('M d, H:i', strtotime($election['end_date_and_time'])) ?>
                  </div>
                </td>
                <td>
                  <a href="view_election.php?id=<?= $election['id'] ?>" class="btn btn-outline" style="padding: 0.25rem 0.5rem; font-size: 0.75rem;">View</a>
                  <?php if ($election['status'] === 'Ongoing'): ?>
                    <a href="ballot.php?id=<?= $election['id'] ?>" class="btn btn-primary" style="padding: 0.25rem 0.5rem; font-size: 0.75rem; background: #166534;">Vote</a>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </div>

  <footer style="text-align: center; color: var(--text-muted); padding: 2rem;">
    &copy; <?= date('Y') ?> E-Vote Pro | High School Online Election System
  </footer>
</body>
</html>
