<?php
/**
 * Delete Election - voting users only
 */

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

if (!isVoting() && !isAdmin()) {
    header('Location: ' . BASE_PATH . '/voting?toast_error=' . urlencode('Only voting administrators or the assigned manager can delete elections.'));
    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 delete this election.'));
    exit;
}

// Delete the election (cascade will delete positions, candidates, and votes)
$pdo->prepare('DELETE FROM elections WHERE id = ?')->execute([$id]);

header('Location: ' . BASE_PATH . '/voting?toast=' . urlencode('Election deleted successfully.'));
exit;
