<?php
/**
 * Search Performance API Endpoint
 */

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

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

// Check authorization
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/GoogleSearchConsoleAPI.php';

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

    $days = $_GET['days'] ?? 30;
    $dimensions = $_GET['dimensions'] ?? 'query';

    $result = $gsc->getSearchPerformance($days, [$dimensions]);

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