<?php
// Replace with your real KiliCow Pay Merchant Key
$merchant_key = "mer_demo123";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount   = $_POST['amount'];
    $currency = "pkr"; // use PKR
    $txn_id   = $_POST['txn_id'];

    // Prepare request
    $postData = http_build_query([
        'merchant_key' => $merchant_key,
        'amount'       => $amount,
        'currency'     => $currency,
        'txn_id'       => $txn_id
    ]);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://kilicow.rdnslvhost.in.net/payin/order");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    curl_close($ch);

    // Debug: show raw response if needed
    // echo "<pre>$response</pre>";

    $result = json_decode($response, true);

    if ($result && isset($result['status']) && $result['status'] === 'redirect') {
        header("Location: " . $result['payment_url']);
        exit;
    } else {
        $error = $result['message'] ?? "Unknown error from KiliCow Pay";
        echo "<h3 style='color:red;'>Payment Error: $error</h3>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>KiliCow Pay Order (PKR)</title>
</head>
<body>
    <h2>Create Order & Pay (PKR)</h2>
    <form method="POST">
        <label>Amount (PKR):</label><br>
        <input type="text" name="amount" placeholder="500.00" required><br><br>

        <label>Transaction ID:</label><br>
        <input type="text" name="txn_id" value="<?php echo 'ORD'.time(); ?>" required><br><br>

        <button type="submit">Pay Now</button>
    </form>
</body>
</html>