<?php
// api/onboarding-check.php — Estado de conexión por servicio para el wizard de onboarding
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../credentials.php';
dm_require_login();

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

// Nombre del cliente
$stmt = $pdo->prepare('SELECT name, services FROM dm_clients WHERE id = ? LIMIT 1');
$stmt->execute([$client_id]);
$client = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$client) { echo json_encode(['ok'=>false,'error'=>'Cliente no encontrado']); exit; }

// Credenciales por servicio
$meta_c   = dm_get_credentials($client_id, 'meta');
$google_c = dm_get_credentials($client_id, 'google');
$gsc_c    = dm_get_credentials($client_id, 'gsc');
$tiktok_c = dm_get_credentials($client_id, 'tiktok');

// Meta Ads
$meta_token = $meta_c['access_token'] ?? (defined('META_SYSTEM_TOKEN') ? META_SYSTEM_TOKEN : '');
$meta_ok    = !empty($meta_token) && !empty($meta_c['ad_account_id']);

// Google Ads
$g_refresh  = defined('GOOGLE_REFRESH_TOKEN') ? GOOGLE_REFRESH_TOKEN : '';
$g_customer = $google_c['customer_id'] ?? (defined('GOOGLE_CUSTOMER_ID') ? GOOGLE_CUSTOMER_ID : '');
$g_dev      = defined('GOOGLE_DEV_TOKEN') ? GOOGLE_DEV_TOKEN : '';
$google_ok  = !empty($g_refresh) && !empty($g_customer) && !empty($g_dev);

// GSC
$gsc_refresh = $gsc_c['refresh_token'] ?? (defined('GOOGLE_REFRESH_TOKEN') ? GOOGLE_REFRESH_TOKEN : '');
$gsc_domain  = $gsc_c['domain'] ?? '';
$gsc_ok      = !empty($gsc_refresh) && !empty($gsc_domain);

// TikTok
$tt_token  = $tiktok_c['access_token'] ?? '';
$tt_adv    = $tiktok_c['advertiser_id'] ?? '';
$tiktok_ok = !empty($tt_token) && !empty($tt_adv);

echo json_encode([
    'ok'     => true,
    'client' => ['id' => $client_id, 'name' => $client['name']],
    'status' => [
        'meta'    => $meta_ok,
        'google'  => $google_ok,
        'gsc'     => $gsc_ok,
        'tiktok'  => $tiktok_ok,
    ],
    'details' => [
        'meta'   => ['ad_account' => !empty($meta_c['ad_account_id'])   ? '✓ ' . $meta_c['ad_account_id']   : '—'],
        'google' => ['customer_id' => !empty($g_customer)               ? '✓ ' . $g_customer                 : '—'],
        'gsc'    => ['domain'      => !empty($gsc_domain)               ? '✓ ' . $gsc_domain                 : '—'],
        'tiktok' => ['advertiser'  => !empty($tt_adv)                   ? '✓ ' . $tt_adv                     : '—'],
    ],
]);
