<?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'] ?? '';

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

    try {
        $pdo = db();
        $stmt = $pdo->prepare("UPDATE candidates SET approved = NOT approved WHERE id = ?");
        $stmt->execute([$id]);

        $stmt = $pdo->prepare("SELECT position_id FROM candidates WHERE id = ?");
        $stmt->execute([$id]);
        $pos_id = $stmt->fetchColumn();

        audit_log('Toggled candidate approval', 'candidates', $id);

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