<?php
// webhooks/paystack.php - Paystack Webhook Handler

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

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

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

// Validate signature
$paystack = new Paystack();

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

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

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

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

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

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

/**
 * Handle successful charge
 */
function handleChargeSuccess($data) {
    $reference = $data['reference'] ?? '';
    $amount = ($data['amount'] ?? 0) / 100; // Convert from kobo
    $status = $data['status'] ?? '';
    
    if ($status !== 'success') {
        return;
    }
    
    $db = Database::getInstance();
    
    // Find payment record
    $payment_model = new Payment();
    $payment = $payment_model->findByReference($reference);
    
    if (!$payment) {
        log_message("Paystack Webhook: Payment not found for reference {$reference}", 'error');
        return;
    }
    
    // Check if already processed
    if ($payment['status'] === 'completed') {
        log_message("Paystack 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("Paystack Webhook: Payment processed successfully - {$reference}", 'info');
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
}

/**
 * Handle successful transfer
 */
function handleTransferSuccess($data) {
    log_message("Paystack Webhook: Transfer successful - " . json_encode($data), 'info');
}

/**
 * Handle failed transfer
 */
function handleTransferFailed($data) {
    log_message("Paystack Webhook: Transfer failed - " . json_encode($data), 'error');
}