yazrkisvs3vvvsv33svrhetrjsvyvsvvyjsvsvs
tavsuysvssvvjvvyjyjkvsvqd
qfogsvvsvsegjdgdfgdskhgdksvqsvshdqsd
<?php
// api/cwv-history.php — Historial de Core Web Vitals por cliente y URL
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth.php';
dm_require_login();

$client_id = (int)($_GET['client_id'] ?? 0);
$url       = trim($_GET['url'] ?? '');
$strategy  = in_array($_GET['strategy'] ?? '', ['mobile','desktop']) ? $_GET['strategy'] : '';

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

try {
    $check = $pdo->query("SHOW TABLES LIKE 'dm_cwv_history'")->fetch();
    if (!$check) { echo json_encode(['ok'=>true,'rows'=>[]]); exit; }

    $sql    = "SELECT checked_at, strategy, performance, lcp, fcp, tbt, cls, inp, ttfb
               FROM dm_cwv_history WHERE client_id = ?";
    $params = [$client_id];

    if ($url)      { $sql .= " AND url = ?";      $params[] = $url; }
    if ($strategy) { $sql .= " AND strategy = ?"; $params[] = $strategy; }

    // ASC order — cronológico para el chart; JS invierte para la tabla
    $sql .= " ORDER BY checked_at ASC LIMIT 60";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['ok'=>true,'rows'=>$rows]);
} catch (Exception $e) {
    echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
