<?php
require_once '../includes/config.php';
require_once '../includes/commission.php';
require_once '../includes/dingconnect.php';
require_once '../includes/telegram.php';
requireLogin();

$input   = json_decode(file_get_contents('php://input'), true);
$phone   = sanitize($input['phone']    ?? '');
$country = sanitize($input['country']  ?? '');
$sku     = sanitize($input['sku_code'] ?? '');
$amount  = floatval($input['amount']   ?? 0);
$currency= sanitize($input['currency'] ?? 'USD');

if (!$phone || !$country || !$sku || $amount <= 0) {
    jsonResponse(false, 'সব তথ্য দিন!');
}

$user = getCurrentUser();
$db   = getDB();

// ── Build phone with correct country dial code ──
$dialCode = '';
try {
    $s = $db->prepare("SELECT dial_code FROM intl_countries WHERE iso=? LIMIT 1");
    $s->execute([$country]);
    $dialCode = preg_replace('/[^0-9]/', '', $s->fetchColumn() ?: '');
} catch(Exception $e) {}

// Clean — digits only, remove leading zeros
$phoneDigits = preg_replace('/[^0-9]/', '', $phone);
$phoneDigits = ltrim($phoneDigits, '0');

// Add dial code if not already present
if ($dialCode && substr($phoneDigits, 0, strlen($dialCode)) !== $dialCode) {
    $phoneDigits = $dialCode . $phoneDigits;
}

$bdtAmount      = usdToBdt($amount);
$balance_before = $user['balance'];
$balance_after  = $balance_before - $bdtAmount;

if ($user['balance'] < $bdtAmount) {
    jsonResponse(false, 'অপর্যাপ্ত ব্যালেন্স! আপনার ব্যালেন্স: ৳' . number_format($user['balance'],2));
}

$ref       = 'INT' . strtoupper(substr(md5(uniqid()), 0, 8));
$ding_mode = getSetting('ding_mode') ?: 'manual';

$db->beginTransaction();
try {
    $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$bdtAmount, $user['id']]);

    $status       = 'pending';
    $api_response = null;
    $note         = 'International: '.$country.' | '.$sku;

    if ($ding_mode === 'auto' && dingIsConfigured()) {

        // Only try without + prefix
        $formatsToTry = [$phoneDigits];
        $formattedPhone = $phoneDigits;
        $validateOk     = false;
        $lastValidate   = [];

        foreach ($formatsToTry as $tryPhone) {
            $v = dingSendTransfer($tryPhone, $sku, $amount, $ref.'_V', true);
            if (isset($v['ResultCode']) && $v['ResultCode'] == 1) {
                $formattedPhone = $tryPhone;
                $validateOk     = true;
                break;
            }
            $lastValidate = $v;
        }

        if ($validateOk) {
            $api_response = dingSendTransfer($formattedPhone, $sku, $amount, $ref);
            $rc = $api_response['ResultCode'] ?? -1;
            if ($rc == 1) {
                $status = 'success';
                $note   = 'DingConnect ✅ | '.$country.' | Phone: '.$formattedPhone;
            } else {
                $errCode = $api_response['ErrorCodes'][0]['Code']    ?? 'Unknown';
                $errCtx  = $api_response['ErrorCodes'][0]['Context'] ?? '';
                $note    = 'DingConnect Error: '.$errCode.' | '.$errCtx.' | Pending admin';
                $status  = 'pending';
            }
        } else {
            $vErr = $lastValidate['ErrorCodes'][0]['Code']    ?? 'ValidationFailed';
            $vCtx = $lastValidate['ErrorCodes'][0]['Context'] ?? '';
            $note = 'DingConnect Validation Failed: '.$vErr.' | '.$vCtx.' | Pending admin';
            $status = 'pending';
            $api_response = $lastValidate;
        }
    }

    // Save transaction
    $db->prepare("INSERT INTO transactions
        (user_id, type, amount, charge, net_amount, balance_before, balance_after,
         phone_number, reference, status, note, api_response)
        VALUES (?, 'international', ?, 0, ?, ?, ?, ?, ?, ?, ?, ?)")
       ->execute([
           $user['id'], $bdtAmount, $bdtAmount,
           $balance_before, $balance_after,
           $phoneDigits, $ref, $status, $note,
           $api_response ? json_encode($api_response) : null
       ]);

    if ($status === 'success') {
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$user['id'], '✅ International Recharge Successful!',
               $phoneDigits.' recharge completed. Ref: '.$ref]);
        applyCommission($db, $user['id'], 'international', $bdtAmount, $ref);
    }

    $db->prepare("INSERT INTO notifications (title,message,type,is_global) VALUES (?,?,'info',0)")
       ->execute(['🌍 New International Recharge', $user['name'].' → '.$phoneDigits.' ('.$country.') ৳'.$bdtAmount]);

    $db->commit();

    jsonResponse(true, $status === 'success' ? 'Recharge successful!' : 'Recharge request submitted!', [
        'status'    => $status,
        'reference' => $ref,
        'phone'     => $phoneDigits,
        'amount'    => $bdtAmount,
        'api_resp'  => $api_response,
    ]);

} catch(Exception $e) {
    $db->rollBack();
    jsonResponse(false, 'Error: '.$e->getMessage().' | Line: '.$e->getLine().' | File: '.basename($e->getFile()));
}
