<?php
session_start();
require 'db-connection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Login method
    if (isset($_POST['admin-login']) && $_POST['admin-login'] == true) {
        if (isset($_POST['userEmail']) && isset($_POST['userPassword'])) {
            $email = $_POST['userEmail'];
            $password = $_POST['userPassword'];
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $response['message'] = 'Invalid email format.';
                echo json_encode($response);
                exit();
            }
            $query = "SELECT id, u_email,u_name, u_password FROM tbl_admin WHERE u_email='$email' and u_password='$password' ";
            $result = mysqli_query($link, $query) or die("Error " . mysqli_error($link));
            if ($row = mysqli_fetch_assoc($result)) {
                $_SESSION['admin_id'] = $row['id'];
                $_SESSION['admin_email'] = $row['u_email'];
                $_SESSION['admin_name'] = $row['u_name'];

                // echo "<pre>";
                // print_r($_SESSION);
                $response['status'] = true;
                $response['message'] = 'Login successful.';
            } else {
                $response['status'] = false;
                $response['message'] = 'Invalid email or password.';
            }
            // Output response
            echo json_encode($response);
        }
    }

    //logout
    if (isset($_POST['admin-logout']) && $_POST['admin-logout'] == true) {
        session_destroy();
        header("Location: index.php");
    }


    if (isset($_POST['fontEnd_userDataSave']) && $_POST['fontEnd_userDataSave'] == true) {
        $user_name = $_POST['user_name'] ?? '';
        $form_name = $_POST['form_name'] ?? '';
        $selected_package = $_POST['slected_package'] ?? ''; // Corrected typo `slected_package` -> `selected_package`
        $user_phone = $_POST['user_phone'] ?? '';
        if (!empty($user_name) && !empty($user_phone)) {
            // Escape the input data to prevent SQL injection
            $user_name = mysqli_real_escape_string($link, $user_name);
            $form_name = mysqli_real_escape_string($link, $form_name);
            $selected_package = mysqli_real_escape_string($link, $selected_package);
            $user_phone = mysqli_real_escape_string($link, $user_phone);
            $select_query = "SELECT id, mobile FROM tbl_user WHERE mobile='$user_phone'";
            $get_user_result = mysqli_query($link, $select_query);
            $data_user = mysqli_fetch_assoc($get_user_result);
            if ($data_user) {
                $last_id = $data_user['id'];
                $update_query = "UPDATE tbl_user SET `name`='$user_name', `status`='$form_name' WHERE `id`='$last_id'";
                $update_result = mysqli_query($link, $update_query);
                if (!$update_result) {
                    $result = [
                        'status' => false,
                        'message' => 'Failed to update user data.'
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }
            } else {
                $users_query = "INSERT INTO `tbl_user` (`name`, `mobile`, `status`) VALUES ('$user_name', '$user_phone', '$form_name')";
                $run_users = mysqli_query($link, $users_query);
                if (!$run_users) {
                    $result = [
                        'status' => false,
                        'message' => 'Error inserting user data: ' . mysqli_error($link)
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }
                $last_id = mysqli_insert_id($link);
            }
            $check_user = "SELECT * FROM `tbl_order` WHERE `user_id`='$last_id' AND `created_at` > NOW() - INTERVAL 24 HOUR";
            $check_user_result = mysqli_query($link, $check_user);
            $data_order = mysqli_fetch_assoc($check_user_result);
            if ($data_order) {
                // update
                $result = [
                    'status' => true,
                    'message' => 'User data updated successfully.',
                    'error_message' => 'You have already submitted data today. Our team will get in touch with you shortly.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            } else {
                // Insert order data
                $order_query = "INSERT INTO `tbl_order` (`user_id`, `product_name`, `status`) VALUES ('$last_id', '$selected_package', '$form_name')";
                $run_order = mysqli_query($link, $order_query);
                if (!$run_order) {
                    $result = [
                        'status' => false,
                        'message' => 'Failed to save order data.'
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }

                // Determine the response message based on form status
                $return_message = ($form_name == 1) ? 'Thank you for your enquiry. Our team will get in touch with you shortly.' : 'Enquiry sent successfully.';

                // Set session variables for the user
                $_SESSION['user_id'] = $last_id;
                $_SESSION['user_name'] = $user_name;
                $_SESSION['user_selected_package'] = $selected_package;
                $_SESSION['user_phone'] = $user_phone;
                $_SESSION['user_status'] = true;

                $result = [
                    'status' => true,
                    'message' => $return_message
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
        } else {
            $result = [
                'status' => false,
                'message' => 'Invalid input. Name and phone number are required.'
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        }
    }
    if (isset($_POST['GetAddressbypin']) && $_POST['GetAddressbypin'] == true) {
        $pincode = $_POST['pincode'];

        // Validate the pincode: non-empty, 6 digits, numeric
        if (empty($pincode) || strlen($pincode) != 6 || !ctype_digit($pincode)) {
            echo json_encode(['status' => false, 'message' => 'Invalid Pincode format']);
            exit();
        }

        // API URL to fetch data
        $apiUrl = 'http://postalpincode.in/api/pincode/' . $pincode;
        $apiResponse = @file_get_contents($apiUrl); // @ to suppress warnings in case of errors

        // Handle case when the API request fails
        if ($apiResponse === FALSE) {
            echo json_encode(['status' => false, 'message' => 'Unable to fetch data from API']);
            exit();
        }

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

        // Check if PostOffice data exists in the API response
        if (isset($data['PostOffice']) && !empty($data['PostOffice'][0])) {
            $postOffice = $data['PostOffice'][0]; // Get the first PostOffice entry
            $arr = [
                'state' => $postOffice['State'],
                'city' => $postOffice['District']
            ];
            echo json_encode(['status' => true, 'data' => $arr]); // Send the city and state in response
        } else {
            echo json_encode(['status' => false, 'message' => 'Invalid Pincode']); // Invalid pincode response
        }
    }
    if (isset($_POST['submit_enquery']) && $_POST['submit_enquery'] == true) {
        $user_name = $_POST['user_name'] ?? '';
        $form_name = $_POST['form_name'] ?? '';
        $selected_package = $_POST['slected_package'] ?? '';
        $user_phone = $_POST['user_phone'] ?? '';
        if (!empty($user_name) && !empty($user_phone)) {
            // Escape the input data to prevent SQL injection
            $user_name = mysqli_real_escape_string($link, $user_name);
            $form_name = mysqli_real_escape_string($link, $form_name);
            $selected_package = mysqli_real_escape_string($link, $selected_package);
            $user_phone = mysqli_real_escape_string($link, $user_phone);

            // Check if user already exists
            $select_query = "SELECT id, mobile FROM tbl_user WHERE mobile='$user_phone'";
            $get_user_result = mysqli_query($link, $select_query);
            $data_user = mysqli_fetch_assoc($get_user_result);
            if ($data_user) {
                $last_id = $data_user['id'];
                $update_query = "UPDATE tbl_user SET `name`='$user_name', `status`='$form_name' ,`created_at` = CURRENT_TIMESTAMP() WHERE `id`='$last_id'";
                $update_result = mysqli_query($link, $update_query);
                if (!$update_result) {
                    $result = [
                        'status' => false,
                        'message' => 'Failed to update user data.'
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }
            } else {
                $users_query = "INSERT INTO `tbl_user` (`name`, `mobile`, `status`) VALUES ('$user_name', '$user_phone', '$form_name')";
                $run_users = mysqli_query($link, $users_query);
                if (!$run_users) {
                    $result = [
                        'status' => false,
                        'message' => 'Error inserting user data: ' . mysqli_error($link)
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }
                $last_id = mysqli_insert_id($link);
            }
            $check_user = "SELECT * FROM `tbl_order` WHERE `user_id`='$last_id' AND `created_at` > NOW() - INTERVAL 24 HOUR";
            $check_user_result = mysqli_query($link, $check_user);
            $data_order = mysqli_fetch_assoc($check_user_result);
            if ($data_order) {
                // update
                $_SESSION['user_id'] = $last_id;
                $_SESSION['user_name'] = $user_name;
                $_SESSION['user_selected_package'] = $selected_package;
                $_SESSION['user_phone'] = $user_phone;
                $_SESSION['user_status'] = true;
                $result = [
                    'status' => true,
                    'message' => 'Thank you for your enquiry. Our team will get in touch with you shortly.',
                    'error_message' => 'You have already submitted data today. Our team will get in touch with you shortly.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            } else {
                // Insert order data
                $order_query = "INSERT INTO `tbl_order` (`user_id`, `product_name`, `status`) VALUES ('$last_id', '$selected_package', '$form_name')";
                $run_order = mysqli_query($link, $order_query);
                if (!$run_order) {
                    $result = [
                        'status' => false,
                        'message' => 'Failed to save order data.'
                    ];
                    header('Content-Type: application/json');
                    echo json_encode($result);
                    exit;
                }
                $return_message = ($form_name == 1) ? 'Thank you for your enquiry. Our team will get in touch with you shortly.' : 'Enquiry sent successfully.';
                $_SESSION['user_id'] = $last_id;
                $_SESSION['user_name'] = $user_name;
                $_SESSION['user_selected_package'] = $selected_package;
                $_SESSION['user_phone'] = $user_phone;
                $_SESSION['user_status'] = true;
                $result = [
                    'status' => true,
                    'message' => $return_message
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
        } else {
            $result = [
                'status' => false,
                'message' => 'Invalid input. Name and phone number are required.'
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        }
    }
    function generateOTP()
    {
        return rand(1000, 9999); // Generate a random 4-digit OTP
    }
    // OTP Functions

    function sendOTP($mobile, $otp)
    {
        $username = 'ramhealthcare';
        $api_key = '*VF4OT$anzQ(lp';
        $sender = 'KYASRI';
        $message = urlencode("Your Mobile Verification OTP is $otp, Thanks Kaya shree Ayurveda");
        $route = 'T';
        $entity_id = '1701173467821572189';
        $content_id = '1707173469943285496';
        $url = "http://shudhsms.in/sendsms_new.php?username=$username&api_key=$api_key&sender=$sender&mobile=$mobile&message=$message&route=$route&entity_id=$entity_id&content_id=$content_id";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    function saveOTP($mobile, $otp, $link)
    {
        $expiry_time = date('Y-m-d H:i:s', strtotime('+5 minutes')); // OTP valid for 5 minutes
        $stmt = $link->prepare("UPDATE `tbl_user` SET otp = ?, expiry_time = ? WHERE `mobile` = ?");
        $stmt->bind_param('sss', $otp, $expiry_time, $mobile);

        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }
    // One-time order processing
    if (isset($_POST['order_now']) && $_POST['order_now'] == true) {
        if (!isset($_SESSION['user_id'])) {
            $result = [
                'status' => false,
                'message' => 'You are not a valid user. Please reload the page and try again.'
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        } else {
            // Fetch and sanitize POST data
            $user_id = $_SESSION['user_id'];
            $first_name = mysqli_real_escape_string($link, trim($_POST['first_name']));
            $zip_code = (int)$_POST['zip_code'];
            $address1 = mysqli_real_escape_string($link, trim($_POST['address1']));
            $address2 = mysqli_real_escape_string($link, trim($_POST['address2']));
            $city = mysqli_real_escape_string($link, trim($_POST['city']));
            $state = mysqli_real_escape_string($link, trim($_POST['state']));
            $email = mysqli_real_escape_string($link, trim($_POST['email']));
            $phone = mysqli_real_escape_string($link, trim($_POST['phone']));
            $payment_method = mysqli_real_escape_string($link, trim($_POST['payment_method']));
            $product_name = mysqli_real_escape_string($link, trim($_POST['product_name']));
            $product_price = (int)$_POST['product_price'];
            $product_discount_promo = (int)$_POST['product_discount_promo'];
            $payment_discount = (int)$_POST['payment_discount'];
            $total_amount = (int)$_POST['total_amount'];
            // Update user details
            $update_user_query = "UPDATE `tbl_user` SET 
                                  `name` = '$first_name', 
                                  `zip_code` = '$zip_code',
                                  `house_no` = '$address1',
                                  `landmark` = '$address2',
                                  `city` = '$city',
                                  `status` = 4,
                                  `state` = '$state',
                                  `email` = '$email',
                                  `mobile` = '$phone' 
                                  WHERE id = '$user_id'";
            if (!mysqli_query($link, $update_user_query)) {
                $result = [
                    'status' => false,
                    'message' => 'Error updating user details. Please try again later.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
            $payment_date = date('Y-m-d H:i:s');
            $order_status = ($payment_method === 'online') ? '5' : '4';
            $prefix = strtoupper(substr('H' . $state, 0, 3));
            $random_letters = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 4);
            $random_digits = rand(1000, 9999);
            $order_id = $prefix . $random_letters . $random_digits;
            // Corrected SQL query for inserting the order

            // $update_product = "UPDATE `tbl_order` SET `user_id`=$user_id where user_id=$user_id";
            // $insert_order_query = "INSERT INTO `tbl_order` (`user_id`, `order_id`, `payment_method`, `product_name`, `product_price`, 
            //                                               `product_discount_promo`, `payment_discount`, `total_amount`, `status`, `created_at`) 
            //                        VALUES ('$user_id', '$order_id', '$payment_method', '$product_name', '$product_price', 
            //                                '$product_discount_promo', '$payment_discount', '$total_amount', '$order_status', '$payment_date')";
            $update_order_query = "UPDATE `tbl_order` 
                                                SET `user_id` = '$user_id', 
                                                    `order_id` = '$order_id', 
                                                    `payment_method` = '$payment_method', 
                                                    `product_name` = '$product_name', 
                                                    `product_price` = '$product_price', 
                                                    `product_discount_promo` = '$product_discount_promo', 
                                                    `payment_discount` = '$payment_discount', 
                                                    `total_amount` = '$total_amount', 
                                                    `status` = '$order_status', 
                                                    `created_at` = '$payment_date' 
                                                WHERE `user_id` = '$user_id'";

            if (mysqli_query($link, $update_order_query)) {
                $order_id = mysqli_insert_id($link);
                $customer_address = $address1 . ' ' . $address2 . ' ' . $city . ' ' . $state . ' ' . $zip_code;
                $otp = generateOTP();
                if (sendOTP($phone, $otp)) {
                    if (saveOTP($phone, $otp, $link)) {
                        $result = [
                            'status' => true,
                            'message' => 'OTP has been successfully sent to your mobile number.'
                        ];
                    } else {
                        $result = [
                            'status' => false,
                            'message' => 'Failed to save OTP in the database.'
                        ];
                    }
                } else {
                    $result = [
                        'status' => false,
                        'message' => 'Failed to send OTP.'
                    ];
                }
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            } else {
                $result = [
                    'status' => false,
                    'message' => 'Error placing your order. Please try again later.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
        }
    }
    // Verify OTP
    if (isset($_POST['submit_otp']) && $_POST['submit_otp'] == true) {
        $otp = $_POST['otp'];
        $mobile = $_SESSION['user_phone'];
        $stmt = $link->prepare("SELECT * FROM `tbl_user` WHERE mobile = ? AND otp = ?");
        $stmt->bind_param('ss', $mobile, $otp);
        $stmt->execute();
        $result_user = $stmt->get_result();
        $row_user = $result_user->fetch_assoc();
        if (!empty($row_user['id'])) {
            $stmt_update = $link->prepare("UPDATE `tbl_user` SET otp = ?, expiry_time = ?, otp_status = ? WHERE `mobile` = ?");
            $null = null;
            $otp_status = 1;
            $stmt_update->bind_param('ssis', $null, $null, $otp_status, $mobile);
            $stmt_update->execute();
            $result = [
                'status' => true,
                'message' => 'Your mobile number has been successfully verified.',
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        } else {
            $result = [
                'status' => false,
                'message' => 'OTP not Verified.'
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        }
    }
    //resendOtpBtn
    if (isset($_POST['resendOtpBtn']) && $_POST['resendOtpBtn'] == true) {
        $phone = $_SESSION['user_phone'];
        $otp = generateOTP();
        if (sendOTP($phone, $otp)) {
            if (saveOTP($phone, $otp, $link)) {
                $result = [
                    'status' => true,
                    'message' => 'OTP has been successfully Resent to your mobile number.'
                ];
            } else {
                $result = [
                    'status' => false,
                    'message' => 'Failed to save OTP in the database.'
                ];
            }
        } else {
            $result = [
                'status' => false,
                'message' => 'Failed to send OTP.'
            ];
        }
        header('Content-Type: application/json');
        echo json_encode($result);
        exit;
    }

    //buynowbtn
    if (isset($_POST['buynowbtn']) && $_POST['buynowbtn'] == true) {
        if (!isset($_SESSION['user_id'])) {
            $result = [
                'status' => false,
                'message' => 'You are not a valid user. Please reload the page and try again.'
            ];
            header('Content-Type: application/json');
            echo json_encode($result);
            exit;
        } else {
            // Fetch and sanitize POST data
            $user_id = $_SESSION['user_id'];
            $first_name = mysqli_real_escape_string($link, trim($_POST['first_name']));
            $zip_code = (int)$_POST['zip_code'];
            $address1 = mysqli_real_escape_string($link, trim($_POST['address1']));
            $address2 = mysqli_real_escape_string($link, trim($_POST['address2']));
            $city = mysqli_real_escape_string($link, trim($_POST['city']));
            $state = mysqli_real_escape_string($link, trim($_POST['state']));
            $email = mysqli_real_escape_string($link, trim($_POST['email']));
            $phone = mysqli_real_escape_string($link, trim($_POST['phone']));
            $payment_method = mysqli_real_escape_string($link, trim($_POST['payment_method']));
            $product_name = mysqli_real_escape_string($link, trim($_POST['product_name']));
            $payment_res = mysqli_real_escape_string($link, trim(isset($_POST['payment_res']) ? $_POST['payment_res'] : null));
            $product_price = (int)$_POST['product_price'];
            $product_discount_promo = (int)$_POST['product_discount_promo'];
            $payment_discount = (int)$_POST['payment_discount'];
            $total_amount = (int)$_POST['total_amount'];
            // Update user details
            $update_user_query = "UPDATE `tbl_user` SET 
                                  `name` = '$first_name', 
                                  `zip_code` = '$zip_code',
                                  `house_no` = '$address1',
                                  `landmark` = '$address2',
                                  `city` = '$city',
                                  `status` = 4,
                                  `state` = '$state',
                                  `email` = '$email',
                                  `mobile` = '$phone' 
                                  WHERE id = '$user_id'";
            if (!mysqli_query($link, $update_user_query)) {
                $result = [
                    'status' => false,
                    'message' => 'Error updating user details. Please try again later.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
            $payment_date = date('Y-m-d H:i:s');
            $order_status = ($payment_method === 'online') ? '5' : '4';
            $prefix = strtoupper(substr('H' . $state, 0, 3));
            $random_letters = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 4);
            $random_digits = rand(1000, 9999);
            $order_id = $prefix . $random_letters . $random_digits;
            // Corrected SQL query for inserting the order
            $update_order_query = "UPDATE `tbl_order` 
                       SET `user_id` = '$user_id', 
                           `order_id` = '$order_id', 
                           `payment_method` = '$payment_method', 
                           `product_name` = '$product_name', 
                           `product_price` = '$product_price', 
                           `product_discount_promo` = '$product_discount_promo', 
                           `payment_discount` = '$payment_discount', 
                           `total_amount` = '$total_amount', 
                           `status` = '$order_status', 
                           `paymentgetway_return` = '$payment_res', 
                           `created_at` = '$payment_date' 
                       WHERE `user_id` = '$user_id'";
            if (mysqli_query($link, $update_order_query)) {
                //get product id 
                $stmt = $link->prepare("SELECT `id` FROM `tbl_order` WHERE `user_id` = ?");
                $stmt->bind_param('s', $user_id);
                $stmt->execute();
                $result_user = $stmt->get_result();
                $row_user = $result_user->fetch_assoc();
                $order_id = $row_user['id'];
                session_unset();
                $result = [
                    'status' => true,
                    'message' => 'Thank you for placing your order! Our team will contact you shortly and send a message to your WhatsApp for further updates.',
                    'url' => 'thankyou.php?product=' . $order_id
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
                // $customer_address = $address1 . ' ' . $address2 . ' ' . $city . ' ' . $state . ' ' . $zip_code;
                // if ($payment_method === 'online') {
                //     // payment_getway($total_amount, $order_id, $first_name, $email, $phone, $customer_address);
                // } else {
                //     session_unset();
                //     $result = [
                //         'status' => true,
                //         'message' => 'Thank you for placing your order! Our team will contact you shortly and send a message to your WhatsApp for further updates.',
                //         'url' => 'thankyou.php?product=' . $order_id
                //     ];
                //     header('Content-Type: application/json');
                //     echo json_encode($result);
                //     exit;
                // }
            } else {
                $result = [
                    'status' => false,
                    'message' => 'Error placing your order. Please try again later.'
                ];
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            }
        }
    }

    function payment_getway($amount, $order_id, $customer_name, $customer_email, $customer_phone, $customer_address)
    {
        require 'db-connection.php';
        $merchant_id = 'YOUR_MERCHANT_ID';
        $api_key = 'YOUR_API_KEY';
        $api_secret = 'YOUR_API_SECRET';
        $data = array(
            'amount' => $amount,
            'order_id' => $order_id,
            'customer_name' => $customer_name,
            'customer_email' => $customer_email,
            'customer_phone' => $customer_phone,
            'customer_address' => $customer_address,
            'merchant_id' => $merchant_id,
            'api_key' => $api_key,
            'api_secret' => $api_secret
        );
        $payment_link = generate_payment_link($data);
        if ($payment_link) {
            $update_payment_query = "UPDATE `tbl_order` SET `payment_link` = '$payment_link' WHERE `id` = '$order_id'";
            mysqli_query($link, $update_payment_query);
            header('Location: ' . $payment_link);
            exit;
        } else {
            echo "Failed to generate payment link. Please try again.";
        }
    }

    function generate_payment_link($data)
    {
        $url = 'https://api.easebuzz.in/v1/payment-link';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        $response = curl_exec($curl);
        if ($response === false) {
            echo 'cURL Error: ' . curl_error($curl);
            curl_close($curl);
            return false;
        }
        curl_close($curl);
        $response_data = json_decode($response, true);
        if (isset($response_data['payment_link'])) {
            return $response_data['payment_link'];
        } else {
            // Handle API response error
            echo 'Error in response: ' . json_encode($response_data);
            return false;
        }
    }
}
