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

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

// Fetch settings
$settings = [];
try {
    $stmt = db()->query("SELECT setting_key, setting_value FROM bot_settings");
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
    exit;
}

$token = $settings['discord_token'] ?? '';
$clientId = $settings['client_id'] ?? '';

if (!$token || !$clientId) {
    echo json_encode(['success' => false, 'error' => 'Token and Client ID are required.']);
    exit;
}

// Execute deployment script
$cmd = "cd ../bot && DISCORD_TOKEN=" . escapeshellarg($token) . " CLIENT_ID=" . escapeshellarg($clientId) . " node deploy-commands.js 2>&1";
exec($cmd, $output, $returnVar);

if ($returnVar === 0) {
    echo json_encode(['success' => true, 'output' => implode("\n", $output)]);
} else {
    echo json_encode(['success' => false, 'error' => implode("\n", $output)]);
}
