<?php
require_once '../auth_helper.php';
require_login();
require_role(['Admin', 'Adviser', 'Officer']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = $_POST['id'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];
    $pdo = db();

    try {
        $stmt = $pdo->prepare("UPDATE elections SET title = ?, description = ?, start_date_and_time = ?, end_date_and_time = ? WHERE id = ?");
        $stmt->execute([$title, $description, $startDate, $endDate, $id]);

        $currentUser = get_user();
        audit_log('election_updated', 'elections', $id, null, null, "Updated election $id");

        header("Location: ../view_election.php?id=$id&success=1");
        exit;
    } catch (PDOException $e) {
        die("Error updating election: " . $e->getMessage());
    }
} else {
    header("Location: ../index.php");
    exit;
}
