<?php
// api/email-data.php — Email Marketing via Mailchimp API v3
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();
dm_csrf_verify();

$input     = json_decode(file_get_contents('php://input'), true) ?? [];
$action    = $input['action'] ?? $_GET['action'] ?? 'campaigns';
$client_id = (int)($input['client_id'] ?? $_GET['client_id'] ?? 0);

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

// Credenciales Mailchimp
$creds = dm_get_credentials($client_id, 'mailchimp');
$api_key = trim($creds['api_key'] ?? '');

if (!$api_key) {
    echo json_encode(['ok'=>false,'error'=>'no_creds','msg'=>'Configura la API key de Mailchimp en ⚙ APIs']);
    exit;
}

// Extraer servidor del API key (formato: key-us1)
$server = 'us1';
if (preg_match('/-([a-z0-9]+)$/', $api_key, $m)) $server = $m[1];
$base = "https://{$server}.api.mailchimp.com/3.0";

function mc_get(string $base, string $api_key, string $path): array {
    $ch = curl_init($base . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_USERPWD        => 'anystring:' . $api_key,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $raw  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code !== 200) return ['_error' => true, '_code' => $code, '_raw' => $raw];
    return json_decode($raw, true) ?? [];
}

// ── Campañas con métricas ─────────────────────────────────────────────────────
if ($action === 'campaigns') {
    $cache_key = "mc_camps_{$client_id}";
    $cached    = dm_cache_get($cache_key);
    if ($cached) { echo json_encode(['ok'=>true,'campaigns'=>$cached,'cached'=>true]); exit; }

    $data = mc_get($base, $api_key, '/campaigns?count=30&status=sent&sort_field=send_time&sort_dir=DESC'
        . '&fields=campaigns.id,campaigns.settings.subject_line,campaigns.settings.title,'
        . 'campaigns.status,campaigns.send_time,campaigns.emails_sent,campaigns.report_summary');

    if (!empty($data['_error'])) {
        $msg = $data['_code'] === 401 ? 'API key inválida' : 'Error Mailchimp HTTP ' . $data['_code'];
        echo json_encode(['ok'=>false,'error'=>$msg]); exit;
    }

    $campaigns = [];
    foreach (($data['campaigns'] ?? []) as $c) {
        $rs = $c['report_summary'] ?? [];
        $sent = (int)($c['emails_sent'] ?? 0);
        $opens = (int)($rs['opens'] ?? 0);
        $unique_opens = (int)($rs['unique_opens'] ?? 0);
        $clicks = (int)($rs['clicks'] ?? 0);
        $unique_clicks = (int)($rs['unique_clicks'] ?? 0);

        $campaigns[] = [
            'id'           => $c['id'],
            'title'        => $c['settings']['title'] ?? '(sin título)',
            'subject'      => $c['settings']['subject_line'] ?? '',
            'status'       => $c['status'],
            'send_time'    => $c['send_time'] ?? '',
            'emails_sent'  => $sent,
            'open_rate'    => $sent > 0 ? round($unique_opens / $sent * 100, 1) : 0,
            'click_rate'   => $sent > 0 ? round($unique_clicks / $sent * 100, 1) : 0,
            'opens'        => $opens,
            'clicks'       => $clicks,
        ];
    }

    dm_cache_set($cache_key, $campaigns, 30);
    echo json_encode(['ok'=>true,'campaigns'=>$campaigns]);
    exit;
}

// ── Métricas de audiencia (listas) ───────────────────────────────────────────
if ($action === 'audience') {
    $data = mc_get($base, $api_key, '/lists?count=5&fields=lists.id,lists.name,lists.stats');
    if (!empty($data['_error'])) { echo json_encode(['ok'=>false,'error'=>'Error cargando audiencias']); exit; }

    $lists = [];
    foreach (($data['lists'] ?? []) as $l) {
        $s = $l['stats'] ?? [];
        $lists[] = [
            'id'            => $l['id'],
            'name'          => $l['name'],
            'member_count'  => (int)($s['member_count'] ?? 0),
            'open_rate'     => round(($s['open_rate'] ?? 0) * 100, 1),
            'click_rate'    => round(($s['click_rate'] ?? 0) * 100, 1),
            'unsub_rate'    => round(($s['unsubscribe_rate'] ?? 0) * 100, 2),
            'avg_bounce'    => round(($s['campaign_bounce_rate'] ?? 0) * 100, 2),
        ];
    }
    echo json_encode(['ok'=>true,'lists'=>$lists]);
    exit;
}

echo json_encode(['ok'=>false,'error'=>'Acción desconocida']);
