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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? '';
    $status = $_POST['status'] ?? '';

    if (!$id || !$status) {
        die("Missing fields");
    }

    try {
        $pdo = db();
        $stmt = $pdo->prepare("UPDATE elections SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);

        audit_log("Updated election status to $status", 'elections', $id);
        
        $redirect = $_POST['redirect'] ?? "../view_election.php?id=$id&success=1";
        header("Location: $redirect");
        exit;

    } catch (Exception $e) {
        die($e->getMessage());
    }
}
