<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Log webhook data for debugging
function logWebhook($data) {
    $logFile = 'webhook_logs.txt';
    $timestamp = date('Y-m-d H:i:s');
    $logEntry = "[$timestamp] " . json_encode($data) . "\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
}

try {
    // Only accept POST requests
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        exit();
    }
    
    // Get the raw POST data
    $rawData = file_get_contents('php://input');
    $webhookData = json_decode($rawData, true);
    
    // Log the webhook data
    logWebhook($webhookData);
    
    if (!$webhookData) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid JSON data']);
        exit();
    }
    
    // Extract PayFort webhook information
    $transactionId = $webhookData['transactionId'] ?? null;
    $object = $webhookData['object'] ?? null;
    $status = $webhookData['status'] ?? null;
    $method = $webhookData['method'] ?? null;
    $value = $webhookData['value'] ?? 0;
    $orderId = $webhookData['orderId'] ?? null;
    $processedAt = $webhookData['processedAt'] ?? null;
    $endToEndId = $webhookData['endToEndId'] ?? null;
    $payer = $webhookData['payer'] ?? null;
    $observation = $webhookData['observation'] ?? null;
    
    if (!$transactionId || !$object || !$status) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit();
    }
    
    // Log webhook received
    error_log("PayFort Webhook received - Transaction: $transactionId, Object: $object, Status: $status, Method: $method, Value: $value, OrderId: $orderId");
    
    // Process the webhook based on object type and status
    switch ($object) {
        case 'cashin':
            // Handle Cash-In (payment received) events
            switch ($status) {
                case 'created':
                    error_log("PIX QR Code created for transaction $transactionId");
                    // PIX QR Code was generated successfully
                    break;
                    
                case 'paid':
                    // Payment was received successfully
                    $payerName = $payer['name'] ?? 'Unknown';
                    $payerDocument = $payer['documentId'] ?? 'Unknown';
                    $bankName = $payer['bankName'] ?? 'Unknown';
                    $bankIspb = $payer['bankIspb'] ?? 'Unknown';
                    
                    error_log("Payment received for transaction $transactionId - Payer: $payerName ($payerDocument), Bank: $bankName ($bankIspb), EndToEndId: $endToEndId");
                    
                    // Here you can add logic to:
                    // - Update your database
                    // - Send confirmation emails
                    // - Process the payment
                    // - Update order status
                    break;
                    
                case 'refund':
                    // Transaction was refunded
                    error_log("Transaction $transactionId was refunded. Reason: $observation");
                    break;
                    
                case 'infraction':
                    // Transaction had an infraction
                    error_log("Transaction $transactionId had an infraction. Reason: $observation");
                    break;
                    
                default:
                    error_log("Transaction $transactionId status changed to: $status");
                    break;
            }
            break;
            
        case 'transfer':
            // Handle Cash-Out (transfer) events
            switch ($status) {
                case 'created':
                    error_log("Transfer created for transaction $transactionId");
                    break;
                    
                case 'paid':
                    // Transfer was completed successfully
                    $destinationBank = $webhookData['destinationBank'] ?? null;
                    $destinationName = $destinationBank['name'] ?? 'Unknown';
                    $destinationCpfCnpj = $destinationBank['cpfCnpj'] ?? 'Unknown';
                    
                    error_log("Transfer completed for transaction $transactionId - Destination: $destinationName ($destinationCpfCnpj), EndToEndId: $endToEndId");
                    break;
                    
                case 'refund':
                    // Transfer was refunded
                    error_log("Transfer $transactionId was refunded. Reason: $observation");
                    break;
                    
                default:
                    error_log("Transfer $transactionId status changed to: $status");
                    break;
            }
            break;
            
        default:
            error_log("Unknown webhook object type: $object");
            break;
    }
    
    // Always respond with 200 OK to acknowledge receipt
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'PayFort webhook received successfully',
        'transaction_id' => $transactionId,
        'object' => $object,
        'status' => $status,
        'order_id' => $orderId
    ]);
    
} catch (Exception $e) {
    // Log the error
    error_log("PayFort Webhook error: " . $e->getMessage());
    
    // Still respond with 200 to prevent retries for this specific webhook
    http_response_code(200);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>

