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

$input       = json_decode(file_get_contents('php://input'), true);
$phone       = preg_replace('/[^0-9]/', '', $input['phone'] ?? '');
$operator_id = intval($input['operator_id'] ?? 0);
$package_id  = intval($input['package_id'] ?? 0);
$amount      = floatval($input['amount'] ?? 0);

if (!$phone || !$operator_id || $amount <= 0) jsonResponse(false, 'সব তথ্য সঠিকভাবে দিন!');
if (strlen($phone) !== 11) jsonResponse(false, 'সঠিক ফোন নম্বর দিন! (১১ ডিজিট)');

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

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

$op = $db->prepare("SELECT * FROM operators WHERE id=? AND status='active'");
$op->execute([$operator_id]);
$operator = $op->fetch();
if (!$operator) jsonResponse(false, 'অপারেটর পাওয়া যায়নি!');

$ref            = generateRef();
$balance_before = $user['balance'];
$balance_after  = $balance_before - $amount;
$api_key        = getSetting('successtopup_key');
$api_secret     = getSetting('successtopup_secret');

$db->beginTransaction();
try {
    // ব্যালেন্স কেটে রাখো
    $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$amount, $user['id']]);

    $status       = 'pending';
    $note         = 'Awaiting admin approval';
    $api_response = null;

    // Per-operator API selection (new system)
    $op_api = getSetting('op_api_'.$operator['id']) ?: 'manual';

    if ($op_api === 'successtopup') {
        $apiResp      = successTopupRecharge($phone, $amount, $operator['code'], $ref);
        $api_response = $apiResp;

        if (!empty($apiResp['result']) && ($apiResp['result'] == 1 || $apiResp['result'] === true)) {
            // ST result:1 = request accepted, NOT final success
            // Must wait for status check via cron
            $status       = 'pending';
            $trxid        = $apiResp['trxid'] ?? $apiResp['TRXID'] ?? '';
            $note         = 'ST_PENDING';
            $need_polling = true;
        } elseif (isset($apiResp['status']) && strtolower($apiResp['status']) === 'processing') {
            $status       = 'pending';
            $note         = 'ST_PENDING';
            $need_polling = true;
        } else {
            $status = 'pending';
            $note   = 'ST_PENDING';
        }

    } elseif ($op_api === 'ecare') {
        try {
            $ecareRef = $ref . substr(str_replace('.','',microtime(true)), -4);
            $apiResp  = ecareRecharge($phone, $amount, $operator['code']??'GP', 'prepaid', $ecareRef);
            $api_response = array_merge($apiResp['raw'] ?? [], ['ecare_ref' => $ecareRef]);

            if ($apiResp['received']) {
                $status       = 'pending';
                $note         = 'TrxID: '.($apiResp['trxid']??'');
                $need_polling = true;
                $ecare_received = true;
                $ecare_ref    = $ecareRef;
                $ecare_trxid  = $apiResp['trxid'] ?? '';
            } elseif ($apiResp['result']) {
                $status = 'success';
                $note   = 'TrxID: '.($apiResp['trxid']??'');
            } else {
                $status = 'pending';
                $note   = '';
            }
        } catch (Exception $ecareEx) {
            $status = 'pending';
            $note   = '';
            $api_response = ['error' => $ecareEx->getMessage()];
        }

    } elseif ($op_api !== 'manual' && $op_api !== 'ecare' && $op_api !== 'successtopup' && !empty($op_api)) {
        // Custom/Dynamic API — by slug or id
        try {
            require_once '../includes/custom_api.php';
            // Get operator map
            if(is_numeric($op_api)) {
                $apiRow = $db->prepare("SELECT operator_map FROM custom_apis WHERE id=? AND is_active=1");
            } else {
                $apiRow = $db->prepare("SELECT operator_map FROM custom_apis WHERE slug=? AND is_active=1");
            }
            $apiRow->execute([$op_api]); $apiRowData = $apiRow->fetch();
            $opMap    = json_decode($apiRowData['operator_map']??'{}',true)?:[];
            $mappedOp = $opMap[strtoupper($operator['code']??'')] ?? $operator['code'];
            $apiResp  = customApiCall($op_api, 'recharge', [
                'phone'    => $phone, 'amount' => $amount,
                'operator' => $mappedOp, 'trxid' => $ref, 'type' => 'prepaid',
            ]);
            $api_response = $apiResp['raw'] ?? $apiResp;
            if(!empty($apiResp['ok'])) {
                $status = 'success';
                $note   = '✅ '.$op_api.' Success | TrxID: '.($apiResp['trxid']??'');
            } else {
                $status = 'pending';
                $note   = '❌ '.$op_api.': '.($apiResp['message']??'Failed');
            }
        } catch(Exception $e) {
            $status = 'pending';
            $note   = '❌ Custom API Error: '.$e->getMessage();
            $api_response = ['error' => $e->getMessage()];
        }

    } else {
        // Manual
        $status = 'pending';
        $note   = '🖐 Manual mode — Awaiting admin approval';
    }

    // Transaction save
    $stmt = $db->prepare("INSERT INTO transactions
        (user_id, type, amount, charge, net_amount, balance_before, balance_after,
         operator_id, package_id, phone_number, reference, status, note, api_response)
        VALUES (?, 'topup', ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $user['id'], $amount, $amount,
        $balance_before,
        $balance_after,
        $operator_id, $package_id ?: null, $phone, $ref,
        $status, $note,
        $api_response ? json_encode(array_merge((array)$api_response, isset($ecare_ref)?['ecare_ref'=>$ecare_ref]:[])) : null
    ]);

    // Notification to user
    if ($status === 'success') {
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$user['id'], '✅ রিচার্জ সফল!',
               $phone . ' নম্বরে ' . CURRENCY . number_format($amount,2) . ' রিচার্জ সম্পন্ন হয়েছে। Ref: ' . $ref]);
        notifyUser($user['id'], 'রিচার্জ সফল! 📱', ['📱 নম্বর'=>$phone, '💰 পরিমাণ'=>CURRENCY.number_format($amount,2), '🔖 Ref'=>$ref]);
    }

    // Admin notification
    $adminMsg = $status === 'success'
        ? $user['name'].' → '.$phone.' | ৳'.number_format($amount,2).' [AUTO SUCCESS ✅]'
        : $user['name'].' → '.$phone.' | ৳'.number_format($amount,2).' [PENDING - API Failed]';

    $db->prepare("INSERT INTO notifications (title,message,type,is_global) VALUES (?,?,'info',0)")
       ->execute([$status === 'success' ? '✅ Auto Recharge Success' : '⏳ নতুন রিচার্জ রিকোয়েস্ট', $adminMsg]);

    $db->commit();

    // Background status checker — for ECARE received and ST pending
    if (!empty($need_polling)) {
        $txnRow = $db->prepare("SELECT id FROM transactions WHERE reference=? AND user_id=? LIMIT 1");
        $txnRow->execute([$ref, $user['id']]);
        $txnId = $txnRow->fetchColumn();
        if ($txnId && function_exists('curl_init')) {
            $bgApi = !empty($ecare_received) ? 'ecare' : 'successtopup';
            $bgUrl = SITE_URL.'/api/check_recharge_status.php?secret=bgcheck2024&ref='.urlencode($ref).'&txn_id='.$txnId.'&api='.$bgApi;
            $bch = curl_init($bgUrl);
            curl_setopt_array($bch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 1,
                CURLOPT_CONNECTTIMEOUT => 1,
                CURLOPT_SSL_VERIFYPEER => false,
            ]);
            curl_exec($bch);
            curl_close($bch);
        }
    }

    // Telegram notification
    if ($status === 'success') {
        notifyRechargeSuccess($user['name'], $phone, number_format($amount,2), $ref);
        // Commission
        applyCommission($db, $user['id'], 'topup', $amount, $ref);
    } else {
        // Pending — notify admin
        $apiLabel = strtoupper($op_api);
        notifyPending('recharge', $user['name'], [
            '📱 Phone'    => $phone,
            '📡 Operator' => $operator['name'],
            '💰 Amount'   => CURRENCY.number_format($amount,2),
            '🔖 Ref'      => $ref,
            '⚙️ API'      => $apiLabel,
            '📊 Status'   => '⏳ Pending — Admin approval needed',
            '📝 Note'     => $note,
        ]);
    }

    // Response to user
    if ($status === 'success') {
        jsonResponse(true, '✅ রিচার্জ সফল হয়েছে!', [
            'reference'   => $ref,
            'old_balance' => $balance_before,
            'new_balance' => $balance_after,
            'status'      => 'success'
        ]);
    } else {
        $userMsg = !empty($need_polling)
            ? '⏳ রিচার্জ process হচ্ছে। কিছুক্ষণের মধ্যে সম্পন্ন হবে।'
            : ($op_api !== 'manual'
                ? '⏳ রিচার্জ রিকোয়েস্ট পাঠানো হয়েছে। API সমস্যায় Admin অনুমোদন করবেন।'
                : '⏳ রিচার্জ রিকোয়েস্ট পাঠানো হয়েছে। Admin অনুমোদনের পরে সম্পন্ন হবে।');

        // Get txn_id for polling
        $txnRow = $db->prepare("SELECT id FROM transactions WHERE reference=? AND user_id=? LIMIT 1");
        $txnRow->execute([$ref, $user['id']]);
        $txnId = $txnRow->fetchColumn() ?: 0;

        jsonResponse(true, $userMsg, [
            'reference'    => $ref,
            'txn_id'       => $txnId,
            'old_balance'  => $balance_before,
            'new_balance'  => $balance_after,
            'status'       => 'pending',
            'need_polling' => !empty($need_polling),
        ]);
    }

} catch (Exception $e) {
    $db->rollBack();
    jsonResponse(false, 'সিস্টেম ত্রুটি! আবার চেষ্টা করুন।');
}
