<?php
require_once __DIR__ . '/config.php';

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $range1 = intval($data['range_0_1_5']);
    $range2 = intval($data['range_1_5_3']);
    $range3 = intval($data['range_3_6']);
    $range4 = intval($data['range_6_15']);
    
    // Validate total is 100%
    $total = $range1 + $range2 + $range3 + $range4;
    if ($total !== 100) {
        echo json_encode([
            'success' => false,
            'message' => 'A soma das probabilidades deve ser exatamente 100%'
        ]);
        exit;
    }
    
    // Update or insert
    $stmt = $pdo->query("SELECT COUNT(*) FROM game_probabilities");
    $count = $stmt->fetchColumn();
    
    if ($count > 0) {
        $stmt = $pdo->prepare("
            UPDATE game_probabilities 
            SET range_0_1_5 = ?, 
                range_1_5_3 = ?, 
                range_3_6 = ?, 
                range_6_15 = ?,
                updated_at = NOW()
            WHERE id = (SELECT id FROM (SELECT id FROM game_probabilities ORDER BY id DESC LIMIT 1) as tmp)
        ");
        $stmt->execute([$range1, $range2, $range3, $range4]);
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO game_probabilities (range_0_1_5, range_1_5_3, range_3_6, range_6_15) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$range1, $range2, $range3, $range4]);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Probabilidades salvas com sucesso'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao salvar probabilidades: ' . $e->getMessage()
    ]);
}
