<?php
// admin/ajax/deposit.php
require_once '../../includes/config.php';
requireAdmin();

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

$deposit = $db->prepare("SELECT * FROM deposits WHERE id=?");
$deposit->execute([$id]);
$dep = $deposit->fetch();
if (!$dep) jsonResponse(false, 'ডিপোজিট পাওয়া যায়নি');

if ($action === 'approve') {
    $db->beginTransaction();
    try {
        $user = $db->prepare("SELECT * FROM users WHERE id=?"); $user->execute([$dep['user_id']]); $user = $user->fetch();
        $db->prepare("UPDATE deposits SET status='approved', approved_by=?, approved_at=NOW() WHERE id=?")->execute([$_SESSION['user_id'], $id]);
        $db->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$dep['amount'], $dep['user_id']]);
        $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,?,?,?,?,?,?,?)")
           ->execute([$dep['user_id'],'deposit',$dep['amount'],0,$dep['amount'],$user['balance'],$user['balance']+$dep['amount'],generateRef(),'success','Deposit approved by admin']);
        $db->commit();
        jsonResponse(true, 'ডিপোজিট অনুমোদন হয়েছে');
    } catch (Exception $e) { $db->rollBack(); jsonResponse(false, 'ত্রুটি হয়েছে'); }
} elseif ($action === 'reject') {
    $note = sanitize($input['note'] ?? '');
    $db->prepare("UPDATE deposits SET status='rejected', admin_note=? WHERE id=?")->execute([$note, $id]);
    jsonResponse(true, 'ডিপোজিট প্রত্যাখ্যান করা হয়েছে');
}
jsonResponse(false, 'অজানা অ্যাকশন');
