<?php
declare(strict_types=1);
require_once __DIR__ . '/../auth_helper.php';
require_login();
require_role(['Admin', 'Adviser', 'Officer']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $user = get_user();

    if (!$title || !$start_date || !$end_date) {
        die("Missing required fields.");
    }

    try {
        $pdo = db();
        $id = uuid();
        
        $stmt = $pdo->prepare("INSERT INTO elections (id, title, description, status, start_date_and_time, end_date_and_time, created_by) VALUES (?, ?, ?, 'Preparing', ?, ?, ?)");
        $stmt->execute([$id, $title, $description, $start_date, $end_date, $user['id']]);

        audit_log('Created election', 'elections', $id);

        $redirect = $_POST['redirect'] ?? "../view_election.php?id=$id&success=1";
        header("Location: $redirect");
        exit;
    } catch (Exception $e) {
        die("Error: " . $e->getMessage());
    }
} else {
    header("Location: ../index.php");
    exit;
}
