<?php
/**
 * Quick Configuration Script for PFSForum Ollama Bot and Admin Settings
 * Sets up the bot to work with a custom domain and configures admin password
 */

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

// Get form data
if (isset($_POST['domain']) && isset($_POST['admin_password'])) {
    $domain = trim($_POST['domain']);
    $adminPassword = trim($_POST['admin_password']);
    $confirmPassword = trim($_POST['confirm_password']);

    // Validate passwords match
    if ($adminPassword !== $confirmPassword) {
        die("<p style='color: red;'>Error: Passwords do not match!</p>");
    }
} else {
    // Check if running from command line
    if (php_sapi_name() === 'cli' && isset($argv) && count($argv) > 1) {
        $domain = trim($argv[1]);
        $adminPassword = isset($argv[2]) ? trim($argv[2]) : 'admin123'; // Default for CLI
    } else {
        // Show configuration form
        echo '<form method="post" style="max-width: 500px; margin: 20px auto; padding: 20px; border: 1px solid #ccc;">';
        echo '<h2>Configuration Settings</h2>';

        echo '<label for="domain">Domain (e.g., secupgrade.com):</label><br>';
        echo '<input type="text" id="domain" name="domain" required style="width: 100%; padding: 8px; margin: 10px 0;"><br>';

        echo '<label for="admin_password">Admin Password:</label><br>';
        echo '<input type="password" id="admin_password" name="admin_password" required style="width: 100%; padding: 8px; margin: 10px 0;"><br>';

        echo '<label for="confirm_password">Confirm Admin Password:</label><br>';
        echo '<input type="password" id="confirm_password" name="confirm_password" required style="width: 100%; padding: 8px; margin: 10px 0;"><br>';

        echo '<input type="submit" value="Configure System" style="background: #4CAF50; color: white; padding: 10px 20px; border: none; cursor: pointer;">';
        echo '</form>';
        exit;
    }
}

// Validate domain
if (empty($domain)) {
    if (php_sapi_name() === 'cli') {
        die("Error: Domain cannot be empty!\nUsage: php configure_domain.php <domain> [admin_password]\n");
    } else {
        die("<p style='color: red;'>Error: Domain cannot be empty!</p>");
    }
}

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

// Set default admin password if not set from CLI
if (!isset($adminPassword)) {
    $adminPassword = 'admin123'; // Default
}

echo "<p>Configuring system for domain: <strong>" . htmlspecialchars($domain) . "</strong></p>\n";

// Create or update config.php with the new admin password
$configPath = __DIR__ . '/config.php';
$backupConfigPath = $configPath . '.backup_' . date('Ymd_His');

if (file_exists($configPath)) {
    copy($configPath, $backupConfigPath);
    echo "<p>Backup created: " . basename($backupConfigPath) . "</p>\n";
}

// Generate a new secure key
$newSecureKey = bin2hex(random_bytes(32));

// Create the config file with the new admin password
$configContent = "<?php\n";
$configContent .= "/**\n";
$configContent .= " * PFSForum Configuration File\n";
$configContent .= " * Generated on " . date('Y-m-d H:i:s') . "\n";
$configContent .= " */\n\n";
$configContent .= "// Security settings\n";
$configContent .= "define('ADMIN_PASSWORD_HASH', '" . password_hash($adminPassword, PASSWORD_DEFAULT) . "');\n";
$configContent .= "define('SECURE_KEY', '" . $newSecureKey . "'); // Random secure key for additional security\n\n";
$configContent .= "// Ollama settings\n";
$configContent .= "define('OLLAMA_BASE_URL', 'http://localhost:11434');\n";
$configContent .= "define('DEFAULT_OLLAMA_MODEL', 'deepseek-v3.1:671b-cloud');\n\n";
$configContent .= "// Other settings\n";
$configContent .= "define('FORUM_NAME', 'PFSForum');\n";
$configContent .= "define('ENABLE_REGISTRATION', true);\n\n";
$configContent .= "?>\n";

file_put_contents($configPath, $configContent);
echo "<p>Configuration file updated with new admin password.</p>\n";

// Backup the original forum-bot.js file
$forumBotPath = __DIR__ . '/forum-bot.js';
if (!file_exists($forumBotPath)) {
    die("<p style='color: red;'>Error: forum-bot.js not found!</p>");
}

$backupPath = $forumBotPath . '.backup_' . date('Ymd_His');
copy($forumBotPath, $backupPath);
echo "<p>Backup created: " . basename($backupPath) . "</p>\n";

// Read the current content
$content = file_get_contents($forumBotPath);

// Ensure useProxy is set to true
if (strpos($content, 'useProxy: true') === false) {
    $content = str_replace(
        'temperature: 0.7,',
        "temperature: 0.7,\n                useProxy: true // Always use PHP proxy for all requests",
        $content
    );
    echo "<p>Enabled PHP proxy mode.</p>\n";
} else {
    echo "<p>PHP proxy mode already enabled.</p>\n";
}

// Update the fallback messages to be more generic
$content = str_replace(
    "Please start Ollama with the deepseek-v3.1:671b-cloud model to chat with me.",
    "Please make sure Ollama is running with the deepseek-v3.1:671b-cloud model.",
    $content
);

// Write the updated content back
file_put_contents($forumBotPath, $content);

echo "<p style='color: green;'><strong>Configuration completed successfully!</strong></p>\n";
echo "<h3>Setup Instructions:</h3>\n";
echo "<ol>\n";
echo "<li>Make sure Ollama is running: <code>ollama serve</code></li>\n";
echo "<li>Verify the model is available: <code>ollama pull deepseek-v3.1:671b-cloud</code></li>\n";
echo "<li>Clear your browser cache</li>\n";
echo "<li>Access admin panel with your new password: <code>admin.php</code></li>\n";
echo "<li>Refresh your forum page to load the updated bot</li>\n";
echo "</ol>\n";
echo "<p>The bot will now use the PHP proxy method to communicate with Ollama, avoiding CORS issues.</p>\n";
echo "<p>Your admin password has been securely configured.</p>\n";
?>