<?php
// save_player_id.php

header('Content-Type: application/json; charset=utf-8');

include 'db_connect.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $playerId = isset($_POST['player_id']) ? $_POST['player_id'] : null;

    if ($userId > 0 && $playerId != null) {
        if (isset($conn) && $conn) {
            $stmt = $conn->prepare("UPDATE users SET onesignal_player_id = ? WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("si", $playerId, $userId);
                if ($stmt->execute()) {
                    $response['status'] = 'success';
                    $response['message'] = 'Player ID updated successfully.';
                } else {
                    $response['status'] = 'error';
                    $response['message'] = 'Failed to execute statement: ' . $stmt->error;
                }
                $stmt->close();
            } else {
                $response['status'] = 'error';
                $response['message'] = 'Failed to prepare statement: ' . $conn->error;
            }
        } else {
            $response['status'] = 'error';
            $response['message'] = 'Database connection failed.';
        }
    } else {
        $response['status'] = 'error';
        $response['message'] = 'User ID and Player ID are required.';
    }
} else {
    $response['status'] = 'error';
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);

if (isset($conn)) {
    $conn->close();
}
?>
