<?php
require_once "../../conn.php"; // Points to: mysqli connection
require_once "../../functions2.php"; // Points to: is_jwt_valid function

header('Content-Type: application/json');
$raw_post_data = file_get_contents("php://input");
$post_data = json_decode($raw_post_data, true);
$amount = isset($post_data['amount']) ? floatval($post_data['amount']) : null;

if ($amount === null || $amount <= 0) {
    echo json_encode(["code" => 1, "msg" => "Invalid amount", "error_details" => ["field" => "amount"]]);
    exit();
}

$auth_header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$jwt = explode(" ", $auth_header)[1] ?? '';
$jwt_data = json_decode(is_jwt_valid($jwt), true); // Points to: shonu_subjects (akshinak)
if ($jwt_data['status'] !== 'Success') {
    echo json_encode(["code" => 1, "msg" => "JWT validation failed"]);
    exit();
}

$jwt_safe = mysqli_real_escape_string($conn, $jwt);
$user_query = "SELECT id FROM shonu_subjects WHERE akshinak = '$jwt_safe' LIMIT 1"; // Points to: shonu_subjects
$user_result = mysqli_query($conn, $user_query);
$user = mysqli_fetch_assoc($user_result);
$user_id = mysqli_real_escape_string($conn, $user['id']);

$safe_query = "SELECT SUM(amount) as safe_balance FROM safe_box WHERE user_id = '$user_id'"; // Points to: safe_box
$safe_result = mysqli_query($conn, $safe_query);
$safe_balance = mysqli_fetch_assoc($safe_result)['safe_balance'] ?? 0.00;

if ($safe_balance < $amount) {
    echo json_encode(["code" => 1, "msg" => "Insufficient safe balance"]);
    exit();
}

$main_query = "SELECT motta FROM shonu_kaichila WHERE balakedara = '$user_id' LIMIT 1"; // Points to: shonu_kaichila
$main_result = mysqli_query($conn, $main_query);
$main_balance = mysqli_fetch_assoc($main_result)['motta'] ?? 0.00;

mysqli_begin_transaction($conn);
$new_main_balance = $main_balance + $amount;
$safe_update_query = "INSERT INTO safe_box (user_id, amount, transaction_date) VALUES ('$user_id', '-$amount', NOW())"; // Points to: safe_box
$main_update_query = "UPDATE shonu_kaichila SET motta = '$new_main_balance' WHERE balakedara = '$user_id'"; // Points to: shonu_kaichila

if (mysqli_query($conn, $safe_update_query) && mysqli_query($conn, $main_update_query)) {
    $updated_safe_balance = $safe_balance - $amount;
    mysqli_commit($conn);
    echo json_encode([
        "data" => ["new_main_balance" => $new_main_balance, "new_safe_balance" => $updated_safe_balance, "transferred_amount" => $amount, "transaction_date" => date("Y-m-d H:i:s")],
        "code" => 0,
        "msg" => "Transfer successful",
        "msgCode" => 0,
        "serviceNowTime" => date("Y-m-d H:i:s")
    ]);
} else {
    mysqli_rollback($conn);
    echo json_encode(["code" => 1, "msg" => "Transfer failed"]);
}
mysqli_close($conn);
?>