<?php
/**
 * Payment Retry Logic
 * Handles retrying failed payments
 */

class PaymentRetry {
    private $pdo;
    private $maxRetries = 3;
    private $retryDelay = 300; // 5 minutes between retries
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    /**
     * Check if order should be retried
     */
    public function shouldRetry($orderId) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT retry_count, last_retry_at, payment_status, error_message
                FROM binance_p2p_orders
                WHERE id = ?
            ");
            $stmt->execute([$orderId]);
            $order = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$order) {
                return false;
            }
            
            // Don't retry if already successful
            if ($order['payment_status'] === 'completed') {
                return false;
            }
            
            // Don't retry if max retries reached
            if ($order['retry_count'] >= $this->maxRetries) {
                return false;
            }
            
            // Check if enough time has passed since last retry
            if ($order['last_retry_at']) {
                $lastRetryTime = strtotime($order['last_retry_at']);
                $timeSinceRetry = time() - $lastRetryTime;
                
                if ($timeSinceRetry < $this->retryDelay) {
                    return false; // Not enough time has passed
                }
            }
            
            return true;
            
        } catch (PDOException $e) {
            error_log("Error checking retry status: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Record retry attempt
     */
    public function recordRetry($orderId) {
        try {
            $stmt = $this->pdo->prepare("
                UPDATE binance_p2p_orders
                SET retry_count = retry_count + 1,
                    last_retry_at = NOW(),
                    updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$orderId]);
        } catch (PDOException $e) {
            error_log("Error recording retry: " . $e->getMessage());
        }
    }
    
    /**
     * Get orders that need retry
     */
    public function getOrdersToRetry($limit = 10) {
        try {
            $stmt = $this->pdo->prepare("
                SELECT id, order_no, retry_count, last_retry_at, error_message
                FROM binance_p2p_orders
                WHERE payment_status IN ('failed', 'processing')
                AND retry_count < ?
                AND (
                    last_retry_at IS NULL 
                    OR last_retry_at < DATE_SUB(NOW(), INTERVAL ? SECOND)
                )
                ORDER BY created_at ASC
                LIMIT ?
            ");
            $stmt->execute([$this->maxRetries, $this->retryDelay, $limit]);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Error getting orders to retry: " . $e->getMessage());
            return [];
        }
    }
}

