<?php
declare(strict_types=1);
require_once __DIR__ . '/db/config.php';

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

$action = $_GET['action'] ?? '';
$pidFile = __DIR__ . '/bot.pid';
$botScript = __DIR__ . '/bot.php';

$response = ['success' => false];

function isBotRunning($pidFile) {
    if (!file_exists($pidFile)) return false;
    $pid = (int)file_get_contents($pidFile);
    return posix_getpgid($pid) !== false;
}

if ($action === 'start') {
    if (isBotRunning($pidFile)) {
        $response['error'] = 'Bot is already running.';
    } else {
        $logFile = __DIR__ . '/bot_output.log';
        $cmd = "nohup php $botScript > $logFile 2>&1 & echo $!";
        $pid = trim(shell_exec($cmd));
        if ($pid) {
            file_put_contents($pidFile, $pid);
            $response['success'] = true;
            // Log to DB
            $db = db();
            $db->prepare("INSERT INTO bot_logs (message, log_level) VALUES ('Bot started manually', 'info')")->execute();
        } else {
            $response['error'] = 'Failed to start bot.';
        }
    }
} elseif ($action === 'stop') {
    if (file_exists($pidFile)) {
        $pid = (int)file_get_contents($pidFile);
        exec("kill $pid");
        unlink($pidFile);
        $response['success'] = true;
        // Update status in DB
        $db = db();
        $db->prepare("UPDATE bot_settings SET setting_value = 'offline' WHERE setting_key = 'bot_status'")->execute();
        $db->prepare("INSERT INTO bot_logs (message, log_level) VALUES ('Bot stopped manually', 'info')")->execute();
    } else {
        $response['error'] = 'Bot is not running.';
    }
} elseif ($action === 'restart') {
    // Stop
    if (file_exists($pidFile)) {
        $pid = (int)file_get_contents($pidFile);
        exec("kill $pid");
        unlink($pidFile);
    }
    // Start
    $logFile = __DIR__ . '/bot_output.log';
    $cmd = "nohup php $botScript > $logFile 2>&1 & echo $!";
    $pid = trim(shell_exec($cmd));
    if ($pid) {
        file_put_contents($pidFile, $pid);
        $response['success'] = true;
        $db = db();
        $db->prepare("UPDATE bot_settings SET setting_value = 'online' WHERE setting_key = 'bot_status'")->execute();
        $db->prepare("INSERT INTO bot_logs (message, log_level) VALUES ('Bot restarted manually', 'info')")->execute();
    } else {
        $response['error'] = 'Failed to restart bot.';
    }
} else {
    $response['error'] = 'Invalid action.';
}

echo json_encode($response);
