<?php
declare(strict_types=1);

function isBotRunning(): bool {
    $output = [];
    exec("ps aux | grep 'node index.js' | grep -v grep", $output);
    return !empty($output);
}

if (isset($_GET['action'])) {
    if ($_GET['action'] === 'start') {
        if (!isBotRunning()) {
            // Run in background
            exec("nohup node index.js > bot.log 2>&1 &");
            sleep(1); // Give it a second to start
        }
    } elseif ($_GET['action'] === 'stop') {
        // Find PID and kill
        $output = [];
        exec("ps aux | grep 'node index.js' | grep -v grep | awk '{print $2}'", $output);
        foreach ($output as $pid) {
            exec("kill $pid");
        }
        sleep(1);
    }
    header("Location: index.php");
    exit;
}
