<?php
// Background status checker - called after recharge submit
// Checks every few seconds for fast response

require_once '../includes/config.php';
require_once '../includes/ecare.php';
require_once '../includes/successtopup.php';
require_once '../includes/custom_api.php';
require_once '../includes/commission.php';
require_once '../includes/telegram.php';

$secret = $_GET['secret'] ?? '';
$ref    = trim($_GET['ref'] ?? '');
$txnId  = intval($_GET['txn_id'] ?? 0);
$api    = $_GET['api'] ?? 'ecare'; // ecare or successtopup

if ($secret !== 'bgcheck2024' || !$ref || !$txnId) {
    http_response_code(403); exit;
}

// Disconnect from browser — run in background
if (ob_get_level()) ob_end_clean();
header('Connection: close');
header('Content-Length: 0');
ignore_user_abort(true);
flush();

set_time_limit(660);
$db = getDB();

// Check intervals: 5s, 5s, 10s, 10s, 15s, 15s, 20s, 20s, 30s, 30s... up to 10 min
$intervals = [5,5,5,10,10,15,15,20,20,30,30,30,30,30,30,30,30,30,30,30];

function resolveSuccess($db, $txnId, $ref, $trxId, $api, $res, $elapsed) {
    $full = $db->prepare("SELECT t.*, u.balance, u.name as uname FROM transactions t JOIN users u ON t.user_id=u.id WHERE t.id=?");
    $full->execute([$txnId]);
    $txnData = $full->fetch();
    if (!$txnData || $txnData['status'] !== 'pending') return;

    $db->beginTransaction();
    try {
        $db->prepare("UPDATE transactions SET status='success', note=?, api_response=?, updated_at=NOW() WHERE id=?")
           ->execute(['TrxID: '.$trxId, json_encode($res), $txnId]);
        applyCommission($db, $txnData['user_id'], 'topup', $txnData['amount'], $ref);
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$txnData['user_id'], '✅ রিচার্জ সফল!',
               $txnData['phone_number'].' — '.CURRENCY.number_format($txnData['amount'],2).' সম্পন্ন হয়েছে।']);
        $db->commit();
        notifyUserRechargeSuccess($txnData['user_id'], $txnData['phone_number'], number_format($txnData['amount'],2), $ref, '');
    } catch(Exception $e) { $db->rollBack(); }
}

function resolveFailed($db, $txnId, $ref, $api, $res) {
    $full = $db->prepare("SELECT t.*, u.balance FROM transactions t JOIN users u ON t.user_id=u.id WHERE t.id=?");
    $full->execute([$txnId]);
    $txnData = $full->fetch();
    if (!$txnData || $txnData['status'] !== 'pending') return;

    $db->beginTransaction();
    try {
        $newBal = $txnData['balance'] + $txnData['amount'];
        $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$txnData['amount'],$txnData['user_id']]);
        $db->prepare("UPDATE transactions SET status='failed', note='❌ Failed', balance_after=?, updated_at=NOW() WHERE id=?")->execute([$newBal,$txnId]);
        $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
           ->execute([$txnData['user_id'],'refund',$txnData['amount'],$txnData['amount'],$txnData['balance'],$newBal,'RF-'.$ref,'success','Auto refund']);
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")
           ->execute([$txnData['user_id'],'❌ রিচার্জ Failed', CURRENCY.number_format($txnData['amount'],2).' refunded.']);
        $db->commit();
        notifyUserRechargeFailed($txnData['user_id'], number_format($txnData['amount'],2), $ref);
    } catch(Exception $e) { $db->rollBack(); }
}

foreach ($intervals as $wait) {
    sleep($wait);

    // Already resolved?
    $txn = $db->prepare("SELECT status FROM transactions WHERE id=? AND reference=?");
    $txn->execute([$txnId, $ref]);
    $t = $txn->fetch();
    if (!$t || in_array($t['status'], ['success','failed','refunded'])) break;

    if ($api === 'ecare') {
        // Get ecare_ref from api_response
        $apiRow = $db->prepare("SELECT api_response FROM transactions WHERE id=?");
        $apiRow->execute([$txnId]);
        $apiData = json_decode($apiRow->fetchColumn(), true);
        $checkRef = $apiData['ecare_ref'] ?? $ref;

        $res      = ecareStatus($checkRef);
        $rcStatus = $res['rc_status'] ?? '';
        $trxId    = $res['trxid'] ?? '';

        if ($rcStatus === 'SUCCESS') {
            resolveSuccess($db, $txnId, $ref, $trxId, $api, $res, 0);
            break;
        } elseif (in_array($rcStatus, ['FAILED','REJECT','REJECTED'])) {
            resolveFailed($db, $txnId, $ref, $api, $res);
            break;
        }

    } elseif ($api === 'successtopup') {
        $res    = successTopupStatus($ref);
        $stStat = strtoupper($res['status'] ?? '');
        $trxId  = $res['trxid'] ?? $res['TRXID'] ?? '';
        $msg    = strtolower($res['message'] ?? '');

        if ($stStat === 'SUCCESS' || $stStat === 'COMPLETED' || strpos($msg,'success')!==false) {
            resolveSuccess($db, $txnId, $ref, $trxId, $api, $res, 0);
            break;
        } elseif (in_array($stStat, ['FAILED','REJECTED','CANCELLED','INVALID']) || strpos($msg,'failed')!==false || strpos($msg,'reject')!==false) {
            resolveFailed($db, $txnId, $ref, $api, $res);
            break;
        }

    } elseif (is_numeric($api) && intval($api) > 0) {
        // Custom API
        $customApiId = intval($api);
        $res    = customApiCall($customApiId, 'status', ['trxid' => $ref, 'ref' => $ref]);
        $trxId  = $res['trxid'] ?? '';
        $stStat = strtoupper($res['status'] ?? '');
        $msg    = strtolower($res['message'] ?? '');

        if ($res['ok'] || in_array($stStat,['SUCCESS','COMPLETED']) || strpos($msg,'success')!==false) {
            resolveSuccess($db, $txnId, $ref, $trxId, $api, $res, 0);
            break;
        } elseif (in_array($stStat,['FAILED','REJECTED','CANCELLED','INVALID']) || strpos($msg,'failed')!==false || strpos($msg,'reject')!==false) {
            resolveFailed($db, $txnId, $ref, $api, $res);
            break;
        }
    }
}
