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

require_once 'config.php';

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

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

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

requireRole('Admin');

try {
    $data = json_decode(file_get_contents('php://input'), true);
    $targetNasional = isset($data['target_nasional']) ? (float)$data['target_nasional'] : null;
    $populationReference = isset($data['population_reference']) ? (int)$data['population_reference'] : null;

    if ($targetNasional === null || $targetNasional < 0 || $targetNasional > 100) {
        http_response_code(400);
        die(json_encode(['error' => 'Target nasional must be between 0 and 100']));
    }

    if ($populationReference === null || $populationReference < 1) {
        http_response_code(400);
        die(json_encode(['error' => 'Population reference must be greater than 0']));
    }

    $db = getDB();
    $stmt = $db->prepare('INSERT INTO score_metadata (key_name, key_value, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE key_value = VALUES(key_value), updated_at = CURRENT_TIMESTAMP');
    $stmt->execute(['target_nasional', number_format($targetNasional, 2, '.', '')]);
    $stmt->execute(['population_reference', (string)$populationReference]);

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