<?php
/**
 * Installation and Configuration Script for PFSForum Ollama Bot
 * This script configures the bot to work with the user's domain
 */

// Check if this is being run as a CLI script or web request
if (php_sapi_name() !== 'cli') {
    header('Content-Type: text/html; charset=utf-8');
    echo "<!DOCTYPE html><html><head><title>PFSForum Bot Configuration</title>";
    echo "<style>body { font-family: Arial, sans-serif; margin: 40px; }</style></head><body>";
}

echo "<h1>PFSForum Ollama Bot Configuration</h1>\n";

// Get user input for domain
if (php_sapi_name() === 'cli') {
    // CLI version
    echo "Enter your domain (e.g., secupgrade.com): ";
    $handle = fopen("php://stdin", "r");
    $domain = trim(fgets($handle));
    fclose($handle);
} else {
    // Web version - create form
    if (!isset($_POST['domain'])) {
        echo '<form method="post">';
        echo '<label for="domain">Enter your domain (e.g., secupgrade.com):</label><br>';
        echo '<input type="text" id="domain" name="domain" required><br><br>';
        echo '<input type="submit" value="Configure Bot">';
        echo '</form>';
        exit("</body></html>");
    }
    $domain = $_POST['domain'];
}

// Validate domain input
if (empty($domain)) {
    die("Error: Domain cannot be empty.\n");
}

// Normalize domain (remove protocol and trailing slashes)
$domain = preg_replace('#^https?://#', '', $domain);
$domain = rtrim($domain, '/');

echo "<p>Configuring bot for domain: <strong>{$domain}</strong></p>\n";

// Function to backup a file
function backupFile($filepath) {
    if (file_exists($filepath)) {
        $backupPath = $filepath . '.backup_' . date('Ymd_His');
        copy($filepath, $backupPath);
        echo "Created backup: {$backupPath}<br>\n";
        return $backupPath;
    }
    return null;
}

// Update forum-bot.js to use PHP proxy by default
$forumBotPath = __DIR__ . '/forum-bot.js';
if (file_exists($forumBotPath)) {
    echo "<h3>Updating forum-bot.js...</h3>\n";
    backupFile($forumBotPath);
    
    $content = file_get_contents($forumBotPath);
    
    // Update the configuration to use PHP proxy by default
    $content = preg_replace(
        '/(useProxy:\s*)([a-zA-Z]+)/',
        '${1}true',
        $content
    );
    
    // If the useProxy setting doesn't exist, add it
    if (strpos($content, 'useProxy:') === false) {
        $content = str_replace(
            'temperature: 0.7,',
            "temperature: 0.7,\n                useProxy: true // Always use PHP proxy for all requests",
            $content
        );
    }
    
    file_put_contents($forumBotPath, $content);
    echo "forum-bot.js updated successfully.<br>\n";
} else {
    echo "Warning: forum-bot.js not found at {$forumBotPath}<br>\n";
}

// Update the testOllamaConnection function to respect useProxy
if (file_exists($forumBotPath)) {
    $content = file_get_contents($forumBotPath);
    
    // Make sure the connection test respects the useProxy setting
    if (preg_match('/testOllamaConnection: async function\(\)/', $content)) {
        echo "testOllamaConnection function already updated.<br>\n";
    } else {
        echo "Note: Manual update may be needed for testOllamaConnection function<br>\n";
    }
}

// Update any references to localhost in the JavaScript if needed
$content = file_get_contents($forumBotPath);
$originalContent = $content;

// Replace localhost references with the new domain where appropriate
// Note: We keep localhost for Ollama since it runs locally, but ensure PHP proxy is used
$content = preg_replace(
    '/baseUrl:\s*[\'"]http:\/\/localhost:11434[\'"]/',
    "baseUrl: 'http://localhost:11434'", // Keep localhost for Ollama, but use proxy
    $content
);

if ($content !== $originalContent) {
    file_put_contents($forumBotPath, $content);
    echo "Updated localhost references in forum-bot.js<br>\n";
}

// Update any other relevant files if they exist
$configFiles = [
    __DIR__ . '/app.php',
    __DIR__ . '/api.php',
    __DIR__ . '/bot-handler.php'
];

foreach ($configFiles as $configFile) {
    if (file_exists($configFile)) {
        echo "<h3>Checking {$configFile}...</h3>\n";
        // These files typically don't need domain-specific changes for Ollama
        echo "File exists, no domain-specific changes needed.<br>\n";
    }
}

// Create/update a configuration file
$configContent = "<?php
/**
 * PFSForum Bot Configuration
 * Generated on " . date('Y-m-d H:i:s') . "
 */
define('BOT_CONFIGURED_DOMAIN', '{$domain}');
define('OLLAMA_BASE_URL', 'http://localhost:11434'); // Ollama runs locally
define('USE_PHP_PROXY', true); // Use PHP proxy to avoid CORS issues
define('DEFAULT_MODEL', 'deepseek-v3.1:671b-cloud');
";

$configFilePath = __DIR__ . '/bot-config.php';
file_put_contents($configFilePath, $configContent);
echo "<h3>Created configuration file:</h3>\n";
echo "bot-config.php created with domain settings.<br>\n";

// Instructions
echo "<h3>Configuration Complete!</h3>\n";
echo "<p>The bot has been configured to work with domain: <strong>{$domain}</strong></p>\n";
echo "<p><strong>Next steps:</strong></p>\n";
echo "<ul>\n";
echo "<li>Make sure Ollama is running: <code>ollama serve</code></li>\n";
echo "<li>Verify the model is available: <code>ollama list</code></li>\n";
echo "<li>Clear your browser cache</li>\n";
echo "<li>Test the bot on your forum</li>\n";
echo "</ul>\n";

if (php_sapi_name() !== 'cli') {
    echo "</body></html>";
}
?>