<?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'] ?? '';
    $name = $_POST['name'] ?? '';
    $type = $_POST['type'] ?? 'Uniform';

    if (!$election_id || !$name) {
        die("Missing fields");
    }

    try {
        $pdo = db();
        $id = uuid();
        $stmt = $pdo->prepare("INSERT INTO positions (id, election_id, name, type, max_votes) VALUES (?, ?, ?, ?, 1)");
        $stmt->execute([$id, $election_id, $name, $type]);

        audit_log('Added position', 'positions', $id);

        header("Location: ../candidate_management.php?success=1");
        exit;
    } catch (Exception $e) {
        die($e->getMessage());
    }
}
