<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$servername = "localhost";  // Change this if needed
$username = "aabcxrbr_ss";         // Your DB username
$password = "aabcxrbr_ss";             // Your DB password
$dbname = "aabcxrbr_ss";  // Your database name

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Database connection failed"]));
}

// Get request data
$request_body = file_get_contents("php://input");
$data = json_decode($request_body, true);

if (!isset($data['user_id'], $data['amount'])) {
    echo json_encode(["status" => "error", "message" => "Invalid request data"]);
    exit;
}

$user_id = $data['user_id'];
$amount = $data['amount'];

// Get current balance
$sql_balance = "SELECT balance FROM motto WHERE user_id = ?";
$stmt = $conn->prepare($sql_balance);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    echo json_encode(["status" => "error", "message" => "User not found"]);
    exit;
}

$current_balance = $row['balance'];

// Check if user has enough balance
if ($current_balance < $amount) {
    echo json_encode(["status" => "error", "message" => "Insufficient balance"]);
    exit;
}

// Deduct amount from motto table
$sql_update = "UPDATE motto SET balance = balance - ? WHERE user_id = ?";
$stmt = $conn->prepare($sql_update);
$stmt->bind_param("di", $amount, $user_id);
$stmt->execute();

// Insert into safe history
$sql_insert = "INSERT INTO safe_history (user_id, amount) VALUES (?, ?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bind_param("id", $user_id, $amount);
$stmt->execute();

// Response
$response = [
    "status" => "success",
    "message" => "Safe successful",
    "new_balance" => $current_balance - $amount
];

echo json_encode($response);
$conn->close();
?>