<?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);
    $score = isset($input['score']) ? (int)$input['score'] : 0;
    
    if (!isset($_SESSION['users'])) {
        echo json_encode(['success' => false, 'message' => 'User not logged in']);
        exit;
    }
    
    $username = $_SESSION['users']['username'];
    
    // Update score jika lebih tinggi dari score sebelumnya
    $sql = "UPDATE users SET score = ? WHERE username = ? AND score < ?";
    $stmt = mysqli_prepare($koneksi, $sql);
    
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "isi", $score, $username, $score);
        mysqli_stmt_execute($stmt);
        
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            echo json_encode(['success' => true, 'message' => 'Score updated']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Score not higher than current']);
        }
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database error']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>