<?php
// Paynow Webhook Handler
// This endpoint receives payment status updates from Paynow

require_once '../../includes/payments.php';
require_once '../../includes/notifications.php';
require_once '../../config/payment_security.php';

header('Content-Type: application/json');

// Set security headers for webhook endpoints
PaymentSecurity::setSecurityHeaders();

// Get the raw POST data
$rawData = file_get_contents('php://input');
$data = json_decode($rawData, true);

// Log the webhook call
$db = getDB();
$stmt = $db->prepare("
    INSERT INTO payment_logs (action, level, message, context, created_at)
    VALUES ('paynow_webhook', 'info', 'Webhook received', ?, NOW())
");
$stmt->execute([json_encode($data)]);

// Validate webhook data
if (!$data || !isset($data['reference'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid webhook data']);
    exit;
}

$reference = $data['reference'];
$status = $data['status'] ?? null;

// Find transaction by reference number
$stmt = $db->prepare("SELECT * FROM payment_transactions WHERE reference_number = ?");
$stmt->execute([$reference]);
$transaction = $stmt->fetch();

if (!$transaction) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'Transaction not found']);
    exit;
}

// Update transaction status based on Paynow status
$newStatus = 'pending';
$processed = false;

switch (strtolower($status)) {
    case 'paid':
    case 'completed':
        $newStatus = 'completed';
        $processed = true;
        break;
    case 'cancelled':
    case 'failed':
        $newStatus = 'failed';
        // Send payment failed notification
        sendPaymentNotification('payment_failed', $transaction['transaction_id']);
        break;
    case 'pending':
    case 'processing':
        $newStatus = 'processing';
        break;
    default:
        $newStatus = 'pending';
        break;
}

// Update transaction
$stmt = $db->prepare("
    UPDATE payment_transactions
    SET status = ?, gateway_response = ?, processed_at = NOW()
    WHERE id = ?
");
$stmt->execute([$newStatus, json_encode($data), $transaction['id']]);

// If payment was successful, process the enrollment
if ($processed && $newStatus === 'completed') {
    $gateway = new PaymentGateway('paynow', $transaction['gateway_type']);
    $result = $gateway->processSuccessfulPayment($transaction['transaction_id']);

    if ($result['success']) {
        // Log successful processing
        $stmt = $db->prepare("
            INSERT INTO payment_logs (transaction_id, action, level, message, created_at)
            VALUES (?, 'payment_processed', 'info', 'Payment processed successfully', NOW())
        ");
        $stmt->execute([$transaction['id']]);
    } else {
        // Log processing error
        $stmt = $db->prepare("
            INSERT INTO payment_logs (transaction_id, action, level, message, context, created_at)
            VALUES (?, 'payment_processing_failed', 'error', ?, ?, NOW())
        ");
        $stmt->execute([$transaction['id'], $result['error'], json_encode(['transaction' => $transaction])]);
    }
}

// Log webhook processing
$stmt = $db->prepare("
    INSERT INTO payment_logs (transaction_id, action, level, message, context, created_at)
    VALUES (?, 'webhook_processed', 'info', 'Webhook processed successfully', ?, NOW())
");
$stmt->execute([$transaction['id'], json_encode(['status' => $newStatus, 'processed' => $processed])]);

// Return success response to Paynow
echo json_encode(['success' => true]);