<?php
/*******************************************************************************************************************
| Rainforest Pay Webhook Handler for EasyStream
| Secure webhook processing for payment notifications
|*******************************************************************************************************************/

define('_ISVALID', true);
include_once '../../../f_core/config.core.php';

// Load Rainforest Pay handler
require_once __DIR__ . '/rainforest_pay.php';

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

try {
    // Get webhook payload
    $payload = file_get_contents('php://input');
    $signature = $_SERVER['HTTP_X_RAINFOREST_SIGNATURE'] ?? '';
    
    // Log webhook received
    error_log(date('Y-m-d H:i:s') . " [RainforestPay] Webhook received\n", 3, 'logs/rainforest_webhooks.log');
    
    if (empty($payload)) {
        http_response_code(400);
        echo json_encode(['error' => 'Empty payload']);
        exit;
    }
    
    if (empty($signature)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing signature']);
        exit;
    }
    
    // Initialize handler and process webhook
    $handler = new RainforestPayHandler($class_database);
    $result = $handler->processWebhook($payload, $signature);
    
    if ($result['success']) {
        http_response_code(200);
        echo json_encode(['status' => 'success', 'message' => $result['message']]);
    } else {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => $result['message']]);
    }
    
} catch (Exception $e) {
    // Log error
    error_log(date('Y-m-d H:i:s') . " [RainforestPay] Webhook error: " . $e->getMessage() . "\n", 3, 'logs/rainforest_webhooks.log');
    
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Internal server error']);
}
?>