<?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) {
    return isset($_POST[$key]) ? $_POST[$key] : '';
}

// Initialize settings with existing data or defaults
$settings = [
    'timezone' => '',
    'mail_settings' => [
        'smtpServer' => '',
        'smtpPort' => '',
        'smtpFromEmail' => ''
    ],
    'whatsapp_settings' => [
        'api_endpoint' => '',
        'sender' => '',
        'api_key' => '',
        'default_footer_text' => '',
        'enable_autoreply' => '',
        '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)) {
    $settings = json_decode(file_get_contents($settingsFile), true);
    if (!is_array($settings)) {
        $settings = []; // In case JSON is corrupted
    }
}

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

// Mail Settings
$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');
$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 && $configSaved) {
    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.']);
}
?>
