<?php
session_start(); // Mulai session
header('Content-Type: application/json'); 
require 'Connection.php'; // Koneksi DB

// Cek Login
if (!isset($_SESSION['username']) || !isset($_SESSION['user_id'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Not logged in"
    ]);
    exit;
}

// Ambil Data
$username = $_SESSION['username']; // Username dari session
$user_id  = $_SESSION['user_id'];  // User ID dari session
$score    = intval($_POST['score'] ?? 0); // Score dari client

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

// Cek Data Leaderboard
$checkStmt = $conn->prepare(
    "SELECT score FROM leaderboard WHERE user_id = ?"
); // Cek berdasarkan user_id
$checkStmt->bind_param("i", $user_id);
$checkStmt->execute();
$result = $checkStmt->get_result();

// Jika sudah ada score
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $oldScore = $row['score'];

    if ($score > $oldScore) {

        // Update jika score lebih tinggi
        $updateStmt = $conn->prepare(
            "UPDATE leaderboard SET score = ?, username = ? WHERE user_id = ?"
        );
        $updateStmt->bind_param("isi", $score, $username, $user_id);

        if ($updateStmt->execute()) {
            echo json_encode([
                "status" => "success",
                "message" => "New high score saved",
                "newHighScore" => true
            ]);
        } else {
            echo json_encode([
                "status" => "error",
                "message" => "Failed to update score"
            ]);
        }
        $updateStmt->close();

    } else {

        // Score lebih rendah dari record lama
        echo json_encode([
            "status" => "success",
            "message" => "Score not higher than previous",
            "newHighScore" => false
        ]);
    }

} else {

    // Jika Belum Ada 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" => "First score saved",
            "newHighScore" => true
        ]);
    } else {
        echo json_encode([
            "status" => "error",
            "message" => "Failed to save score"
        ]);
    }
    $insertStmt->close();
}

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