<?php
// api/sitemap.php — Análisis y gestión de sitemaps por cliente
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../credentials.php';
require_once __DIR__ . '/google-auth.php';
dm_require_login();

$action    = $_GET['action'] ?? 'list';
$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);

$creds  = dm_get_credentials($client_id, 'gsc');
$domain = $creds['domain'] ?? '';

if (!$domain) { echo json_encode(['ok'=>false,'error'=>'Configura el dominio GSC del cliente']); exit; }

// Normalizar dominio
if (!str_starts_with($domain, 'sc-domain:') && !str_starts_with($domain, 'https://') && !str_starts_with($domain, 'http://')) {
    $domain_url = 'https://' . $domain . '/';
} elseif (str_starts_with($domain, 'https://') && !str_ends_with($domain, '/')) {
    $domain_url = $domain . '/';
} else {
    $domain_url = $domain;
}
$base_url = rtrim(preg_replace('#^sc-domain:#', 'https://', $domain_url), '/');

switch ($action) {

    case 'list':
        // Sitemaps registrados en GSC
        $token = dm_google_access_token('https://www.googleapis.com/auth/webmasters.readonly');
        if (!$token) { echo json_encode(['ok'=>false,'error'=>'No hay token Google']); exit; }
        $ch = curl_init('https://searchconsole.googleapis.com/webmasters/v3/sites/' . urlencode($domain_url) . '/sitemaps');
        curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$token],CURLOPT_TIMEOUT=>15,CURLOPT_SSL_VERIFYPEER=>true]);
        $raw  = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $data = json_decode($raw, true);
        if ($code !== 200) { echo json_encode(['ok'=>false,'error'=>$data['error']['message']??'Error GSC HTTP '.$code]); exit; }
        $sitemaps = [];
        foreach ($data['sitemap'] ?? [] as $sm) {
            $sitemaps[] = [
                'path'      => $sm['path'] ?? '',
                'type'      => $sm['type'] ?? 'sitemap',
                'indexed'   => (int)($sm['contents'][0]['indexed'] ?? 0),
                'submitted' => (int)($sm['contents'][0]['submitted'] ?? 0),
                'warnings'  => count($sm['warnings'] ?? []),
                'errors'    => count($sm['errors'] ?? []),
                'last_dl'   => substr($sm['lastDownloaded'] ?? '', 0, 10),
                'pending'   => (bool)($sm['isPending'] ?? false),
            ];
        }
        echo json_encode(['ok'=>true,'sitemaps'=>$sitemaps,'domain'=>$domain_url]);
        break;

    case 'fetch':
        // Descargar y parsear sitemap.xml
        $sitemap_url = $base_url . '/sitemap.xml';
        $ch = curl_init($sitemap_url);
        curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>20,CURLOPT_FOLLOWLOCATION=>true,CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,CURLOPT_USERAGENT=>'SuperCerebro-Bot/1.0']);
        $raw  = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($code !== 200 || !$raw) { echo json_encode(['ok'=>false,'error'=>"No se encontró sitemap.xml en $sitemap_url (HTTP $code)"]); exit; }
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($raw);
        if (!$xml) { echo json_encode(['ok'=>false,'error'=>'Sitemap XML inválido o no parseable']); exit; }
        $urls = [];
        $is_index = $xml->getName() === 'sitemapindex';
        if ($is_index) {
            foreach ($xml->sitemap as $sm) {
                $urls[] = ['url'=>(string)($sm->loc??''),'type'=>'sitemap','lastmod'=>substr((string)($sm->lastmod??''),0,10)];
            }
        } else {
            foreach ($xml->url as $u) {
                $loc = (string)($u->loc ?? '');
                if (!$loc) continue;
                $urls[] = ['url'=>$loc,'lastmod'=>substr((string)($u->lastmod??''),0,10),'priority'=>(float)($u->priority??0.5),'changefreq'=>(string)($u->changefreq??'')];
            }
        }
        echo json_encode(['ok'=>true,'sitemap_url'=>$sitemap_url,'is_index'=>$is_index,'count'=>count($urls),'urls'=>array_slice($urls,0,200)]);
        break;

    case 'submit':
        // Enviar sitemap a Google Search Console — detecta sitemap_index.xml automáticamente
        $token = dm_google_access_token('https://www.googleapis.com/auth/webmasters');
        if (!$token) { echo json_encode(['ok'=>false,'error'=>'No hay token Google']); exit; }
        // Detectar URL real del sitemap (puede ser sitemap.xml → sitemap_index.xml)
        $sm_test = $base_url . '/sitemap.xml';
        $ch_test = curl_init($sm_test);
        curl_setopt_array($ch_test,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>10,CURLOPT_FOLLOWLOCATION=>true,CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,CURLOPT_USERAGENT=>'SuperCerebro-Bot/1.0']);
        curl_exec($ch_test);
        $effective_url = curl_getinfo($ch_test, CURLINFO_EFFECTIVE_URL);
        curl_close($ch_test);
        $sitemap_url = $effective_url ?: $sm_test;
        $submit_url  = 'https://searchconsole.googleapis.com/webmasters/v3/sites/' . urlencode($domain_url) . '/sitemaps/' . urlencode($sitemap_url);
        $ch = curl_init($submit_url);
        curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_CUSTOMREQUEST=>'PUT',CURLOPT_HTTPHEADER=>['Authorization: Bearer '.$token,'Content-Length: 0'],CURLOPT_TIMEOUT=>15,CURLOPT_SSL_VERIFYPEER=>true]);
        $raw  = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($code >= 200 && $code < 300) {
            echo json_encode(['ok'=>true,'message'=>"Sitemap enviado: $sitemap_url"]);
        } else {
            $err = json_decode($raw,true);
            echo json_encode(['ok'=>false,'error'=>$err['error']['message']??'Error enviando sitemap (HTTP '.$code.')']);
        }
        break;
}
