<?php
error_reporting(0);
header('Content-Type: application/json');
require_once '../config/db.php';

// Data handle karne ka sabse solid tarika
$data = $_POST;
if (empty($data)) {
    parse_str(file_get_contents('php://input'), $data);
}

$old_wallet = $data['old_wallet'] ?? null;
$new_wallet = $data['wallet'] ?? null;
$name = $data['name'] ?? null;
$email = $data['email'] ?? null;
$mobile = $data['mobile'] ?? null;

if (!$old_wallet || !$new_wallet) {
    echo json_encode(["success" => false, "message" => "Critical Error: Wallet IDs missing at server side."]);
    exit;
}

mysqli_begin_transaction($conn);
try {
    // 1. Users table update
    $u_sql = "UPDATE users SET wallet='$new_wallet', name='$name', email='$email', mobile='$mobile' WHERE wallet='$old_wallet'";
    mysqli_query($conn, $u_sql);
    
    // 2. Deposits sync
    mysqli_query($conn, "UPDATE deposits SET wallet='$new_wallet' WHERE wallet='$old_wallet'");
    
    // 3. Withdrawals sync
    mysqli_query($conn, "UPDATE withdrawals SET wallet='$new_wallet' WHERE wallet='$old_wallet'");

    mysqli_commit($conn);
    echo json_encode(["success" => true]);
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(["success" => false, "message" => "DB Error: " . mysqli_error($conn)]);
}
exit;
?>