<?php
include('../includes/session.php');
include('../includes/config.php');

if(isset($_GET['txn_data'])){
    $txxn = $_GET['txn_data'];
    $qor = explode('_',$txxn);
     $orderid = $txxn;
    $phone = $qor['0'];
    $key = "587a85ce847f26a9e7b9652017c09c39";
    $post_data = array("user_token"=>$key,"order_id"=>$orderid);
    
    $curl = curl_init();
	curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://pay.herobro.in/api/check-order-status',
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_POSTFIELDS => json_encode($post_data),
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/json'
		),
	));
	$response = curl_exec($curl);
	curl_close($curl);
   
	$result = json_decode($response, true);
	echo json_encode($result);
	$amt = $result['result']['amount'];
	if ($result['status'] == 'COMPLETED') {
	    
		// Txn Status = 'created', 'scanning', 'success','failure'
            $uddi = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM `wallet` WHERE `txn_id`='".$result['result']['orderId']."'"));
          // if($uddi['status']!='success'){
            if($uddi['amount']==$amt){
              $stss = $result['result']['status'];
		if ($stss=='TXN_SUCCESS') {
		     echo $uddi['status']; 
		    $update_wallet_q = "UPDATE wallet SET status='success' WHERE txn_id='".$result['result']['orderId']."'";
        if (!mysqli_query($ahk_conn, $update_wallet_q)) {
            die("Update wallet status query failed: " . mysqli_error($ahk_conn));
        }else{
            // Update user balance by adding $amt to the existing balance for the given phone number (using prepared statement).
        $update_user_balance_query = "UPDATE users SET balance=balance+? WHERE phone=?";
        $stmt = mysqli_prepare($ahk_conn, $update_user_balance_query);
        mysqli_stmt_bind_param($stmt, "is", $amt, $phone);

        if (!mysqli_stmt_execute($stmt)) {
            die("Update user balance query failed: " . mysqli_error($ahk_conn));
        }else{
            $msg = "*Add Wallet:* Dear User \nTime : ".date("d M Y h:i A")."\nRs. ".$amt." is credited your account.\nThank You for Using Our Service ".$_SERVER['SERVER_NAME'];
           
            //$mbb = $userdata['mobile_no'];
            SendWa($phone,$msg);
            
             echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>'; 
              echo '<script>Swal.fire({
              title: "Done!",
              text: "Payment Successfully Added!",
              icon: "success"
            });</script>';
            echo '<script>window.location.href="wallet.php"</script>';
        }

        // Close the prepared statement.
        mysqli_stmt_close($stmt);

        // Close the database connection.
        mysqli_close($ahk_conn);
        }
		}
	}else{
	    $update_wallet_q = "UPDATE wallet SET status='failed' WHERE txn_id='".$result['result']['orderId']."'";
	    mysqli_query($ahk_conn, $update_wallet_q);
	    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>'; 
              echo '<script>Swal.fire({
              title: "Done!",
              text: "Cheater!",
              icon: "failed"
            });</script>';
            echo '<script>window.location.href="wallet.php"</script>';
	}
          /* }else{
              echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>'; 
              echo '<script>Swal.fire({
              title: "Done!",
              text: "Txn Alredy Done!",
              icon: "failed"
            });</script>';
            echo '<script>window.location.href="wallet.php"</script>'; 
           }*/
	}else{
	    echo 'Somthing wrong';
	}
}
?>