<?php
// api/reports.php — Reportes mensuales con ejecuciones, estrategias y resultados
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();

$input     = json_decode(file_get_contents('php://input'), true) ?? [];
$action    = $_GET['action'] ?? $input['action'] ?? 'generate';
$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);

// CSRF solo en acciones de escritura
if ($action === 'generate') dm_csrf_verify();

// ── Helpers ───────────────────────────────────────────────────────────────────

function rfmt(float $v): string {
    if ($v >= 1000000) return '$'.number_format($v/1000000,1,',','.').'M';
    if ($v >= 1000)    return '$'.number_format($v/1000,0,',','.').'K';
    return '$'.number_format($v,0,',','.');
}
function rnum(float $v, int $d=0): string { return number_format($v,$d,',','.'); }

function meta_r(string $ep, array $p, string $tok): array {
    $p['access_token']=$tok;
    $ch=curl_init("https://graph.facebook.com/v19.0/{$ep}?".http_build_query($p));
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>25,CURLOPT_SSL_VERIFYPEER=>false]);
    $r=json_decode(curl_exec($ch),true); curl_close($ch); return $r??[];
}

function gads_r(string $gaql, string $cid, string $access, string $dev_tok, string $mcc_id=''): array {
    $headers=['Authorization: Bearer '.$access,'developer-token: '.$dev_tok,'Content-Type: application/json'];
    if($mcc_id && $mcc_id!==$cid) $headers[]='login-customer-id: '.preg_replace('/[^0-9]/','', $mcc_id);
    $ch=curl_init("https://googleads.googleapis.com/v20/customers/{$cid}/googleAds:searchStream");
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_TIMEOUT=>25,CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_HTTPHEADER=>$headers,
        CURLOPT_POSTFIELDS=>json_encode(['query'=>$gaql])]);
    $r=json_decode(curl_exec($ch),true); curl_close($ch); return $r??[];
}

// ── Listar reportes ───────────────────────────────────────────────────────────
if ($action === 'list') {
    try {
        $rows = $pdo->prepare("SELECT id, period_label, DATE_FORMAT(created_at,'%d/%m/%Y') AS created_at FROM dm_reports WHERE client_id=? ORDER BY period_from DESC LIMIT 24");
        $rows->execute([$client_id]);
        echo json_encode(['ok'=>true,'reports'=>$rows->fetchAll(PDO::FETCH_ASSOC)]);
    } catch (Exception $e) {
        echo json_encode(['ok'=>true,'reports'=>[]]);
    }
    exit;
}

// ── Obtener reporte por ID ────────────────────────────────────────────────────
if ($action === 'get') {
    $id = (int)($_GET['id'] ?? 0);
    if (!$id) { echo json_encode(['ok'=>false,'error'=>'id requerido']); exit; }
    $row = $pdo->prepare("SELECT * FROM dm_reports WHERE id=? AND client_id=?");
    $row->execute([$id, $client_id]);
    $r = $row->fetch(PDO::FETCH_ASSOC);
    if (!$r) { echo json_encode(['ok'=>false,'error'=>'No encontrado']); exit; }
    echo json_encode(['ok'=>true,'html'=>$r['html'],'period_label'=>$r['period_label']]);
    exit;
}

// ── Servicios conectados del cliente ─────────────────────────────────────────
if ($action === 'services') {
    $meta_c   = dm_get_credentials($client_id, 'meta');
    $google_c = dm_get_credentials($client_id, 'google');
    $gsc_c    = dm_get_credentials($client_id, 'gsc');

    // Meta: access_token puede ser por cliente o vía META_SYSTEM_TOKEN global
    $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: refresh_token y dev_token son constantes globales (nunca por cliente)
    $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: usa clave 'domain' (no 'site_url'), refresh_token también puede ser global
    $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);

    echo json_encode(['ok'=>true,'services'=>[
        'meta'   => $meta_ok,
        'google' => $google_ok,
        'seo'    => $gsc_ok,
    ]]);
    exit;
}

// ── GENERATE ─────────────────────────────────────────────────────────────────

$client_row = $pdo->prepare("SELECT * FROM dm_clients WHERE id=?");
$client_row->execute([$client_id]);
$client = $client_row->fetch(PDO::FETCH_ASSOC);
if (!$client) { echo json_encode(['ok'=>false,'error'=>'Cliente no encontrado']); exit; }

$period     = $input['period'] ?? 'last_month';
$date_since = $input['since'] ?? '';
$date_until = $input['until'] ?? '';
$include    = $input['include'] ?? ['meta','google','seo']; // servicios a incluir

if ($date_since && $date_until) {
    $date_from = $date_since; $date_to = $date_until;
    $period_label = date('d M Y', strtotime($date_from)).' — '.date('d M Y', strtotime($date_to));
} else {
    switch ($period) {
        case 'last_7':
            $date_from=date('Y-m-d',strtotime('-7 days')); $date_to=date('Y-m-d');
            $period_label='Últimos 7 días ('.date('d M',strtotime('-7 days')).' — '.date('d M Y').')';
            break;
        case 'last_15':
            $date_from=date('Y-m-d',strtotime('-15 days')); $date_to=date('Y-m-d');
            $period_label='Últimos 15 días ('.date('d M',strtotime('-15 days')).' — '.date('d M Y').')';
            break;
        case 'last_30':
            $date_from=date('Y-m-d',strtotime('-30 days')); $date_to=date('Y-m-d');
            $period_label='Últimos 30 días ('.date('d M',strtotime('-30 days')).' — '.date('d M Y').')';
            break;
        case 'last_90':
            $date_from=date('Y-m-d',strtotime('-90 days')); $date_to=date('Y-m-d');
            $period_label='Últimos 90 días ('.date('d M Y',strtotime('-90 days')).' — '.date('d M Y').')';
            break;
        case 'this_month':
            $date_from=date('Y-m-01'); $date_to=date('Y-m-d');
            $period_label='Mes actual — '.date('F Y');
            break;
        default: // last_month
            $date_from=date('Y-m-01',strtotime('first day of last month'));
            $date_to=date('Y-m-t',strtotime('last month'));
            $period_label='Mes anterior — '.date('F Y',strtotime('last month'));
    }
}

$meta_data=['ok'=>false]; $google_data=['ok'=>false]; $seo_data=['ok'=>false];

// ── RECOPILAR META ADS ────────────────────────────────────────────────────────
if (in_array('meta',$include)) {
    $mc = dm_get_credentials($client_id,'meta');
    $mt = $mc['access_token'] ?? (defined('META_SYSTEM_TOKEN')?META_SYSTEM_TOKEN:'');
    $ma = $mc['ad_account_id'] ?? '';
    if ($mt && $ma) {
        if (strpos($ma,'act_')!==0) $ma='act_'.$ma;
        $tr=json_encode(['since'=>$date_from,'until'=>$date_to]);
        $cr=meta_r("{$ma}/campaigns",[
            'fields'=>'id,name,status,objective,daily_budget,lifetime_budget,insights.time_range('.$tr.'){spend,impressions,clicks,ctr,reach,frequency,cpm,cpc,actions,action_values}',
            'effective_status'=>json_encode(['ACTIVE','PAUSED','WITH_ISSUES']),
            'action_attribution_windows'=>json_encode(['7d_click']),
            'limit'=>50,
        ],$mt);

        $camps=[]; $m_spend=$m_imp=$m_clicks=$m_reach=$m_conv=$m_val=0;
        foreach(($cr['data']??[]) as $c){
            $ci=$c['insights']['data'][0]??[];
            $sp=round((float)($ci['spend']??0),0);
            $conv=0; $val=0;
            foreach(($ci['actions']??[]) as $a){
                $t=$a['action_type']??''; $v=(float)($a['value']??0);
                if(in_array($t,['lead','purchase','complete_registration','messaging_conversation_started_7d','onsite_conversion.messaging_conversation_started_7d','submit_application','contact'])) $conv+=$v;
            }
            foreach(($ci['action_values']??[]) as $a){ if($a['action_type']==='purchase') $val+=(float)($a['value']??0); }
            $m_spend+=$sp; $m_imp+=(int)($ci['impressions']??0); $m_clicks+=(int)($ci['clicks']??0);
            $m_reach+=(int)($ci['reach']??0); $m_conv+=$conv; $m_val+=$val;
            $camps[]=[ 'name'=>$c['name'], 'status'=>strtolower($c['status']),
                'objective'=>str_replace('_',' ',strtolower($c['objective']??'')),
                'spend'=>$sp, 'spend_fmt'=>rfmt($sp),
                'budget'=>parse_budget_r($c['daily_budget']??0,$c['lifetime_budget']??0),
                'impressions'=>(int)($ci['impressions']??0),
                'reach'=>(int)($ci['reach']??0),
                'clicks'=>(int)($ci['clicks']??0),
                'ctr'=>round((float)($ci['ctr']??0),2),
                'cpm'=>round((float)($ci['cpm']??0),0),
                'cpc'=>round((float)($ci['cpc']??0),0),
                'freq'=>round((float)($ci['frequency']??0),2),
                'conv'=>round($conv,0),
                'conv_val'=>round($val,0),
            ];
        }
        usort($camps,fn($a,$b)=>$b['spend']<=>$a['spend']);
        $meta_data=['ok'=>true,'spend'=>$m_spend,'spend_fmt'=>rfmt($m_spend),
            'impressions'=>$m_imp,'clicks'=>$m_clicks,'ctr'=>$m_imp>0?round($m_clicks/$m_imp*100,2):0,
            'reach'=>$m_reach,'conversions'=>round($m_conv,0),'conv_value'=>round($m_val,0),
            'cpa'=>$m_conv>0?round($m_spend/$m_conv,0):0,'cpa_fmt'=>$m_conv>0?rfmt(round($m_spend/$m_conv,0)):'—',
            'roas'=>$m_spend>0&&$m_val>0?round($m_val/$m_spend,2):0,
            'campaigns'=>array_slice($camps,0,8),
        ];
    }
}

function parse_budget_r($daily,$lifetime): string {
    $d=round((float)$daily,0); $l=round((float)$lifetime,0);
    if($d>0) return rfmt($d).'/día';
    if($l>0) return rfmt($l).' total';
    return 'Del Ad Set';
}

// ── RECOPILAR GOOGLE ADS ──────────────────────────────────────────────────────
if (in_array('google',$include)) {
    $gc=dm_get_credentials($client_id,'google');
    $gref=defined('GOOGLE_REFRESH_TOKEN')?GOOGLE_REFRESH_TOKEN:'';
    $gcid=$gc['customer_id']??(defined('GOOGLE_CUSTOMER_ID')?GOOGLE_CUSTOMER_ID:'');
    $gmcc=$gc['mcc_id']??(defined('GOOGLE_MCC_ID')?GOOGLE_MCC_ID:'');
    $gdev=defined('GOOGLE_DEV_TOKEN')?GOOGLE_DEV_TOKEN:'';
    $gcli=defined('GOOGLE_CLIENT_ID')?GOOGLE_CLIENT_ID:'';
    $gsec=defined('GOOGLE_CLIENT_SECRET')?GOOGLE_CLIENT_SECRET:'';
    if($gref&&$gcid&&$gdev){
        $tch=curl_init('https://oauth2.googleapis.com/token');
        curl_setopt_array($tch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_SSL_VERIFYPEER=>false,
            CURLOPT_POSTFIELDS=>http_build_query(['client_id'=>$gcli,'client_secret'=>$gsec,'refresh_token'=>$gref,'grant_type'=>'refresh_token'])]);
        $tr2=json_decode(curl_exec($tch),true); curl_close($tch);
        $gacc=$tr2['access_token']??'';
        $gcid_clean=preg_replace('/[^0-9]/','', $gcid);
        if($gacc){
            // Campañas
            $gr=gads_r("SELECT campaign.name,campaign.status,campaign.advertising_channel_type,metrics.cost_micros,metrics.impressions,metrics.clicks,metrics.conversions,metrics.ctr,metrics.average_cpc,metrics.search_impression_share FROM campaign WHERE segments.date BETWEEN '{$date_from}' AND '{$date_to}' AND metrics.cost_micros > 0 ORDER BY metrics.cost_micros DESC LIMIT 15",$gcid_clean,$gacc,$gdev,$gmcc);
            $g_spend=$g_imp=$g_clicks=$g_conv=0; $g_camps=[];
            foreach(($gr??[]) as $batch){
                foreach(($batch['results']??[]) as $row){
                    $sp=round((float)($row['metrics']['costMicros']??0)/1000000,0);
                    $conv=round((float)($row['metrics']['conversions']??0),1);
                    $g_spend+=$sp; $g_imp+=(int)($row['metrics']['impressions']??0);
                    $g_clicks+=(int)($row['metrics']['clicks']??0); $g_conv+=$conv;
                    $g_camps[]=['name'=>$row['campaign']['name']??'','status'=>strtolower($row['campaign']['status']??''),
                        'type'=>str_replace('_',' ',strtolower($row['campaign']['advertisingChannelType']??'')),
                        'spend'=>$sp,'spend_fmt'=>rfmt($sp),
                        'impressions'=>(int)($row['metrics']['impressions']??0),
                        'clicks'=>(int)($row['metrics']['clicks']??0),
                        'ctr'=>round((float)($row['metrics']['ctr']??0)*100,2),
                        'cpc'=>round((float)($row['metrics']['averageCpc']??0)/1000000,0),
                        'conv'=>$conv,
                        'is'=>$row['metrics']['searchImpressionShare']??null,
                    ];
                }
            }
            // Top keywords
            $kwr=gads_r("SELECT ad_group_criterion.keyword.text,metrics.clicks,metrics.impressions,metrics.average_cpc,metrics.conversions,metrics.search_impression_share FROM keyword_view WHERE segments.date BETWEEN '{$date_from}' AND '{$date_to}' AND metrics.clicks > 0 ORDER BY metrics.clicks DESC LIMIT 10",$gcid_clean,$gacc,$gdev,$gmcc);
            $g_kws=[];
            foreach(($kwr??[]) as $batch){
                foreach(($batch['results']??[]) as $row){
                    $g_kws[]=['kw'=>$row['adGroupCriterion']['keyword']['text']??'',
                        'clicks'=>(int)($row['metrics']['clicks']??0),
                        'imp'=>(int)($row['metrics']['impressions']??0),
                        'cpc'=>round((float)($row['metrics']['averageCpc']??0)/1000000,0),
                        'conv'=>round((float)($row['metrics']['conversions']??0),1),
                    ];
                }
            }
            $google_data=['ok'=>true,'spend'=>$g_spend,'spend_fmt'=>rfmt($g_spend),
                'impressions'=>$g_imp,'clicks'=>$g_clicks,'ctr'=>$g_imp>0?round($g_clicks/$g_imp*100,2):0,
                'conversions'=>$g_conv,'cpa'=>$g_conv>0?round($g_spend/$g_conv,0):0,
                'cpa_fmt'=>$g_conv>0?rfmt(round($g_spend/$g_conv,0)):'—',
                'campaigns'=>$g_camps,'keywords'=>$g_kws,
            ];
        }
    }
}

// ── RECOPILAR SEO ─────────────────────────────────────────────────────────────
if (in_array('seo',$include)) {
    $sc=dm_get_credentials($client_id,'gsc');
    $sref=$sc['refresh_token']??(defined('GOOGLE_REFRESH_TOKEN')?GOOGLE_REFRESH_TOKEN:'');
    $ssite=$sc['domain']??'';
    $gcli2=defined('GOOGLE_CLIENT_ID')?GOOGLE_CLIENT_ID:'';
    $gsec2=defined('GOOGLE_CLIENT_SECRET')?GOOGLE_CLIENT_SECRET:'';
    if($sref&&$ssite){
        $tch=curl_init('https://oauth2.googleapis.com/token');
        curl_setopt_array($tch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_SSL_VERIFYPEER=>false,
            CURLOPT_POSTFIELDS=>http_build_query(['client_id'=>$gcli2,'client_secret'=>$gsec2,'refresh_token'=>$sref,'grant_type'=>'refresh_token'])]);
        $tr3=json_decode(curl_exec($tch),true); curl_close($tch);
        $sacc=$tr3['access_token']??'';
        if($sacc){
            // Métricas globales
            $sch=curl_init("https://searchconsole.googleapis.com/webmasters/v3/sites/".urlencode($ssite)."/searchAnalytics/query");
            curl_setopt_array($sch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_TIMEOUT=>20,
                CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$sacc,'Content-Type: application/json'],
                CURLOPT_POSTFIELDS=>json_encode(['startDate'=>$date_from,'endDate'=>$date_to,'dimensions'=>['query'],'rowLimit'=>10])]);
            $sr=json_decode(curl_exec($sch),true); curl_close($sch);
            // Top páginas
            $pch=curl_init("https://searchconsole.googleapis.com/webmasters/v3/sites/".urlencode($ssite)."/searchAnalytics/query");
            curl_setopt_array($pch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_TIMEOUT=>20,
                CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$sacc,'Content-Type: application/json'],
                CURLOPT_POSTFIELDS=>json_encode(['startDate'=>$date_from,'endDate'=>$date_to,'dimensions'=>['page'],'rowLimit'=>5])]);
            $pr=json_decode(curl_exec($pch),true); curl_close($pch);
            $s_clicks=$s_imp=$s_pos=0; $s_kws=[];
            foreach(($sr['rows']??[]) as $row){
                $s_clicks+=(int)($row['clicks']??0); $s_imp+=(int)($row['impressions']??0);
                $s_pos+=(float)($row['position']??0);
                $s_kws[]=['kw'=>$row['keys'][0]??'','clicks'=>(int)($row['clicks']??0),'pos'=>round((float)($row['position']??0),1),'ctr'=>round((float)($row['ctr']??0)*100,1)];
            }
            $s_pages=[];
            foreach(($pr['rows']??[]) as $row){
                $url=parse_url($row['keys'][0]??'',PHP_URL_PATH)??$row['keys'][0]??'';
                $s_pages[]=['url'=>$url,'clicks'=>(int)($row['clicks']??0),'imp'=>(int)($row['impressions']??0),'ctr'=>round((float)($row['ctr']??0)*100,1),'pos'=>round((float)($row['position']??0),1)];
            }
            $cnt=count($sr['rows']??[]);
            $seo_data=['ok'=>true,'clicks'=>$s_clicks,'impressions'=>$s_imp,
                'ctr'=>$s_imp>0?round($s_clicks/$s_imp*100,1):0,
                'avg_position'=>$cnt>0?round($s_pos/$cnt,1):0,
                'keywords'=>$s_kws,'pages'=>$s_pages,'site'=>$ssite,
            ];
        }
    }
}

// ── ANÁLISIS CLAUDE ───────────────────────────────────────────────────────────
$api_key=defined('CLAUDE_API_KEY')?CLAUDE_API_KEY:'';
$analysis=[
    'executive'=>'','meta_strategy'=>'','meta_results'=>'','meta_observations'=>'',
    'google_strategy'=>'','google_results'=>'','google_observations'=>'',
    'seo_strategy'=>'','seo_results'=>'','seo_observations'=>'','recommendations'=>[]
];

if($api_key){
    $blks=[];
    if(!empty($meta_data['ok'])){
        $camp_lines=array_map(fn($c)=>"  • {$c['name']} [{$c['status']}] obj:{$c['objective']} — {$c['spend_fmt']} invertido, alcance ".rnum($c['reach']).", CTR {$c['ctr']}%, frec {$c['freq']}, {$c['conv']} conv",$meta_data['campaigns']);
        $blks[]="META ADS — {$period_label}:\n- Inversión total: {$meta_data['spend_fmt']}\n- Alcance total: ".rnum($meta_data['reach'])." personas\n- Impresiones: ".rnum($meta_data['impressions'])."\n- CTR promedio: {$meta_data['ctr']}%\n- Conversiones/leads: {$meta_data['conversions']}\n- CPA promedio: {$meta_data['cpa_fmt']}\n- ROAS: {$meta_data['roas']}\nCampañas:\n".implode("\n",$camp_lines);
    }
    if(!empty($google_data['ok'])){
        $gcamp_lines=array_map(fn($c)=>"  • {$c['name']} [{$c['status']}] tipo:{$c['type']} — {$c['spend_fmt']}, CTR {$c['ctr']}%, CPC {$c['cpc']}, {$c['conv']} conv",$google_data['campaigns']);
        $gkw_lines=array_map(fn($k)=>"  • \"{$k['kw']}\" — {$k['clicks']} clics, pos ".($k['imp']>0?round($k['clicks']/$k['imp']*100,1):'—')."% CTR, CPC ".rfmt($k['cpc']).", {$k['conv']} conv",$google_data['keywords']);
        $blks[]="GOOGLE ADS — {$period_label}:\n- Inversión total: {$google_data['spend_fmt']}\n- Clics: ".rnum($google_data['clicks'])."\n- CTR: {$google_data['ctr']}%\n- Conversiones: {$google_data['conversions']}\n- CPA: {$google_data['cpa_fmt']}\nCampañas:\n".implode("\n",$gcamp_lines)."\nTop keywords:\n".implode("\n",$gkw_lines);
    }
    if(!empty($seo_data['ok'])){
        $skw_lines=array_map(fn($k)=>"  • \"{$k['kw']}\" — pos {$k['pos']}, {$k['clicks']} clics, CTR {$k['ctr']}%",$seo_data['keywords']);
        $blks[]="SEO / Google Search Console — {$period_label}:\n- Clics orgánicos: {$seo_data['clicks']}\n- Impresiones: ".rnum($seo_data['impressions'])."\n- CTR orgánico: {$seo_data['ctr']}%\n- Posición promedio: {$seo_data['avg_position']}\nTop keywords:\n".implode("\n",$skw_lines);
    }
    $data_block=implode("\n\n",$blks);
    $modules_inc=implode(', ',array_filter(['Meta Ads'=>!empty($meta_data['ok']),'Google Ads'=>!empty($google_data['ok']),'SEO'=>!empty($seo_data['ok'])],fn($v)=>$v,ARRAY_FILTER_USE_KEY));

    $prompt="Eres el Director de Marketing Digital de DIMARK, agencia experta en marketing digital para el mercado latinoamericano con 20 años de experiencia. Estás redactando el reporte mensual profesional del cliente \"{$client['name']}\" para el período {$period_label}. Los módulos incluidos: {$modules_inc}.

DATOS DEL PERÍODO:
{$data_block}

Genera un informe mensual profesional y detallado. El tono es de experto en marketing digital hablando con el dueño de un negocio: claro, concreto, con criterio y siempre orientado a resultados. Usa los números reales del período en cada sección.

Responde ÚNICAMENTE con este JSON válido (sin markdown, sin texto antes ni después):
{
  \"executive\": \"Resumen ejecutivo de 4-5 oraciones: menciona la inversión total, el resultado más importante del mes, qué canal tuvo mejor desempeño, una observación sobre tendencia y el foco recomendado para el próximo mes.\",
  \"meta_strategy\": \"Estrategia ejecutada en Meta Ads (4-5 oraciones): qué tipo de campañas se corrieron, cuáles fueron los objetivos (tráfico/conversiones/alcance), a qué audiencias se dirigió la pauta, formatos utilizados y distribución del presupuesto entre campañas.\",
  \"meta_results\": \"Análisis de resultados Meta Ads (4-5 oraciones): interpreta los números clave del período — inversión, alcance, CTR, conversiones y CPA. Indica qué campañas tuvieron mejor desempeño y por qué. Si el CPA es alto o el CTR es bajo, explica qué lo puede estar causando.\",
  \"meta_observations\": \"Observaciones y consejos Meta Ads (3-4 oraciones): qué aspectos específicos funcionaron bien este mes, qué señales de alerta detectas en los datos, y una recomendación concreta de optimización para el próximo período.\",
  \"google_strategy\": \"Estrategia ejecutada en Google Ads (4-5 oraciones): tipos de campañas activas, enfoque de keywords (búsquedas que se están capturando), estrategia de puja utilizada y cómo se distribuyó el presupuesto.\",
  \"google_results\": \"Análisis de resultados Google Ads (4-5 oraciones): interpreta los clics, CTR, CPC y conversiones. Destaca qué keywords generaron más conversiones y cuál fue el costo por conversión. Compara eficiencia si hay varias campañas.\",
  \"google_observations\": \"Observaciones y consejos Google Ads (3-4 oraciones): oportunidades detectadas en keywords o audiencias, campañas que merecen más presupuesto, términos de búsqueda relevantes que se podrían agregar o excluir, y una recomendación de acción inmediata.\",
  \"seo_strategy\": \"Contexto SEO del período (3-4 oraciones): qué tipo de visibilidad orgánica tiene este cliente, en qué categorías o servicios está posicionado, y cuál es el enfoque general de la estrategia SEO.\",
  \"seo_results\": \"Resultados SEO (4-5 oraciones): interpreta los clics orgánicos, impresiones, CTR y posición promedio del período. Destaca las keywords con mejor rendimiento y las páginas con más tráfico orgánico.\",
  \"seo_observations\": \"Observaciones y consejos SEO (3-4 oraciones): tendencias detectadas (keywords subiendo o bajando), páginas con potencial de mejora, y una acción concreta recomendada para mejorar el posicionamiento en el próximo mes.\",
  \"recommendations\": [
    {\"priority\": \"alta\", \"area\": \"meta\", \"action\": \"Acción específica y concreta\", \"reason\": \"Por qué es prioritaria ahora\"},
    {\"priority\": \"alta\", \"area\": \"google\", \"action\": \"Acción específica y concreta\", \"reason\": \"Por qué impacta los resultados\"},
    {\"priority\": \"alta\", \"area\": \"seo\", \"action\": \"Acción específica y concreta\", \"reason\": \"Por qué es relevante este mes\"},
    {\"priority\": \"media\", \"area\": \"meta\", \"action\": \"Acción de mejora a mediano plazo\", \"reason\": \"Beneficio esperado\"},
    {\"priority\": \"media\", \"area\": \"google\", \"action\": \"Acción de mejora a mediano plazo\", \"reason\": \"Beneficio esperado\"}
  ]
}";

    $ch=curl_init('https://api.anthropic.com/v1/messages');
    curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_TIMEOUT=>60,
        CURLOPT_HTTPHEADER=>['x-api-key:'.$api_key,'anthropic-version:2023-06-01','Content-Type:application/json'],
        CURLOPT_POSTFIELDS=>json_encode(['model'=>'claude-haiku-4-5-20251001','max_tokens'=>4000,
            'messages'=>[['role'=>'user','content'=>$prompt]]])]);
    $raw=curl_exec($ch); $http=curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch);
    if($http===200){
        $res=json_decode($raw,true);
        $txt=trim($res['content'][0]['text']??'');
        if(preg_match('/\{[\s\S]*\}/s',$txt,$m)){
            $parsed=json_decode($m[0],true);
            if($parsed) $analysis=array_merge($analysis,$parsed);
        }
    }
}

// ── CONSTRUIR HTML ────────────────────────────────────────────────────────────
$logo_path=__DIR__.'/../uploads/brand/'.$client_id.'/logo.*';
$logo_files=glob($logo_path);
$logo_tag='';
if($logo_files){
    $ext=pathinfo($logo_files[0],PATHINFO_EXTENSION);
    $ld=base64_encode(file_get_contents($logo_files[0]));
    $mime=$ext==='svg'?'image/svg+xml':'image/'.$ext;
    $logo_tag='<img src="data:'.$mime.';base64,'.$ld.'" alt="Logo" style="max-height:48px;max-width:150px;object-fit:contain">';
}
$gen_date=date('d \d\e F \d\e Y');
$h=fn(string $s):string=>htmlspecialchars($s,ENT_QUOTES,'UTF-8');
$total_inv=($meta_data['spend']??0)+($google_data['spend']??0);

// Helpers de tabla
function tr_camp(array $c, string $type='meta'): string {
    $badge=$c['status']==='active'||$c['status']==='enabled'
        ?'<span style="background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:12px;font-size:10px;font-weight:600">Activa</span>'
        :'<span style="background:#fef9c3;color:#a16207;padding:2px 8px;border-radius:12px;font-size:10px;font-weight:600">Pausada</span>';
    $extra=$type==='meta'
        ?'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right">'.($c['freq']>0?$c['freq']:'—').'</td><td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right">'.($c['conv']>0?rnum($c['conv']):'—').'</td>'
        :'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right">'.rfmt($c['cpc']??0).'</td><td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right">'.($c['conv']>0?rnum($c['conv']):'—').'</td>';
    $obj=$type==='meta'?'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;font-size:10px;color:#64748b">'.ucfirst($c['objective']??'').'</td>':'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;font-size:10px;color:#64748b">'.ucfirst($c['type']??'').'</td>';
    return '<tr><td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;font-size:11px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">'.htmlspecialchars($c['name'],ENT_QUOTES,'UTF-8').'</td>'.$badge_td=$badge?'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9">'.$badge.'</td>':''
        .$obj
        .'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right;font-weight:700">'.$c['spend_fmt'].'</td>'
        .'<td style="padding:7px 10px;border-bottom:1px solid #f1f5f9;text-align:right">'.($c['ctr']>0?$c['ctr'].'%':'—').'</td>'
        .$extra.'</tr>';
}

ob_start(); ?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Reporte — <?= $h($client['name']) ?> — <?= $h($period_label) ?></title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Helvetica Neue',Arial,sans-serif;font-size:13px;color:#1e293b;background:#f1f5f9}
.page{max-width:920px;margin:0 auto;background:#fff;box-shadow:0 2px 12px rgba(0,0,0,.08)}
.rh{background:linear-gradient(130deg,#0f172a 0%,#e8272a 100%);color:#fff;padding:36px 48px;display:flex;justify-content:space-between;align-items:flex-start}
.rh h1{font-size:20px;font-weight:700;margin-top:8px}
.rh p{font-size:12px;opacity:.7;margin-top:3px}
.rh-r{text-align:right}.rh-r .per{font-size:16px;font-weight:700}
.rh-r .gen{font-size:10px;opacity:.6;margin-top:4px}
.totals{display:flex;gap:16px;padding:24px 48px 0}
.tc{flex:1;background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:16px 18px;text-align:center}
.tc .v{font-size:22px;font-weight:800;color:#0f172a}.tc .l{font-size:10px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin-top:3px}
.tc.hi{border-color:#e8272a;background:#fff5f5}.tc.hi .v{color:#e8272a}
.exec{margin:24px 48px;background:#f0f9ff;border-left:4px solid #e8272a;border-radius:0 8px 8px 0;padding:18px 22px}
.exec .lbl{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:#e8272a;margin-bottom:7px}
.exec p{font-size:13px;line-height:1.75;color:#334155}
.sec{margin:0 48px 32px}
.sh{display:flex;align-items:center;gap:10px;margin-bottom:14px;padding-bottom:10px;border-bottom:2px solid #f1f5f9}
.si{width:34px;height:34px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:17px}
.si.m{background:#eff6ff}.si.g{background:#f0fdf4}.si.s{background:#fefce8}
.sh h2{font-size:14px;font-weight:700}.sh .src{font-size:11px;color:#94a3b8;margin-left:auto}
.mg{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:14px}
.mc{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px}
.mc .mv{font-size:17px;font-weight:700}.mc .ml{font-size:10px;color:#64748b;margin-top:2px}
.mc.hi{border-color:#e8272a;background:#fff8f8}.mc.hi .mv{color:#e8272a}
.box{background:#f8fafc;border-radius:8px;padding:13px 16px;margin-bottom:12px;font-size:12px;line-height:1.7;color:#475569}
.box.strat{background:#f0fdf4;border-left:3px solid #22c55e}
.box.res{background:#fff7ed;border-left:3px solid #f59e0b}
.box-lbl{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;margin-bottom:5px}
.box.strat .box-lbl{color:#15803d}.box.res .box-lbl{color:#b45309}
table{width:100%;border-collapse:collapse;font-size:11px}
thead tr{background:#f1f5f9}
thead th{padding:7px 10px;text-align:left;font-weight:600;font-size:9px;text-transform:uppercase;letter-spacing:.4px;color:#64748b}
thead th:not(:first-child){text-align:right}
.recs{margin:0 48px 32px;background:#1e293b;border-radius:12px;padding:22px 26px;color:#fff}
.recs h2{font-size:13px;font-weight:700;margin-bottom:14px;color:#f8fafc}
.rec-item{display:flex;gap:10px;align-items:flex-start;padding:9px 0;border-bottom:1px solid rgba(255,255,255,.08)}
.rec-item:last-child{border-bottom:none}
.rec-badge{padding:2px 8px;border-radius:10px;font-size:9px;font-weight:700;white-space:nowrap}
.rec-badge.alta{background:#dc2626;color:#fff}
.rec-badge.media{background:#d97706;color:#fff}
.rec-badge.baja{background:#0891b2;color:#fff}
.rec-area{font-size:10px;color:#94a3b8;white-space:nowrap;min-width:50px}
.rec-body{flex:1}.rec-txt{font-size:12px;color:#e2e8f0;line-height:1.5}
.rec-reason{font-size:11px;color:#94a3b8;margin-top:3px;line-height:1.4}
.rf{background:#0f172a;color:#64748b;padding:18px 48px;display:flex;justify-content:space-between;align-items:center;font-size:10px;margin-top:32px}
.rf .brand{font-weight:700;color:#fff;font-size:12px}
.np-bar{padding:10px 48px;background:#f1f5f9;display:flex;gap:8px;align-items:center}
.box.obs{background:#eff6ff;border-left:3px solid #3b82f6}
.box.obs .box-lbl{color:#1d4ed8}
.mg5{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin-bottom:14px}
.mg6{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;margin-bottom:14px}
.tbl-wrap{overflow-x:auto;margin-bottom:14px}
@media print{
  body{background:#fff}.page{box-shadow:none;max-width:100%}
  .np-bar{display:none!important}
  .sec,.exec,.recs{break-inside:avoid}
  .rh,.rf,.recs,.tc.hi,.mc.hi{-webkit-print-color-adjust:exact;print-color-adjust:exact}
  .box.strat,.box.res,.box.obs{-webkit-print-color-adjust:exact;print-color-adjust:exact}
}
</style>
</head>
<body>
<div class="page">

<div class="np-bar">
  <button onclick="window.print()" style="padding:7px 16px;background:#e8272a;color:#fff;border:none;border-radius:6px;font-size:11px;font-weight:700;cursor:pointer">🖨 Imprimir / Guardar PDF</button>
  <span style="font-size:11px;color:#64748b">En el diálogo de impresión activa <strong>"Gráficos de fondo"</strong> para conservar colores.</span>
</div>

<!-- HEADER -->
<div class="rh">
  <div>
    <?= $logo_tag ?>
    <h1><?= $h($client['name']) ?></h1>
    <p>Reporte de Marketing Digital</p>
  </div>
  <div class="rh-r">
    <div class="per"><?= $h($period_label) ?></div>
    <div class="gen">Generado el <?= $gen_date ?></div>
    <div style="margin-top:8px;font-size:10px;opacity:.5">DIMARK — SuperCerebro</div>
  </div>
</div>

<!-- TOTALES GLOBALES -->
<div class="totals">
  <?php if($total_inv>0): ?><div class="tc hi"><div class="v"><?= rfmt($total_inv) ?></div><div class="l">Inversión total</div></div><?php endif ?>
  <?php if(!empty($meta_data['ok'])): ?>
    <div class="tc"><div class="v"><?= rnum($meta_data['conversions']) ?></div><div class="l">Conv. Meta</div></div>
    <?php if($meta_data['roas']>0): ?><div class="tc"><div class="v"><?= $meta_data['roas'] ?>x</div><div class="l">ROAS Meta</div></div><?php endif ?>
  <?php endif ?>
  <?php if(!empty($google_data['ok'])): ?><div class="tc"><div class="v"><?= rnum($google_data['conversions']) ?></div><div class="l">Conv. Google</div></div><?php endif ?>
  <?php if(!empty($seo_data['ok'])): ?><div class="tc"><div class="v"><?= rnum($seo_data['clicks']) ?></div><div class="l">Clics orgánicos</div></div><?php endif ?>
</div>
<div style="height:24px"></div>

<!-- EXECUTIVE SUMMARY -->
<?php if(!empty($analysis['executive'])): ?>
<div class="exec"><div class="lbl">Resumen Ejecutivo — <?= $h($period_label) ?></div><p><?= $h($analysis['executive']) ?></p></div>
<?php endif ?>

<!-- ═══════════════════════ META ADS ═══════════════════════ -->
<?php if(!empty($meta_data['ok'])): ?>
<div class="sec">
  <div class="sh"><div class="si m">📘</div><h2>Meta Ads</h2><span class="src">Facebook · Instagram · <?= $h($period_label) ?></span></div>

  <!-- Métricas principales -->
  <div class="mg6">
    <div class="mc hi"><div class="mv"><?= $meta_data['spend_fmt'] ?></div><div class="ml">Inversión</div></div>
    <div class="mc"><div class="mv"><?= rnum($meta_data['reach']) ?></div><div class="ml">Alcance</div></div>
    <div class="mc"><div class="mv"><?= rnum($meta_data['impressions']) ?></div><div class="ml">Impresiones</div></div>
    <div class="mc"><div class="mv"><?= $meta_data['ctr'] ?>%</div><div class="ml">CTR prom.</div></div>
    <div class="mc"><div class="mv"><?= rnum($meta_data['conversions']) ?></div><div class="ml">Conversiones</div></div>
    <div class="mc<?= $meta_data['cpa']>0?' hi':'' ?>"><div class="mv"><?= $meta_data['cpa_fmt'] ?></div><div class="ml">CPA</div></div>
  </div>
  <?php if($meta_data['roas']>0||$meta_data['conv_value']>0): ?>
  <div class="mg" style="grid-template-columns:repeat(2,1fr);margin-bottom:14px">
    <?php if($meta_data['conv_value']>0): ?><div class="mc"><div class="mv"><?= rfmt($meta_data['conv_value']) ?></div><div class="ml">Valor de conversiones</div></div><?php endif ?>
    <?php if($meta_data['roas']>0): ?><div class="mc"><div class="mv"><?= $meta_data['roas'] ?>x</div><div class="ml">ROAS</div></div><?php endif ?>
  </div>
  <?php endif ?>

  <!-- Análisis AVI -->
  <?php if(!empty($analysis['meta_strategy'])): ?>
  <div class="box strat"><div class="box-lbl">🎯 Estrategia ejecutada</div><?= nl2br($h($analysis['meta_strategy'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['meta_results'])): ?>
  <div class="box res"><div class="box-lbl">📊 Análisis de resultados</div><?= nl2br($h($analysis['meta_results'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['meta_observations'])): ?>
  <div class="box obs"><div class="box-lbl">💡 Observaciones y consejos</div><?= nl2br($h($analysis['meta_observations'])) ?></div>
  <?php endif ?>

  <!-- Tabla campañas -->
  <?php if(!empty($meta_data['campaigns'])): ?>
  <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin:14px 0 8px">Detalle de campañas</div>
  <div class="tbl-wrap"><table>
    <thead><tr>
      <th style="min-width:160px">Campaña</th><th>Estado</th><th>Objetivo</th><th>Inversión</th>
      <th>Alcance</th><th>Impr.</th><th>CTR</th><th>Frec.</th><th>CPM</th><th>CPC</th><th>Conv.</th><th>Presupuesto</th>
    </tr></thead>
    <tbody>
    <?php foreach($meta_data['campaigns'] as $c): $td='padding:7px 10px;border-bottom:1px solid #f1f5f9'; ?>
    <tr>
      <td style="<?=$td?>;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= $h($c['name']) ?></td>
      <td style="<?=$td?>"><?= $c['status']==='active'?'<span style="background:#dcfce7;color:#15803d;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700">Activa</span>':'<span style="background:#fef9c3;color:#a16207;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700">Pausada</span>' ?></td>
      <td style="<?=$td?>;font-size:10px;color:#64748b"><?= $h(ucfirst($c['objective']??'')) ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700"><?= $c['spend_fmt'] ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['reach']>0?rnum($c['reach']):'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['impressions']>0?rnum($c['impressions']):'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['ctr']>0?$c['ctr'].'%':'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['freq']>0?$c['freq']:'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['cpm']>0?rfmt($c['cpm']):'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['cpc']>0?rfmt($c['cpc']):'—' ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700;color:<?=$c['conv']>0?'#15803d':'#94a3b8'?>"><?= $c['conv']>0?rnum($c['conv']):'—' ?></td>
      <td style="<?=$td?>;text-align:right;font-size:10px;color:#64748b"><?= $c['budget'] ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
  </table></div>
  <?php endif ?>
</div>
<?php endif ?>

<!-- ═══════════════════════ GOOGLE ADS ═══════════════════════ -->
<?php if(!empty($google_data['ok'])): ?>
<div class="sec">
  <div class="sh"><div class="si g">🟢</div><h2>Google Ads</h2><span class="src">Search · Display · <?= $h($period_label) ?></span></div>

  <div class="mg5">
    <div class="mc hi"><div class="mv"><?= $google_data['spend_fmt'] ?></div><div class="ml">Inversión</div></div>
    <div class="mc"><div class="mv"><?= rnum($google_data['clicks']) ?></div><div class="ml">Clics</div></div>
    <div class="mc"><div class="mv"><?= $google_data['ctr'] ?>%</div><div class="ml">CTR</div></div>
    <div class="mc"><div class="mv"><?= rnum($google_data['conversions']) ?></div><div class="ml">Conversiones</div></div>
    <div class="mc<?= $google_data['cpa']>0?' hi':'' ?>"><div class="mv"><?= $google_data['cpa_fmt'] ?></div><div class="ml">CPA</div></div>
  </div>

  <?php if(!empty($analysis['google_strategy'])): ?>
  <div class="box strat"><div class="box-lbl">🎯 Estrategia ejecutada</div><?= nl2br($h($analysis['google_strategy'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['google_results'])): ?>
  <div class="box res"><div class="box-lbl">📊 Análisis de resultados</div><?= nl2br($h($analysis['google_results'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['google_observations'])): ?>
  <div class="box obs"><div class="box-lbl">💡 Observaciones y consejos</div><?= nl2br($h($analysis['google_observations'])) ?></div>
  <?php endif ?>

  <!-- Tabla campañas -->
  <?php if(!empty($google_data['campaigns'])): ?>
  <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin:14px 0 8px">Detalle de campañas</div>
  <div class="tbl-wrap"><table>
    <thead><tr>
      <th style="min-width:160px">Campaña</th><th>Estado</th><th>Tipo</th><th>Inversión</th>
      <th>Clics</th><th>Impr.</th><th>CTR</th><th>CPC prom.</th><th>Conv.</th><th>IS%</th>
    </tr></thead>
    <tbody>
    <?php foreach($google_data['campaigns'] as $c): $td='padding:7px 10px;border-bottom:1px solid #f1f5f9'; ?>
    <tr>
      <td style="<?=$td?>;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= $h($c['name']) ?></td>
      <td style="<?=$td?>"><?= $c['status']==='enabled'?'<span style="background:#dcfce7;color:#15803d;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700">Activa</span>':'<span style="background:#fef9c3;color:#a16207;padding:2px 7px;border-radius:10px;font-size:9px;font-weight:700">Pausada</span>' ?></td>
      <td style="<?=$td?>;font-size:10px;color:#64748b"><?= $h(ucfirst($c['type']??'')) ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700"><?= $c['spend_fmt'] ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($c['clicks']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($c['impressions']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['ctr']>0?$c['ctr'].'%':'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $c['cpc']>0?rfmt($c['cpc']):'—' ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700;color:<?=$c['conv']>0?'#15803d':'#94a3b8'?>"><?= $c['conv']>0?rnum($c['conv']):'—' ?></td>
      <td style="<?=$td?>;text-align:right;font-size:10px"><?= !empty($c['is'])?round((float)$c['is']*100,1).'%':'—' ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
  </table></div>
  <?php endif ?>

  <!-- Top Keywords -->
  <?php if(!empty($google_data['keywords'])): ?>
  <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin:16px 0 8px">Top Keywords</div>
  <div class="tbl-wrap"><table>
    <thead><tr><th>Keyword</th><th>Clics</th><th>Impr.</th><th>CTR</th><th>CPC prom.</th><th>Conv.</th></tr></thead>
    <tbody>
    <?php foreach($google_data['keywords'] as $k): $td='padding:6px 10px;border-bottom:1px solid #f1f5f9'; ?>
    <tr>
      <td style="<?=$td?>"><?= $h($k['kw']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($k['clicks']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($k['imp']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= $k['imp']>0?round($k['clicks']/$k['imp']*100,2).'%':'—' ?></td>
      <td style="<?=$td?>;text-align:right"><?= $k['cpc']>0?rfmt($k['cpc']):'—' ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700;color:<?=$k['conv']>0?'#15803d':'#94a3b8'?>"><?= $k['conv']>0?rnum($k['conv']):'—' ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
  </table></div>
  <?php endif ?>
</div>
<?php endif ?>

<!-- ═══════════════════════ SEO ═══════════════════════ -->
<?php if(!empty($seo_data['ok'])): ?>
<div class="sec">
  <div class="sh"><div class="si s">🔍</div><h2>SEO Orgánico</h2><span class="src">Google Search Console · <?= $h($period_label) ?></span></div>

  <div class="mg">
    <div class="mc hi"><div class="mv"><?= rnum($seo_data['clicks']) ?></div><div class="ml">Clics orgánicos</div></div>
    <div class="mc"><div class="mv"><?= rnum($seo_data['impressions']) ?></div><div class="ml">Impresiones</div></div>
    <div class="mc"><div class="mv"><?= $seo_data['ctr'] ?>%</div><div class="ml">CTR orgánico</div></div>
    <div class="mc"><div class="mv"><?= $seo_data['avg_position'] ?></div><div class="ml">Posición prom.</div></div>
  </div>

  <?php if(!empty($analysis['seo_strategy'])): ?>
  <div class="box strat"><div class="box-lbl">🎯 Contexto y estrategia SEO</div><?= nl2br($h($analysis['seo_strategy'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['seo_results'])): ?>
  <div class="box res"><div class="box-lbl">📊 Análisis de resultados</div><?= nl2br($h($analysis['seo_results'])) ?></div>
  <?php endif ?>
  <?php if(!empty($analysis['seo_observations'])): ?>
  <div class="box obs"><div class="box-lbl">💡 Observaciones y consejos</div><?= nl2br($h($analysis['seo_observations'])) ?></div>
  <?php endif ?>

  <!-- Top Keywords -->
  <?php if(!empty($seo_data['keywords'])): ?>
  <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin:14px 0 8px">Top Keywords orgánicas</div>
  <div class="tbl-wrap"><table>
    <thead><tr><th>Keyword</th><th>Clics</th><th>Impresiones</th><th>CTR</th><th>Posición</th></tr></thead>
    <tbody>
    <?php foreach($seo_data['keywords'] as $k): $td='padding:7px 10px;border-bottom:1px solid #f1f5f9'; ?>
    <tr>
      <td style="<?=$td?>"><?= $h($k['kw']) ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700"><?= rnum($k['clicks']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($k['clicks']>0&&$k['ctr']>0?round($k['clicks']/$k['ctr']*100):0) ?></td>
      <td style="<?=$td?>;text-align:right"><?= $k['ctr'] ?>%</td>
      <td style="<?=$td?>;text-align:right"><?= $k['pos'] ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
  </table></div>
  <?php endif ?>

  <!-- Top Páginas -->
  <?php if(!empty($seo_data['pages'])): ?>
  <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.5px;margin:16px 0 8px">Top Páginas</div>
  <div class="tbl-wrap"><table>
    <thead><tr><th>Página</th><th>Clics</th><th>Impresiones</th><th>CTR</th><th>Posición</th></tr></thead>
    <tbody>
    <?php foreach($seo_data['pages'] as $p): $td='padding:7px 10px;border-bottom:1px solid #f1f5f9'; ?>
    <tr>
      <td style="<?=$td?>;max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px"><?= $h($p['url']) ?></td>
      <td style="<?=$td?>;text-align:right;font-weight:700"><?= rnum($p['clicks']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= rnum($p['imp']) ?></td>
      <td style="<?=$td?>;text-align:right"><?= $p['ctr'] ?>%</td>
      <td style="<?=$td?>;text-align:right"><?= $p['pos'] ?></td>
    </tr>
    <?php endforeach ?>
    </tbody>
  </table></div>
  <?php endif ?>
</div>
<?php endif ?>

<!-- ═══════════════════════ RECOMENDACIONES ═══════════════════════ -->
<?php if(!empty($analysis['recommendations'])): ?>
<div class="recs">
  <h2>📌 Plan de acción para el próximo mes</h2>
  <?php foreach($analysis['recommendations'] as $rec): ?>
  <div class="rec-item">
    <span class="rec-badge <?= $h($rec['priority']??'media') ?>"><?= strtoupper($h($rec['priority']??'MEDIA')) ?></span>
    <span class="rec-area"><?= strtoupper($h($rec['area']??'')) ?></span>
    <div class="rec-body">
      <div class="rec-txt"><?= $h($rec['action']??'') ?></div>
      <?php if(!empty($rec['reason'])): ?><div class="rec-reason">↳ <?= $h($rec['reason']) ?></div><?php endif ?>
    </div>
  </div>
  <?php endforeach ?>
</div>
<?php endif ?>

<?php if(empty($meta_data['ok'])&&empty($google_data['ok'])&&empty($seo_data['ok'])): ?>
<div style="margin:48px;text-align:center;color:#94a3b8;padding:40px">
  <div style="font-size:32px;margin-bottom:12px">⚠</div>
  <p>No hay credenciales configuradas para este cliente.</p>
</div>
<?php endif ?>

<!-- FOOTER -->
<div class="rf">
  <div><div class="brand">DIMARK</div><div style="margin-top:2px">Agencia de Marketing Digital · SuperCerebro</div></div>
  <div style="text-align:right"><div><?= $h($client['name']) ?> · <?= $h($period_label) ?></div><div style="margin-top:2px">Generado el <?= $gen_date ?></div></div>
</div>

</div>
</body>
</html>
<?php
$html=ob_get_clean();

// Guardar en BD
try {
    $title = $client['name'].' — '.$period_label;
    $stmt=$pdo->prepare("INSERT INTO dm_reports (client_id,period_from,period_to,period_label,html,title,created_at) VALUES (?,?,?,?,?,?,NOW()) ON DUPLICATE KEY UPDATE html=VALUES(html),period_label=VALUES(period_label),title=VALUES(title),created_at=NOW()");
    $stmt->execute([$client_id,$date_from,$date_to,$period_label,$html,$title]);
    $report_id = (int)$pdo->lastInsertId();
    if (!$report_id) {
        $rs=$pdo->prepare("SELECT id FROM dm_reports WHERE client_id=? AND period_from=? AND period_to=? LIMIT 1");
        $rs->execute([$client_id,$date_from,$date_to]);
        $report_id=(int)($rs->fetchColumn()?:0);
    }
} catch(Exception $e){ $report_id=0; }

echo json_encode(['ok'=>true,'html'=>$html,'id'=>$report_id,'period'=>$period_label,
    'meta'=>!empty($meta_data['ok']),'google'=>!empty($google_data['ok']),'seo'=>!empty($seo_data['ok'])]);
