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

// File paths to the settings JSON files
$settingsFile = '../../database/settings/settings.json';
$configFile = '../../../database/config.json';

// Helper function to safely get POST values
function get_post_value($key) {
    // Sanitize input: Use filter_input for better security/validation in a real application
    // For this example, we stick to the basic check:
    return isset($_POST[$key]) ? $_POST[$key] : '';
}

// Initialize settings with existing data or defaults
// IMPORTANT: Added 'enable_default_footer' to the whatsapp_settings defaults
$settings = [
    'timezone' => '',
    'mail_settings' => [
        'smtpServer' => '',
        'smtpPort' => '',
        'smtpFromEmail' => ''
    ],
    'whatsapp_settings' => [
        'api_endpoint' => '',
        'sender' => '',
        'api_key' => '',
        'default_footer_text' => '',
        'enable_autoreply' => '',
        'enable_default_footer' => '', // <--- ADDED DEFAULT HERE
        'use_ai_model' => ''
    ],
    'gemini_settings' => [
        'api_key' => '',
        'model' => '',
        'api_endpoint' => ''
    ]
];

// Read current settings from the settings JSON file if it exists
if (file_exists($settingsFile)) {
    $currentSettings = json_decode(file_get_contents($settingsFile), true);
    if (is_array($currentSettings)) {
        // Merge existing settings to preserve fields not in the default list
        $settings = array_merge($settings, $currentSettings);
        // Deep merge whatsapp_settings to ensure new keys are present while keeping old ones
        if (isset($currentSettings['whatsapp_settings']) && is_array($currentSettings['whatsapp_settings'])) {
            $settings['whatsapp_settings'] = array_merge($settings['whatsapp_settings'], $currentSettings['whatsapp_settings']);
        }
    }
}

// Update values from POST data
$settings['timezone'] = get_post_value('timezone');

// Mail Settings (assuming fields for mail settings are passed via POST if needed)
$settings['mail_settings']['smtpServer'] = get_post_value('smtpServer');
$settings['mail_settings']['smtpPort'] = get_post_value('smtpPort');
$settings['mail_settings']['smtpFromEmail'] = get_post_value('smtpFromEmail');

// WhatsApp Settings
$settings['whatsapp_settings']['api_endpoint'] = get_post_value('whatsappApiEndpoint');
$settings['whatsapp_settings']['sender'] = get_post_value('whatsappSenderNumber');
$settings['whatsapp_settings']['api_key'] = get_post_value('whatsappApiKey');
$settings['whatsapp_settings']['default_footer_text'] = get_post_value('whatsappFooterText');
$settings['whatsapp_settings']['enable_autoreply'] = get_post_value('whatsappEnabled');

// *** CRITICAL UPDATE: Capture the 'enableDefaultFooter' POST value ***
$settings['whatsapp_settings']['enable_default_footer'] = get_post_value('enableDefaultFooter');

$settings['whatsapp_settings']['use_ai_model'] = get_post_value('useAiModel');

// Gemini Settings
$settings['gemini_settings']['api_key'] = get_post_value('geminiApiKey');
$settings['gemini_settings']['model'] = get_post_value('geminiModel');
$settings['gemini_settings']['api_endpoint'] = get_post_value('geminiApiEndpoint');

// Save the updated settings to the settings JSON file
$settingsSaved = file_put_contents($settingsFile, json_encode($settings, JSON_PRETTY_PRINT));

// Save the updated settings to the config JSON file
$configSaved = file_put_contents($configFile, json_encode($settings, JSON_PRETTY_PRINT));

// Check if both files are saved successfully
if ($settingsSaved !== false && $configSaved !== false) {
    echo json_encode(['status' => 'success', 'message' => 'Settings saved successfully to both files.']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to save settings to one or both files.']);
}
?>