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

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

$output = [];
$return_var = 0;
// Using sudo to run as ubuntu user who owns the pm2 process
exec("sudo -u ubuntu /usr/bin/pm2 restart discord-bot 2>&1", $output, $return_var);

if ($return_var === 0) {
    echo json_encode(['success' => true, 'message' => 'Bot restarted successfully']);
} else {
    echo json_encode(['success' => false, 'error' => 'Failed to restart bot', 'details' => implode("\n", $output)]);
}
