<?php
/**
 * Admin wallet deposits management
 */
require_once 'config.php';

$input = json_decode(file_get_contents('php://input'), true) ?: $_GET;
$userId = miniapp_require_admin();
$status = $input['status'] ?? $_GET['status'] ?? 'PENDING';

// GET - list deposits
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $pdo->prepare("
        SELECT wt.*, u.first_name, u.last_name, u.username
        FROM wallet_transactions wt
        JOIN users u ON wt.user_id = u.id
        WHERE wt.type = 'DEPOSIT'
        AND wt.status = ?
        ORDER BY wt.created_at DESC
        LIMIT 100
    ");
    $stmt->execute([$status]);
    $deposits = $stmt->fetchAll();
    
    foreach ($deposits as &$d) {
        $d['amount_formatted'] = money((int)$d['amount']);
        $d['receipt_url'] = null;
        if (!empty($d['receipt_file_id']) && preg_match('/^(receipt|deposit)_\\d+_\\d+\\.(jpg|jpeg|png|gif|webp)$/i', $d['receipt_file_id'])) {
            $d['receipt_url'] = 'uploads/' . $d['receipt_file_id'];
        }
    }
    
    echo json_encode([
        'ok'   => true,
        'data' => ['deposits' => $deposits],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// POST - approve/reject
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $txId = $input['tx_id'] ?? null;
    $action = strtoupper($input['action'] ?? '');
    
    if (!$txId || !in_array($action, ['APPROVE', 'REJECT'])) {
        echo json_encode(['ok' => false, 'error' => 'tx_id and action required'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    $txId = (int)$txId;
    
    // Get transaction
    $stmt = $pdo->prepare("SELECT * FROM wallet_transactions WHERE id = ? AND type = 'DEPOSIT'");
    $stmt->execute([$txId]);
    $tx = $stmt->fetch();
    
    if (!$tx) {
        echo json_encode(['ok' => false, 'error' => 'تراکنش یافت نشد'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($tx['status'] !== 'PENDING') {
        echo json_encode(['ok' => false, 'error' => 'این تراکنش قبلاً پردازش شده است'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'REJECT') {
        $stmt = $pdo->prepare("UPDATE wallet_transactions SET status = 'REJECTED', processed_by=?, processed_at=NOW() WHERE id = ?");
        $stmt->execute([(int)$userId, $txId]);
        $pdo->prepare("UPDATE crypto_payments SET status='REJECTED', processed_by=?, processed_at=NOW() WHERE wallet_transaction_id=? AND status<>'PAID'")->execute([(int)$userId, $txId]);
        
        tg('sendMessage', [
            'chat_id' => $tx['user_id'],
            'text'    => "❌ درخواست واریز #{$txId} به مبلغ " . money($tx['amount']) . " رد شد.\n\nلطفاً با پشتیبانی تماس بگیرید.",
        ]);
        gemaccAdminActionNotify('درخواست واریز رد شد', ['شماره تراکنش'=>$txId, 'کاربر'=>$tx['user_id'], 'مبلغ'=>money((int)$tx['amount'])], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'تراکنش رد شد'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // APPROVE
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("UPDATE wallet_transactions SET status = 'COMPLETED', processed_by=?, processed_at=NOW() WHERE id = ?");
        $stmt->execute([(int)$userId, $txId]);
        $pdo->prepare("UPDATE crypto_payments SET status='PAID', paid_at=COALESCE(paid_at,NOW()), processed_by=?, processed_at=NOW() WHERE wallet_transaction_id=?")->execute([(int)$userId, $txId]);
        
        $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt->execute([$tx['amount'], $tx['user_id']]);
        
        // Get new balance
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$tx['user_id']]);
        $newBalance = $stmt->fetchColumn();
        
        $pdo->commit();
        
        tg('sendMessage', [
            'chat_id' => $tx['user_id'],
            'text'    => "✅ واریز #{$txId} به مبلغ " . money($tx['amount']) . " تأیید شد!\n\n💰 موجودی جدید: " . money($newBalance),
        ]);
        gemaccAdminActionNotify('درخواست واریز تأیید شد', ['شماره تراکنش'=>$txId, 'کاربر'=>$tx['user_id'], 'مبلغ'=>money((int)$tx['amount']), 'موجودی جدید'=>money((int)$newBalance)], $userId);
        
        echo json_encode(['ok' => true, 'message' => 'تراکنش تأیید شد'], JSON_UNESCAPED_UNICODE);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['ok' => false, 'error' => 'خطا: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    }
}
