<?php
// webhooks/flutterwave.php - Flutterwave Webhook Handler

require_once __DIR__ . '/../app/Core/init.php';

// Get input
$input = @file_get_contents("php://input");
$signature = $_SERVER['HTTP_VERIF_HASH'] ?? '';

// Log webhook
log_message("Flutterwave Webhook Received: " . $input, 'info');

// Validate signature
$flutterwave = new Flutterwave();

if (!$flutterwave->validateWebhook($signature)) {
    log_message("Flutterwave Webhook: Invalid signature", 'error');
    http_response_code(400);
    die('Invalid signature');
}

// Parse webhook data
$event = json_decode($input, true);

if (!$event) {
    log_message("Flutterwave Webhook: Invalid JSON", 'error');
    http_response_code(400);
    die('Invalid JSON');
}

// Handle event
$event_type = $event['event'] ?? '';
$data = $event['data'] ?? [];

log_message("Flutterwave Webhook Event: {$event_type}", 'info');

try {
    switch ($event_type) {
        case 'charge.completed':
            handleChargeCompleted($data);
            break;
            
        case 'transfer.completed':
            handleTransferCompleted($data);
            break;
            
        default:
            log_message("Flutterwave Webhook: Unhandled event type - {$event_type}", 'info');
    }
    
    // Send success response
    http_response_code(200);
    echo json_encode(['status' => 'success']);
    
} catch (Exception $e) {
    log_message("Flutterwave Webhook Error: " . $e->getMessage(), 'error');
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

/**
 * Handle completed charge
 */
function handleChargeCompleted($data) {
    $reference = $data['tx_ref'] ?? '';
    $amount = $data['amount'] ?? 0;
    $status = $data['status'] ?? '';
    
    if ($status !== 'successful') {
        return;
    }
    
    // Verify with Flutterwave API
    $flutterwave = new Flutterwave();
    $verification = $flutterwave->verify($reference);
    
    if (!$verification['success']) {
        log_message("Flutterwave Webhook: Verification failed for {$reference}", 'error');
        return;
    }
    
    $db = Database::getInstance();
    
    // Find payment record
    $payment_model = new Payment();
    $payment = $payment_model->findByReference($reference);
    
    if (!$payment) {
        log_message("Flutterwave Webhook: Payment not found for reference {$reference}", 'error');
        return;
    }
    
    // Check if already processed
    if ($payment['status'] === 'completed') {
        log_message("Flutterwave Webhook: Payment already processed - {$reference}", 'info');
        return;
    }
    
    $db->beginTransaction();
    
    try {
        // Update payment status
        $payment_model->markAsCompleted($payment['id'], json_encode($data));
        
        // Update order payment status
        $order_model = new Order();
        $order_model->updatePaymentStatus($payment['order_id'], 'paid');
        
        // Create commission record
        $commission_service = new CommissionService();
        $commission_service->createCommission($payment['order_id']);
        
        // Send notifications
        $notification_service = new NotificationService();
        $notification_service->notifyPaymentConfirmed($payment['id']);
        $notification_service->notifyVendorNewOrder($payment['order_id']);
        
        $db->commit();
        
        log_message("Flutterwave Webhook: Payment processed successfully - {$reference}", 'info');
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
}

/**
 * Handle completed transfer
 */
function handleTransferCompleted($data) {
    log_message("Flutterwave Webhook: Transfer completed - " . json_encode($data), 'info');
}