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

$input  = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$id     = intval($input['id'] ?? 0);
$note   = sanitize($input['note'] ?? '');

$db = getDB();
// All DingConnect types
$txn = $db->prepare("SELECT t.*, u.name as uname, u.balance FROM transactions t JOIN users u ON t.user_id=u.id WHERE t.id=? AND t.type IN ('international','pin','gift','card')");
$txn->execute([$id]);
$t = $txn->fetch();

if (!$t) jsonResponse(false, 'Transaction not found!');
if (!in_array($t['status'], ['pending','processing'])) jsonResponse(false, 'Cannot change this transaction!');

if ($action === 'success') {
    $db->prepare("UPDATE transactions SET status='success', note=?, updated_at=NOW() WHERE id=?")
       ->execute([$note ?: 'Approved by admin', $id]);

    // Commission apply
    applyCommission($db, $t['user_id'], $t['type'], $t['amount'], $t['reference']);

    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
       ->execute([$t['user_id'],'✅ Transaction Approved!','Your '.ucfirst($t['type']).' has been completed. Ref: '.$t['reference']]);
    jsonResponse(true, '✅ Approved successfully!');

} elseif ($action === 'refund') {
    $db->beginTransaction();
    try {
        $db->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$t['amount'], $t['user_id']]);
        $new_bal = $t['balance'] + $t['amount'];
        $db->prepare("UPDATE transactions SET status='refunded', note=?, balance_after=?, updated_at=NOW() WHERE id=?")
           ->execute([$note ?: 'Rejected & refunded', $new_bal, $id]);
        $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'],$new_bal,'RF-'.$t['reference'],'success','Refund: '.$t['reference']]);
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")
           ->execute([$t['user_id'],'↩️ Refunded',CURRENCY.number_format($t['amount'],2).' has been refunded to your balance.']);
        $db->commit();
        jsonResponse(true, '↩️ Refund completed.');
    } catch(Exception $e) {
        $db->rollBack();
        jsonResponse(false, 'Error: '.$e->getMessage());
    }
}
jsonResponse(false, 'Unknown action');
