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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Metode tidak diizinkan.']);
    exit;
}

if (!isset($_SESSION['id_user']) && !isset($_SESSION['username'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Anda harus login untuk menyimpan skor.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$final_score = (int)($input['score'] ?? 0);

if ($final_score <= 0) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Skor tidak valid atau 0.']);
    exit;
}

$user_id = null;
if (isset($_SESSION['id_user'])) {
    $user_id = $_SESSION['id_user'];
} elseif (isset($_SESSION['username'])) {

    $username = $_SESSION['username'];

    $getID_sql = "SELECT id_user FROM users WHERE username = '$username'";
    $result_id = mysqli_query($koneksi, $getID_sql);
    
    if ($result_id && mysqli_num_rows($result_id) > 0) {
        $row = mysqli_fetch_assoc($result_id);
        $user_id = $row['id_user'];
    }
}

if (!$user_id) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'ID pengguna tidak ditemukan.']);
    exit;
}

$sql = "UPDATE users SET score = ? WHERE id_user = ? AND score < ?";

if ($stmt = mysqli_prepare($koneksi, $sql)) {
    mysqli_stmt_bind_param($stmt, "iii", $final_score, $user_id, $final_score);
    $exec = mysqli_stmt_execute($stmt);

    if ($exec) {
        $rows_affected = mysqli_stmt_affected_rows($stmt);
        
        if ($rows_affected > 0) {
            $message = 'Skor berhasil diperbarui. Ini adalah Highscore baru!';
        } else {
            $message = 'Skor berhasil dikirim, tetapi skor tidak lebih tinggi dari Highscore sebelumnya.';
        }

        echo json_encode([
            'status' => 'success', 
            'message' => $message,
            'skor_terkirim' => $final_score
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Gagal menjalankan kueri update: ' . mysqli_stmt_error($stmt)]);
    }
    mysqli_stmt_close($stmt);

} else {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Gagal mempersiapkan statement: ' . mysqli_error($koneksi)]);
}
?>