<?php
// Get the amount and username from the URL parameters
$amount = isset($_GET['amount']) ? $_GET['amount'] : 0;
$username = isset($_GET['username']) ? $_GET['username'] : 'unknown_user';

// Initialize cURL request
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'http://api.kunchhunlichhean.org/khqr/create?amount=' . $amount . '&bakongid=chenlong_chea@aclb&merchantname=LONGGSMM',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);

// Decode the API response
$responseData = json_decode($response, true);

// Check if the necessary fields are available in the response
if (isset($responseData['qr'], $responseData['md5'], $responseData['tran'])) {
    // Database connection
    $servername = "localhost"; // Your DB server name
    $username_db = "templesm_longsmm";      // Your DB username
    $password_db = "templesm_longsmm";          // Your DB password
    $dbname = "templesm_longsmm";  // Your database name
    // Create connection
    $conn = new mysqli($servername, $username_db, $password_db, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // Prepare and bind the SQL statement
    $stmt = $conn->prepare("INSERT INTO payment_qrcode (tran_id, username, amount, qr, md5, payment_status, topup_status, create_at) VALUES (?, ?, ?, ?, ?, 'PENDING', 'PENDING', NOW())");
    $stmt->bind_param("ssdss", $tran_id, $username_param, $amount_param, $qr, $md5);

    // Assign values to the parameters
    $tran_id = $responseData['tran'];
    $username_param = $username;
    $amount_param = (float)$amount; // Cast amount to a float
    $qr = $responseData['qr'];
    $md5 = $responseData['md5'];

    // Execute the statement
    if ($stmt->execute()) {
        // Redirect to the checkout page after a successful insertion
        header("Location: https://longg-smm.com/payment/checkout.php?tran_id=" . urlencode($tran_id));
        exit(); // Ensure that no further code is executed after the redirection
    } else {
        echo "Error: " . $stmt->error;
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
} else {
    echo "Invalid API response";
}
?>
