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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['discord_token'] ?? '';
    $app_id = $_POST['application_id'] ?? '';

    try {
        $stmt = db()->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'discord_token'");
        $stmt->execute([$token]);

        $stmt = db()->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'application_id'");
        $stmt->execute([$app_id]);

        // Generate config.json for the Node.js bot
        $config = [
            'DISCORD_TOKEN' => $token,
            'DISCORD_CLIENT_ID' => $app_id
        ];
        file_put_contents(__DIR__ . '/config.json', json_encode($config, JSON_PRETTY_PRINT));

        header('Location: index.php?success=1');
        exit;
    } catch (Exception $e) {
        header('Location: index.php?error=' . urlencode($e->getMessage()));
        exit;
    }
}
