<?php

namespace App\Controllers;

use Core\Request;
use Core\Redirect;
use Core\DB;

class ConfigEditor
{
    public function updateSettings()
    {
        $configFile = dirname(__DIR__) . '/../config.php';

        if (!file_exists($configFile)) {
            Redirect::redirectError('config_editor', 'Config file not found.');
            return;
        }

        // Load current config content
        $configContent = file_get_contents($configFile);

        // Match define() lines with flexible regex
        preg_match_all('/define\s*\(\s*[\'"]([A-Z_]+)[\'"]\s*,\s*[\'"](.*?)[\'"]\s*\);/', $configContent, $matches, PREG_SET_ORDER);

        $settings = [];
        foreach ($matches as $match) {
            $settings[$match[1]] = stripslashes($match[2]);
        }

        // Fields user can update
        $editableFields = [
            'COMPANY_NAME' => Request::getPost('companyName', 'string'),
            'CLOUDFLARE_TOKEN' => Request::getPost('cloudflare_token', 'string'),
            'CLOUDFLARE_ZONE_ID' => Request::getPost('cloudflare_zone_id', 'string'),
            'BOT_TOKEN' => Request::getPost('bot_token', 'string'),
            'CHAT_ID' => Request::getPost('chat_id', 'string'),
        ];

        // Protected fields - not editable via UI
        $protectedFields = [
            'MAIN_DOMAIN',
            'SERVER_IP',
            'MYSQL_HOST',
            'MYSQL_USER',
            'MYSQL_PASSWORD',
            'MYSQL_DATABASE',
            'DATABASE_FILE',
            'SYSTEM_ZIP_FILE_NAME',
        ];

        // Build new config array
        $newSettings = [];

        foreach ($settings as $key => $value) {
            if (array_key_exists($key, $editableFields)) {
                $newValue = $editableFields[$key] ?? $value;
                $newSettings[$key] = $newValue;
            } else {
                $newSettings[$key] = $value;
            }
        }

        // Just in case some protected fields weren't captured (e.g., commented out), preserve them
        foreach ($protectedFields as $protectedKey) {
            if (!isset($newSettings[$protectedKey])) {
                $newSettings[$protectedKey] = '';
            }
        }

        // Write back to config file
        $output = "<?php\n\n";
        foreach ($newSettings as $key => $val) {
            $output .= 'define("' . $key . '", "' . addslashes($val) . '");' . "\n";
        }

        if (file_put_contents($configFile, $output)) {
            Redirect::redirectSuccess('config_editor', 'Config file updated successfully.');
        } else {
            Redirect::redirectError('config_editor', 'Failed to update config file.');
        }
    }



    public  function saveConfig($settings)
    {
        $configFile = dirname(__DIR__) . '/../config.php';

        // Generate the new config content
        $configContent = "<?php\n\n";
        foreach ($settings as $key => $value) {
            $safeValue = addslashes($value); // Prevent syntax errors
            $configContent .= "define(\"{$key}\", \"{$safeValue}\");\n";
        }

        // Ensure the file is writable
        if (!is_writable($configFile)) {
            return false;
        }

        return file_put_contents($configFile, $configContent) !== false;
    }
}
