<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

$input = json_decode(file_get_contents('php://input'), true);
if(!$input || !isset($input['service'])) {
    echo json_encode(['ok' => false, 'error' => 'Datos inválidos']);
    exit;
}

$config_file = dirname(__DIR__) . '/config.php';

// Leer config existente
$existing = [];
if(file_exists($config_file)) {
    $content = file_get_contents($config_file);
    preg_match_all("/define\('([^']+)',\s*'([^']*)'\)/", $content, $matches, PREG_SET_ORDER);
    foreach($matches as $m) $existing[$m[1]] = $m[2];
}

$service = $input['service'];

// Mapear campos según servicio
switch($service) {
    case 'meta':
        if(!empty($input['app_id']))  $existing['META_APP_ID']    = $input['app_id'];
        if(!empty($input['token']))   $existing['META_TOKEN']      = $input['token'];
        if(!empty($input['account'])) $existing['META_ACCOUNT_ID'] = $input['account'];
        break;
    case 'google':
        if(!empty($input['token']))    $existing['GOOGLE_DEV_TOKEN']  = $input['token'];
        if(!empty($input['customer'])) $existing['GOOGLE_CUSTOMER_ID']= $input['customer'];
        if(!empty($input['client']))   $existing['GOOGLE_CLIENT_ID']  = $input['client'];
        break;
    case 'gsc':
        if(!empty($input['json']))   $existing['GSC_JSON_PATH'] = $input['json'];
        if(!empty($input['domain'])) $existing['GSC_DOMAIN']    = $input['domain'];
        break;
    case 'claude':
        if(!empty($input['key'])) $existing['CLAUDE_API_KEY'] = $input['key'];
        break;
    default:
        echo json_encode(['ok' => false, 'error' => 'Servicio desconocido']);
        exit;
}

// Generar archivo config.php
$php = "<?php\n// DIMARK Brain - Configuración de APIs\n// Generado automáticamente - NO subir a repositorios públicos\n\n";
foreach($existing as $key => $val) {
    $safe = addslashes($val);
    $php .= "define('{$key}', '{$safe}');\n";
}
$php .= "\n// Fin de configuración\n";

$written = file_put_contents($config_file, $php);
if($written === false) {
    echo json_encode(['ok' => false, 'error' => 'No se pudo escribir config.php. Verifica permisos del directorio.']);
    exit;
}

echo json_encode(['ok' => true, 'message' => 'Configuración guardada.']);
