<?php
session_start();
require_once "koneksi.php";

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (isset($input['score']) && isset($_SESSION['users'])) {
        $score = (int)$input['score'];
        $username = $_SESSION['users']['username'];
        
        $sql = "UPDATE users SET score = $score WHERE username = '$username' AND score < $score";
        $result = mysqli_query($koneksi, $sql);
        
        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Score saved', 'score' => $score]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid data']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
}
?>