<?php
/**
 * API - Guardar configuración del sistema
 * Fecha: 13 de noviembre de 2025
 */

require_once '../config/config.php';

// Verificar autenticación
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Método no permitido']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(['error' => 'Datos inválidos']);
        exit;
    }
    
    $db = Database::getInstance();
    
    // Mapear configuraciones
    $configMap = [
        'whatsapp_token' => $input['whatsapp_token'] ?? '',
        'phone_number_id' => $input['phone_number_id'] ?? '',
        'webhook_verify_token' => $input['webhook_token'] ?? '',
        'business_name' => $input['business_name'] ?? '',
        'welcome_message' => $input['welcome_message'] ?? ''
    ];
    
    $db->beginTransaction();
    
    try {
        foreach ($configMap as $key => $value) {
            if (!empty($value)) {
                // Verificar si la configuración existe
                $existing = $db->fetch(
                    "SELECT id FROM system_config WHERE config_key = :key",
                    ['key' => $key]
                );
                
                if ($existing) {
                    // Actualizar
                    $db->update(
                        'system_config',
                        ['config_value' => $value, 'updated_at' => date('Y-m-d H:i:s')],
                        'config_key = :key',
                        ['key' => $key]
                    );
                } else {
                    // Insertar
                    $db->insert('system_config', [
                        'config_key' => $key,
                        'config_value' => $value,
                        'description' => 'Configurado desde la interfaz web',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                }
            }
        }
        
        $db->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Configuración guardada correctamente'
        ]);
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    error_log("Error in save_system_config.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
}
?>