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

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

    if (!$id) {
        die("Missing election ID");
    }

    try {
        $pdo = db();
        $params = [];
        $sql = "UPDATE elections SET ";
        
        if ($status) {
            $sql .= "status = ?, ";
            $params[] = $status;
        }
        
        if ($end_time) {
            $sql .= "end_date_and_time = ?, ";
            $params[] = str_replace('T', ' ', $end_time);
        }
        
        // Remove trailing comma and space
        $sql = rtrim($sql, ', ');
        $sql .= " WHERE id = ?";
        $params[] = $id;

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        audit_log("Election Managed: Status=$status, EndTime=$end_time", 'elections', $id);

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