<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../credentials.php';
dm_require_admin();
dm_csrf_verify();

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

$client_id = (int)($input['client_id'] ?? 0);
$service   = $input['service'] ?? '';
$fields    = $input['fields'] ?? [];

if (!$client_id || !$service || empty($fields)) {
    echo json_encode(['ok'=>false,'error'=>'Faltan datos']); exit;
}

$allowed = ['wordpress','shopify','meta','google','gsc','tiktok','mailchimp'];
if (!in_array($service, $allowed)) {
    echo json_encode(['ok'=>false,'error'=>'Servicio no válido']); exit;
}

$saved = 0;
foreach ($fields as $key => $value) {
    if (!empty($value)) {
        if (dm_set_credential($client_id, $service, $key, $value)) $saved++;
    }
}

dm_log(dm_user()['id'], $client_id, 'save_credentials', "Credenciales {$service} actualizadas");
echo json_encode(['ok'=>true,'saved'=>$saved]);