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

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 ('paypal_webhook', 'info', 'Webhook received', ?, NOW())
");
$stmt->execute([json_encode($data)]);

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

$orderId = $data['resource']['id'];
$eventType = $data['event_type'] ?? '';

// Find transaction by PayPal order ID
$stmt = $db->prepare("
    SELECT pt.* FROM payment_transactions pt
    WHERE JSON_EXTRACT(pt.gateway_metadata, '$.paypal_order_id') = ?
");
$stmt->execute([$orderId]);
$transaction = $stmt->fetch();

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

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

switch ($eventType) {
    case 'PAYMENT.CAPTURE.COMPLETED':
        $newStatus = 'completed';
        $processed = true;
        break;
    case 'PAYMENT.CAPTURE.DENIED':
    case 'PAYMENT.CAPTURE.FAILED':
        $newStatus = 'failed';
        break;
    case 'PAYMENT.CAPTURE.CANCELLED':
    case 'PAYMENT.CAPTURE.REVERSED':
        $newStatus = 'cancelled';
        break;
    default:
        // Keep current status for unhandled events
        $newStatus = $transaction['status'];
        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('paypal', $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, 'event_type' => $eventType, 'processed' => $processed])]);

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