<?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 transaction information
    $transactionId = $webhookData['objectId'] ?? null;
    $eventType = $webhookData['type'] ?? null;
    $transactionData = $webhookData['data'] ?? null;
    
    if (!$transactionId || !$eventType || !$transactionData) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required fields']);
        exit();
    }
    
    // Process the webhook based on event type
    switch ($eventType) {
        case 'transaction':
            $status = $transactionData['status'] ?? null;
            $amount = $transactionData['amount'] ?? 0;
            $customerName = $transactionData['customer']['name'] ?? 'Unknown';
            
            // Log status change
            error_log("Webhook received - Transaction: $transactionId, Status: $status, Amount: $amount, Customer: $customerName");
            
            // Handle different statuses
            switch ($status) {
                case 'paid':
                    // Transaction was paid successfully
                    error_log("Transaction $transactionId was paid successfully!");
                    // Here you can add logic to update your database, send confirmation emails, etc.
                    break;
                    
                case 'refused':
                    // Transaction was refused
                    $refusedReason = $transactionData['refusedReason'] ?? 'Unknown reason';
                    error_log("Transaction $transactionId was refused: $refusedReason");
                    break;
                    
                case 'canceled':
                    // Transaction was canceled
                    error_log("Transaction $transactionId was canceled");
                    break;
                    
                case 'expired':
                    // Transaction expired
                    error_log("Transaction $transactionId expired");
                    break;
                    
                case 'waiting_payment':
                    // Transaction is waiting for payment
                    error_log("Transaction $transactionId is waiting for payment");
                    break;
                    
                default:
                    error_log("Transaction $transactionId status changed to: $status");
                    break;
            }
            break;
            
        default:
            error_log("Unknown webhook event type: $eventType");
            break;
    }
    
    // Always respond with 200 OK to acknowledge receipt
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Webhook received successfully',
        'transaction_id' => $transactionId,
        'status' => $transactionData['status'] ?? 'unknown'
    ]);
    
} catch (Exception $e) {
    // Log the error
    error_log("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()
    ]);
}
?>
