<?php
// api/pagespeed.php — Core Web Vitals via Google PageSpeed Insights API v5
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
dm_require_login();
dm_csrf_verify();

$input    = json_decode(file_get_contents('php://input'), true);
$url      = trim($input['url'] ?? '');
$strategy = ($input['strategy'] ?? 'mobile') === 'desktop' ? 'desktop' : 'mobile';
$client_id = (int)($input['client_id'] ?? 0);

if (!$url) { echo json_encode(['ok'=>false,'error'=>'URL requerida']); exit; }
if (!preg_match('#^https?://#i', $url)) $url = 'https://' . $url;
if (!filter_var($url, FILTER_VALIDATE_URL)) { echo json_encode(['ok'=>false,'error'=>'URL inválida']); exit; }

$api_key = defined('PAGESPEED_API_KEY') ? PAGESPEED_API_KEY : '';
$api_url = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url='
         . urlencode($url) . '&strategy=' . $strategy . '&category=performance'
         . ($api_key ? '&key=' . urlencode($api_key) : '');

$ch = curl_init($api_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 40,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER     => ['Accept: application/json'],
]);
$raw  = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($code !== 200) {
    $err = json_decode($raw, true);
    $msg = $err['error']['message'] ?? 'Error API PageSpeed (HTTP ' . $code . ')';
    echo json_encode(['ok'=>false,'error'=>$msg]); exit;
}

$data    = json_decode($raw, true);
$lr      = $data['lighthouseResult']    ?? [];
$audits  = $lr['audits']               ?? [];
$cats    = $lr['categories']           ?? [];
$le      = $data['loadingExperience']  ?? []; // Field data (CrUX)
$ole     = $data['originLoadingExperience'] ?? []; // Origin field data

function ps_metric(array $audits, string $key): array {
    $a = $audits[$key] ?? [];
    return [
        'display' => $a['displayValue'] ?? '—',
        'score'   => $a['score']        ?? null,
        'value'   => $a['numericValue'] ?? null,
    ];
}

function ps_field(array $le, string $key): ?array {
    $m = $le['metrics'][$key] ?? null;
    if (!$m) return null;
    $cat = $m['category'] ?? '';
    $p75 = $m['percentile'] ?? null;
    return ['category'=>$cat, 'p75'=>$p75];
}

function ps_score_label(float $score): string {
    if ($score >= 0.9) return 'good';
    if ($score >= 0.5) return 'needs-improvement';
    return 'poor';
}

$performance = (int)round(($cats['performance']['score'] ?? 0) * 100);

// Lab metrics (Lighthouse)
$lcp  = ps_metric($audits, 'largest-contentful-paint');
$fcp  = ps_metric($audits, 'first-contentful-paint');
$tbt  = ps_metric($audits, 'total-blocking-time');
$cls  = ps_metric($audits, 'cumulative-layout-shift');
$si   = ps_metric($audits, 'speed-index');
$tti  = ps_metric($audits, 'interactive');
$inp  = ps_metric($audits, 'interaction-to-next-paint');
$ttfb = ps_metric($audits, 'server-response-time');

// Field data (CrUX — datos reales de usuarios)
$field = [
    'lcp' => ps_field($le, 'LARGEST_CONTENTFUL_PAINT_MS'),
    'fid' => ps_field($le, 'FIRST_INPUT_DELAY_MS'),
    'cls' => ps_field($le, 'CUMULATIVE_LAYOUT_SHIFT_SCORE'),
    'inp' => ps_field($le, 'INTERACTION_TO_NEXT_PAINT'),
    'fcp' => ps_field($le, 'FIRST_CONTENTFUL_PAINT_MS'),
    'ttfb'=> ps_field($le, 'EXPERIMENTAL_TIME_TO_FIRST_BYTE'),
    'overall' => $le['overall_category'] ?? null,
];

// Oportunidades de mejora (top 8)
$opps = [];
foreach ($audits as $audit) {
    if (isset($audit['details']['type']) && $audit['details']['type'] === 'opportunity'
        && ($audit['score'] ?? 1) < 0.9 && !empty($audit['title'])) {
        $opps[] = [
            'title'   => $audit['title'],
            'desc'    => $audit['description'] ?? '',
            'savings' => $audit['displayValue'] ?? '',
            'score'   => $audit['score'] ?? null,
        ];
    }
}
usort($opps, fn($a,$b) => ($a['score']??1) <=> ($b['score']??1));
$opps = array_slice($opps, 0, 8);

// Diagnósticos (issues adicionales)
$diags = [];
$diag_keys = ['render-blocking-resources','unused-css-rules','unused-javascript','uses-optimized-images','uses-webp-images','efficient-animated-content','uses-text-compression'];
foreach ($diag_keys as $k) {
    $a = $audits[$k] ?? null;
    if ($a && ($a['score'] ?? 1) < 0.9) {
        $diags[] = ['title'=>$a['title']??$k, 'display'=>$a['displayValue']??'', 'score'=>$a['score']??null];
    }
}

$result = [
    'url'         => $url,
    'strategy'    => $strategy,
    'performance' => $performance,
    'score_label' => ps_score_label(($cats['performance']['score'] ?? 0)),
    // Lab metrics
    'lcp'  => $lcp,
    'fcp'  => $fcp,
    'tbt'  => $tbt,
    'cls'  => $cls,
    'si'   => $si,
    'tti'  => $tti,
    'inp'  => $inp,
    'ttfb' => $ttfb,
    // Field data
    'field'        => $field,
    'opportunities'=> $opps,
    'diagnostics'  => $diags,
];

// Guardar historial en DB
if ($client_id) {
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS dm_cwv_history (
            id INT AUTO_INCREMENT PRIMARY KEY,
            client_id INT NOT NULL,
            url VARCHAR(512) NOT NULL,
            strategy VARCHAR(10) NOT NULL DEFAULT 'mobile',
            performance INT,
            lcp FLOAT, fcp FLOAT, tbt FLOAT, cls FLOAT, inp FLOAT, ttfb FLOAT,
            checked_at DATETIME NOT NULL,
            INDEX idx_client (client_id),
            INDEX idx_date (checked_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        $pdo->prepare("INSERT INTO dm_cwv_history (client_id,url,strategy,performance,lcp,fcp,tbt,cls,inp,ttfb,checked_at)
            VALUES (?,?,?,?,?,?,?,?,?,?,NOW())")
            ->execute([$client_id,$url,$strategy,$performance,
                $lcp['value'],$fcp['value'],$tbt['value'],$cls['value'],
                $inp['value']??null,$ttfb['value']??null]);
        // Mantener 90 registros por cliente+url+strategy
        $pdo->prepare("DELETE FROM dm_cwv_history WHERE client_id=? AND url=? AND strategy=? AND id NOT IN (
            SELECT id FROM (SELECT id FROM dm_cwv_history WHERE client_id=? AND url=? AND strategy=? ORDER BY checked_at DESC LIMIT 90) t
        )")->execute([$client_id,$url,$strategy,$client_id,$url,$strategy]);
    } catch (Exception $e) {}
}

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