<?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: ../candidate_management.php?success=1");
        exit;
    } catch (Exception $e) {
        die($e->getMessage());
    }
}
