<?php
/**
 * Top Pages API Endpoint
 */

header('Content-Type: application/json');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../../helpers/seo_analytics/GoogleAnalytics4API.php';

try {
    $config = include __DIR__ . '/../../helpers/seo_analytics/config.php';
    $ga4 = new GoogleAnalytics4API($config);

    $days = $_GET['days'] ?? 30;
    $result = $ga4->getTopPages($days);

    echo json_encode($result);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>
