<?php
session_start();
header('Content-Type: application/json');
require 'Connection.php'; // Gunakan require agar stop jika file tidak ada

// 1. Pastikan user login & user_id tersedia
if (!isset($_SESSION['username']) || !isset($_SESSION['user_id'])) {
    echo json_encode(["status" => "error", "message" => "Belum login atau sesi tidak valid"]);
    exit;
}

$username = $_SESSION['username'];
$user_id = $_SESSION['user_id']; // AMBIL ID DARI SESSION
$score = intval($_POST['score'] ?? 0);

// Validasi score
if ($score <= 0) {
    echo json_encode(["status" => "error", "message" => "Skor tidak valid"]);
    exit;
}

// Cek apakah user sudah punya record di leaderboard
$checkStmt = $conn->prepare("SELECT score FROM leaderboard WHERE user_id = ?");
$checkStmt->bind_param("i", $user_id); // Cek berdasarkan ID, lebih akurat daripada username
$checkStmt->execute();
$result = $checkStmt->get_result();

if ($result->num_rows > 0) {
    // --- UPDATE ---
    $row = $result->fetch_assoc();
    $oldScore = $row['score'];
    
    if ($score > $oldScore) {
        // Update score berdasarkan user_id
        $updateStmt = $conn->prepare("UPDATE leaderboard SET score = ?, username = ? WHERE user_id = ?");
        // Kita update username juga untuk jaga-jaga kalau user ganti nama
        $updateStmt->bind_param("isi", $score, $username, $user_id);
        
        if ($updateStmt->execute()) {
            echo json_encode([
                "status" => "success", 
                "message" => "High Score baru tercatat!",
                "newHighScore" => true
            ]);
        } else {
            echo json_encode(["status" => "error", "message" => "Gagal update database"]);
        }
        $updateStmt->close();
    } else {
        echo json_encode([
            "status" => "success", 
            "message" => "Skor lebih rendah dari rekor sebelumnya.",
            "newHighScore" => false
        ]);
    }
} else {
    // --- INSERT BARU ---
    // Masukkan user_id, username, dan score
    $insertStmt = $conn->prepare("INSERT INTO leaderboard (user_id, username, score) VALUES (?, ?, ?)");
    $insertStmt->bind_param("isi", $user_id, $username, $score);
    
    if ($insertStmt->execute()) {
        echo json_encode([
            "status" => "success", 
            "message" => "Skor pertama berhasil disimpan!",
            "newHighScore" => true
        ]);
    } else {
        echo json_encode(["status" => "error", "message" => "Gagal insert database"]);
    }
    $insertStmt->close();
}

$checkStmt->close();
$conn->close();
?>