<?php
ini_set('display_errors', 1);

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");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $postData = $_POST;
     

    try {
         if (isset($_GET['order_id'])) {
            $postData['order_id'] = $_GET['order_id'];
        }
        // Convert POST data to JSON
        $payload = json_encode($postData);
        
        // cURL setup
        $ch = curl_init();
        $commonResponsePath = add(); // Get URL of common response file
        
        

        curl_setopt($ch, CURLOPT_URL, $commonResponsePath);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch); // Execute cURL

        if ($result === false) {
            $error_msg = curl_error($ch);
            curl_close($ch);
            echo json_encode(array('status' => 0, 'error' => 'cURL error: ' . $error_msg));
            exit;
        }
        
        curl_close($ch);
        
        $data = json_decode($result, true);


        if (isset($data['error']) && $data['error']) {
            echo "<pre>Error from common_response: " . $data['message'] . "</pre>";
            exit;
        }

        // Extract and display only the relevant fields
        // echo json_encode([
        //     "status" => $data["status"],
        //     "message" => $data["message"],
        //     "order_id" => $data["order_id"],
        //     "remarks" => $data["remarks"]
        // ], JSON_PRETTY_PRINT);
        echo "<script>
          if (window.flutter_inappwebview) {
            // Signal to Flutter if needed
            window.flutter_inappwebview.callHandler('paymentDone', {status: 'completed'});
          }
        
          // In browser: close the tab
          if (window.opener) {
            window.close();
          } else {
            // In Flutter WebView: redirect
            window.location.href = 'https://rejoicebilldesk.in/rjllearning_development/resources/payment_gateway/complete_payment_stop.php';
          }
        </script>";
        exit;

    } catch (Exception $e) {
        echo json_encode(array('status' => 0, 'error' => 'Exception: ' . $e->getMessage()));
        exit;
    }
}

function add()
{
    return 'https://rejoicebilldesk.in/rjllearning_development/resources/payment_gateway/common_response.php';
}
