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

dm_require_admin();

function dm_get_credentials_local(int $client_id, string $service): array {
    global $pdo;
    if (!$pdo) return [];
    try {
        $stmt = $pdo->prepare('SELECT key_name, key_value FROM dm_client_credentials WHERE client_id = ? AND service = ?');
        $stmt->execute([$client_id, $service]);
        $result = [];
        foreach ($stmt->fetchAll() as $row) {
            $result[$row['key_name']] = $row['key_value'];
        }
        return $result;
    } catch (Exception $e) { return []; }
}

$client_id = (int)($_GET['client_id'] ?? 0);
if (!$client_id) { echo json_encode(['ok'=>false,'error'=>'client_id requerido']); exit; }

$services = ['meta','google','gsc','wordpress','shopify','mailchimp'];
$has = [];
$credentials = [];
foreach ($services as $svc) {
    $creds = dm_get_credentials_local($client_id, $svc);
    $has[$svc] = !empty($creds);
    // Devolver campos no-sensibles para pre-fill de formularios
    if ($svc === 'wordpress' && !empty($creds)) {
        $credentials['wordpress'] = [
            'wp_url'  => $creds['wp_url']  ?? '',
            'wp_user' => $creds['wp_user'] ?? '',
        ];
    }
}

echo json_encode(['ok'=>true,'has'=>$has,'credentials'=>$credentials]);