38458-vm/api/add_candidate.php
2026-02-15 19:01:09 +00:00

40 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../auth_helper.php';
require_login();
require_role(['Admin', 'Adviser', 'Officer']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$election_id = $_POST['election_id'] ?? '';
$position_id = $_POST['position_id'] ?? '';
$user_id = $_POST['user_id'] ?? '';
$party_name = $_POST['party_name'] ?? '';
$manifesto = $_POST['manifesto'] ?? '';
if (!$election_id || !$position_id || !$user_id) {
die("Missing fields");
}
try {
$pdo = db();
$id = uuid();
// Check if user is already a candidate in this election
$check = $pdo->prepare("SELECT id FROM candidates WHERE election_id = ? AND user_id = ?");
$check->execute([$election_id, $user_id]);
if ($check->fetch()) {
die("User is already a candidate in this election.");
}
$stmt = $pdo->prepare("INSERT INTO candidates (id, election_id, position_id, user_id, party_name, manifesto, approved) VALUES (?, ?, ?, ?, ?, ?, TRUE)");
$stmt->execute([$id, $election_id, $position_id, $user_id, $party_name, $manifesto]);
audit_log('Added candidate', 'candidates', $id);
header("Location: ../manage_candidates.php?position_id=$position_id&success=1");
exit;
} catch (Exception $e) {
die($e->getMessage());
}
}