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

require_once 'config.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

try {
    $db = getDB();

    $stmt = $db->prepare('SELECT key_value FROM score_metadata WHERE key_name = ? LIMIT 1');
    $stmt->execute(['target_nasional']);
    $targetNasional = $stmt->fetchColumn();

    $stmt->execute(['population_reference']);
    $populationReference = $stmt->fetchColumn();

    if ($targetNasional === false || $targetNasional === null || $targetNasional === '') {
        $targetNasional = '7.50';
    }

    if ($populationReference === false || $populationReference === null || $populationReference === '') {
        $populationReference = '288315899';
    }

    echo json_encode([
        'success' => true,
        'configuration' => [
            'target_nasional' => (float)$targetNasional,
            'population_reference' => (int)$populationReference
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>