<?php
session_start();
include '../includes/database.php';
include '../includes/functions.php';

//header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$conn = new Functions();

try {
    $template_id = (int)$_POST['id'];
    $action = $_POST['action'];

    if ($template_id <= 0) {
        throw new Exception("Invalid template ID");
    }

    if (!in_array($action, ['activate', 'deactivate'])) {
        throw new Exception("Invalid action");
    }

    $status = $action === 'activate' ? 'active' : 'inactive';

    $sql = "UPDATE assessment_templates SET status = :status WHERE id = :id";
    $conn->query($sql);
    $conn->bind(':status', $status);
    $conn->bind(':id', $template_id);
    $conn->execute();

    echo json_encode(['success' => true, 'message' => "Template {$action}d successfully"]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}