<?php
header('Content-Type: application/json');
require 'db.php'; // Include your database connection script

$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($user_id > 0) {
    $sql_check = "SELECT COUNT(*) AS count FROM wallets WHERE user_id = $user_id";
    $result_check = $conn->query($sql_check);

    if ($result_check) {
        $row_check = $result_check->fetch_assoc();
        $count = $row_check['count'];

        if ($count == 0) {
            // Create the wallet if it does not exist
            $sql = "INSERT INTO wallets (user_id, balance) VALUES ($user_id, 0)";
            if ($conn->query($sql) === TRUE) {
                echo json_encode(['success' => true, 'message' => 'Wallet created successfully']);
            } else {
                echo json_encode(['error' => 'Failed to create wallet']);
            }
        } else {
            echo json_encode(['error' => 'Wallet already exists']);
        }
    } else {
        echo json_encode(['error' => 'Failed to execute check query']);
    }
} else {
    echo json_encode(['error' => 'Invalid user ID']);
}

$conn->close();
?>
