<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
// When called via POST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Collect all POST data (usually from a form or API request)
    $postData = json_decode(file_get_contents("php://input"), true);


    try {
        // Convert POST data into JSON for sending
        $payload = json_encode($postData);

        // Define the external API endpoint
        $url = 'https://rejoicebilldesk.in/rjllearning_development/resources/payment_gateway/send_request.php';

        // Initialize cURL
        $ch = curl_init($url);

        // Set cURL options
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        // Execute request
        $response = curl_exec($ch);

        if ($response === false) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            echo json_encode(['status' => 0, 'error' => 'cURL Error: ' . $error_msg]);
            exit;
        }

        // Close cURL
        curl_close($ch);

        // Output the HTML page from send_request.php (e.g., redirect form)
        echo $response;
        exit;
    } catch (Exception $e) {
        echo json_encode(['status' => 0, 'error' => 'Exception: ' . $e->getMessage()]);
        exit;
    }
}
