<?php
/**
 * Check and credit pending crypto payments
 * Call this function after user logs in or on dashboard load
 */
function checkPendingCryptoPayments($userId) {
    try {
        require_once __DIR__ . '/OxaPayAPI.php';
        
        $pdo = getDBConnection();
        $oxapay = new OxaPayAPI();
        
        if (!$oxapay->isConfigured()) {
            return false;
        }
        
        // Get pending crypto payments for this user
        $stmt = $pdo->prepare("SELECT * FROM fund_requests WHERE user_id = ? AND status = 'pending' AND payment_method = 'crypto' AND payment_uuid IS NOT NULL");
        $stmt->execute([$userId]);
        $pendingPayments = $stmt->fetchAll();
        
        if (empty($pendingPayments)) {
            return false;
        }
        
        $credited = false;
        
        foreach ($pendingPayments as $payment) {
            // Check payment status from OxaPay
            $paymentInfo = $oxapay->getPaymentInfo($payment['payment_uuid']);
            
            if (!$paymentInfo) continue;
            
            // Get status from response
            $status = '';
            $payStatus = '';
            $txId = '';
            
            // Handle different response formats
            if (isset($paymentInfo['result']) && $paymentInfo['result'] == 100) {
                $status = strtolower($paymentInfo['status'] ?? '');
                $payStatus = strtolower($paymentInfo['payStatus'] ?? '');
                $txId = $paymentInfo['txID'] ?? '';
            } elseif (isset($paymentInfo['status'])) {
                $status = strtolower($paymentInfo['status']);
                $txId = $paymentInfo['txid'] ?? $paymentInfo['txID'] ?? '';
            }
            
            // Check if payment is complete
            if (in_array($payStatus, ['complete', 'paid', 'confirmed']) || in_array($status, ['complete', 'paid', 'confirmed', 'sending', 'finished'])) {
                
                // Double-check status to prevent duplicate credits
                $checkStmt = $pdo->prepare("SELECT status FROM fund_requests WHERE id = ? FOR UPDATE");
                $checkStmt->execute([$payment['id']]);
                $currentStatus = $checkStmt->fetchColumn();
                
                if ($currentStatus === 'pending') {
                    // Credit user balance
                    $userModel = new User();
                    $userModel->updateBalance($userId, $payment['amount'], 'add');
                    
                    // Update fund request
                    $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'approved', payment_txid = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$txId, $payment['id']]);
                    
                    // Record transaction
                    try {
                        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, reference, created_at) VALUES (?, 'deposit', ?, ?, ?, NOW())");
                        $stmt->execute([
                            $userId,
                            $payment['amount'],
                            'Crypto deposit via OxaPay',
                            $payment['payment_reference']
                        ]);
                    } catch (Exception $e) {
                        // Ignore if transactions table doesn't exist
                    }
                    
                    $credited = true;
                }
                
            } elseif (in_array($status, ['expired']) || in_array($payStatus, ['expired'])) {
                // Mark as expired
                $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'expired', updated_at = NOW() WHERE id = ?");
                $stmt->execute([$payment['id']]);
                
            } elseif (in_array($status, ['failed']) || in_array($payStatus, ['failed'])) {
                // Mark as failed
                $stmt = $pdo->prepare("UPDATE fund_requests SET status = 'failed', updated_at = NOW() WHERE id = ?");
                $stmt->execute([$payment['id']]);
            }
            // If 'waiting' or 'confirming', keep as pending
        }
        
        return $credited;
        
    } catch (Exception $e) {
        error_log('Payment check error: ' . $e->getMessage());
        return false;
    }
}