<?php
/**
 * withdraw_wallets_api.php
 * User-এর Save করা bKash/Nagad Number Save/List করার জন্য।
 * action=list  → Saved Number-এর তালিকা দেয়
 * action=save  → নতুন Number Save করে (আগে থাকলে Update হয়)
 */
include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
header('Content-Type: application/json; charset=utf-8');

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Unauthorized']);
    exit;
}

$userId = intval($data_auth['payload']['id']);
$action = $_GET['action'] ?? '';

if ($action === 'list') {
    $result = $conn->query("SELECT wallet_type, account_number FROM user_withdraw_wallets WHERE user_id = '$userId'");
    $wallets = [];
    while ($row = $result->fetch_assoc()) {
        $wallets[$row['wallet_type']] = $row['account_number'];
    }
    echo json_encode(['code' => 0, 'wallets' => $wallets]);
    exit;
}

if ($action === 'save') {
    $input = json_decode(file_get_contents('php://input'), true);
    $walletType = $input['walletType'] ?? '';
    $accountNumber = trim($input['accountNumber'] ?? '');

    if (!in_array($walletType, ['bKash', 'Nagad']) || !preg_match('/^01[0-9]{9}$/', $accountNumber)) {
        echo json_encode(['code' => 1, 'msg' => 'সঠিক তথ্য দাও']);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO user_withdraw_wallets (user_id, wallet_type, account_number) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE account_number = VALUES(account_number)");
    $stmt->bind_param("iss", $userId, $walletType, $accountNumber);
    $stmt->execute();

    echo json_encode(['code' => 0, 'msg' => 'Save হয়েছে']);
    exit;
}

echo json_encode(['code' => 1, 'msg' => 'Invalid Action']);
