<?php
// Called by user app JS every 30 seconds to check recharge status
require_once '../includes/config.php';
require_once '../includes/ecare.php';
require_once '../includes/successtopup.php';
require_once '../includes/commission.php';
require_once '../includes/telegram.php';
requireLogin();

header('Content-Type: application/json');

$ref   = trim($_GET['ref'] ?? '');
$txnId = intval($_GET['txn_id'] ?? 0);

if (!$ref || !$txnId) {
    echo json_encode(['success'=>false,'message'=>'Invalid params']); exit;
}

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

// Get transaction
$txn = $db->prepare("SELECT t.*, u.balance, u.name as uname, o.code as op_code FROM transactions t JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id WHERE t.id=? AND t.user_id=? AND t.reference=?");
$txn->execute([$txnId, $user['id'], $ref]);
$t = $txn->fetch();

if (!$t) {
    echo json_encode(['success'=>false,'message'=>'Transaction not found']); exit;
}

// Already resolved?
if (in_array($t['status'], ['success','refunded','failed'])) {
    echo json_encode([
        'success' => true,
        'status'  => $t['status'],
        'done'    => true,
        'message' => $t['status'] === 'success' ? '✅ রিচার্জ সফল হয়েছে!' : '❌ রিচার্জ Failed — Refunded',
    ]); exit;
}

// Detect API from note and get correct check ID
$isEcare = strpos($t['note']??'', 'ECARE') !== false;
$isST    = strpos($t['note']??'', 'ST ') !== false || strpos($t['note']??'', 'SuccessTopUp') !== false;

// For ECARE: use ecare_ref saved in api_response (may differ from our $ref)
$ecareCheckRef = $ref;
if ($isEcare && $t['api_response']) {
    $apiData = json_decode($t['api_response'], true);
    if (!empty($apiData['ecare_ref'])) {
        $ecareCheckRef = $apiData['ecare_ref'];
    }
}

// Check status from correct API
$rcStatus = ''; $trxId = '';

if ($isEcare) {
    $res      = ecareStatus($ecareCheckRef);
    $rcStatus = $res['rc_status'] ?? '';
    $trxId    = $res['trxid']    ?? '';
    // Normalize
    if ($rcStatus === 'SUCCESS')                         $rcStatus = 'success';
    if (in_array($rcStatus, ['FAILED','REJECT']))        $rcStatus = 'failed';
    if (in_array($rcStatus, ['PENDING','PROCESSING']))   $rcStatus = 'pending';

} elseif ($isST) {
    $res      = successTopupStatus($ref);
    $rcStatus = strtolower($res['status'] ?? 'pending');
    $trxId    = $res['trxid'] ?? $res['transaction_id'] ?? '';
    // Normalize ST status
    if ($rcStatus === 'success' || $rcStatus === 'completed') $rcStatus = 'success';
    if (in_array($rcStatus, ['failed','rejected','cancelled'])) $rcStatus = 'failed';

} else {
    // Unknown API — check both
    $res = ecareStatus($ref);
    $rc  = $res['rc_status'] ?? '';
    if ($rc === 'SUCCESS') $rcStatus = 'success';
    elseif (in_array($rc, ['FAILED','REJECT'])) $rcStatus = 'failed';
    else {
        $res2 = successTopupStatus($ref);
        $rc2  = strtolower($res2['status'] ?? '');
        if (in_array($rc2, ['success','completed'])) $rcStatus = 'success';
        elseif (in_array($rc2, ['failed','rejected'])) $rcStatus = 'failed';
        else $rcStatus = 'pending';
    }
    $trxId = $res['trxid'] ?? $res2['trxid'] ?? '';
}

if ($rcStatus === 'success') {
    $db->beginTransaction();
    try {
        $db->prepare("UPDATE transactions SET status='success', note=?, api_response=?, updated_at=NOW() WHERE id=?")
           ->execute(['✅ ECARE Success. TrxID: '.$trxId, json_encode($res), $txnId]);

        applyCommission($db, $t['user_id'], 'topup', $t['amount'], $ref);

        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$t['user_id'], '✅ রিচার্জ সফল!',
               $t['phone_number'].' — '.CURRENCY.number_format($t['amount'],2).' সম্পন্ন। Ref: '.$ref]);

        $db->commit();

        // Notify user Telegram
        notifyUserRechargeSuccess($t['user_id'], $t['phone_number'], number_format($t['amount'],2), $ref, $t['op_name']??'');

        // Telegram
        notifyPending('recharge_success', $t['uname'], [
            '📱 Phone'  => $t['phone_number'],
            '💰 Amount' => CURRENCY.number_format($t['amount'],2),
            '🔖 Ref'    => $ref,
            '🆔 TrxID'  => $trxId,
            '📊 Status' => '✅ SUCCESS',
        ]);

        echo json_encode([
            'success' => true,
            'status'  => 'success',
            'done'    => true,
            'message' => '✅ রিচার্জ সফল হয়েছে! TrxID: '.$trxId,
        ]); exit;

    } catch(Exception $e) {
        $db->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]); exit;
    }

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

        // Notify user Telegram
        notifyUserRechargeFailed($t['user_id'], number_format($t['amount'],2), $ref);

        echo json_encode([
            'success' => true,
            'status'  => 'failed',
            'done'    => true,
            'message' => '❌ রিচার্জ Failed — '.CURRENCY.number_format($t['amount'],2).' refunded',
        ]); exit;

    } catch(Exception $e) {
        $db->rollBack();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]); exit;
    }

} else {
    // Still pending/processing
    echo json_encode([
        'success' => true,
        'status'  => 'pending',
        'done'    => false,
        'message' => 'Processing... ('.$rcStatus.')',
    ]); exit;
}
