<?php
if (!defined('ADDFUNDS')) {
    http_response_code(404);
    die();
}

// Retrieve Cashfree API details from methodExtras
$AppID = $methodExtras["AppID"]; // Cashfree App ID (x-client-id)
$SecretKey = $methodExtras["SecretKey"]; // Cashfree Secret Key (x-secret-key)

// Check for empty API credentials
if (empty($AppID) || empty($SecretKey)) {
    errorExit("API credentials (AppID or SecretKey) are missing.");
}

// Generate unique Order ID
$ORDER_ID = uniqid("CF_"); 

// Callback URL for Cashfree to redirect after payment
$REDIRECT_URL = site_url("payment/" . $methodCallback);

// Payment data structure
$paymentData = [
    "order_id" => $ORDER_ID,
    "order_amount" => $paymentAmount,
    "order_currency" => $methodCurrency,
    "customer_details" => [
        "customer_id" => $user["client_id"],
        "customer_email" => $user["email"],
        "customer_phone" => $user["telephone"],
    ],
    "order_meta" => [
        "return_url" => $REDIRECT_URL . "?order_id={$ORDER_ID}&cf_id={order_id}",
    ],
];

// API call to Cashfree to initiate payment
$ch = curl_init("https://api.cashfree.com/pg/orders");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'x-client-id: ' .$AppID,
    'x-secret-key: ' .$SecretKey,  // Ensure no extra spaces here
]);

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

// Check if cURL failed
if ($response === false) {
    $error = curl_error($ch);
    curl_close($ch);
    errorExit("Curl error: " . $error);
}

curl_close($ch);

// Log the raw response for debugging
file_put_contents('cashfree_api_response.log', print_r($response, true));

// Decode the JSON response
$response_array = json_decode($response, true);

// Log the decoded response for further debugging
file_put_contents('cashfree_api_response_decoded.log', print_r($response_array, true));

// Check if the payment link is available
if (isset($response_array["payment_link"])) {
    // Redirect user to Cashfree payment page
    $redirectForm = '<script>window.location.href = "' . $response_array["payment_link"] . '";</script>';
    $response = [
        "success" => true,
        "message" => "Redirecting to Cashfree...",
        "content" => $redirectForm,
    ];
    echo json_encode($response);
} else {
    // Log the error details for debugging
    if (isset($response_array["message"])) {
        $errorMessage = $response_array["message"];
    } else {
        $errorMessage = "Unknown error.";
    }
    errorExit("Failed to initiate payment. Error: " . $errorMessage);
}
?>
