<?php 
ob_start();
// ajax.php
// handles ajax requests
// require_once("phpmailer/class.phpmailer.php");
require_once("../../config.php");
require_once("../functions.php");
require_once("../query-functions.php");
require_once("../table-functions.php");

spl_autoload_register(function($class_name) {
	$file = "../classes/class-".$class_name.".php";
	if(file_exists($file))
		include $file;
});

require_once("../../contents/plugins/plugins.php");
require_once("../pages/templates.php");
$plugins = new plugins();
$plugins->load();

$session = Session::getInstance();


if ($_SERVER["REQUEST_METHOD"] == "POST") :

	if(isset($_POST['action'])){
		$response = array();
		$args = $_POST;
		unset($args['action']);
		$user = new user;
		$post = new post;
		$support = new support;

		switch ($_POST['action']) {
			case 'login':
				$credentials = $args;
				$result = $user->user_login($credentials['email'], $credentials['password']);
				if($result == 1) {
					$ck = "No";
					if(isset($credentials['remember_me'])) {
						ob_get_clean();
						setcookie("user_login", $session->id, time()+ (10 * 365 * 24 * 60 * 60), "/");
					}
					$response['url'] = get_sign_in_url($credentials['email']);
					$response['error'] = 0;
					$response['msg'] = 'Congratulations, You have signed in successfully. Wait to be redirected.';
					echo json_encode($response);
					exit();
				} else if ($result == -1) {
					$response['error'] = 1;
					$response['msg'] = 'Sorry, there seems to be a problem and you cannot login at the moment. Contact the admin through '.implode(", ", get_option("company_phone")).' or write support through '.get_option("company_email").' if you want to restore your account';
					echo json_encode($response);
					exit();
				} else {
					$site_binding = new site_binding;
					if($args = $site_binding->pull_credentials($credentials['email'], $credentials['password'])) {
						$args = (array) $args;
						$args['password'] = $credentials['password'];
						$response = $user->register_user($args);
					} else {
						$response['error'] = 1;
						$response['msg'] = 'Username or password is incorrect';
					}
					echo json_encode($response);
					exit();
				}
				break;

			case 'forget':
				$usermeta = get_user_meta($args['username']);
				if($usermeta) {
					$supportObj = generate_otp($usermeta['id']);
					$response['user_id'] = $usermeta['id'];
					if(!$supportObj->error && $support->sms_response == "OK") {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your email and phone number. Enter the pin in the field above. Pin expires in 15 minutes';
					} else if(!$supportObj->error) {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your email. Enter the pin in the field above. Pin expires in 15 minutes';
					} else if($support->sms_response == "OK") {
						$response['error'] = 0;
						$response['msg'] = 'One time pin has been generated and sent to your phone number. Enter the pin in the field above. Pin expires in 15 minutes';
					} else {
						$response['error'] = 1;
						$response['msg'] = 'Sorry, email and text message could not be sent. Password could not be retrived';
					}
				} else {
					$response['error'] = 1;
					$response['msg'] = 'Username/Email do not match any of our records';
				}
				echo json_encode($response);
				exit();
				break;

			case 'verifyotp':
				$verify = verifyotp($args['otp'], $args['user_id']);
				if($verify) {
					$authe = SHA1(rand(1000, 9999));
					$loggon_key = SHA1(time(). SALT);
					$user->update_user_meta($args['user_id'], array('loggon_key' => $loggon_key, 'authe' => $authe));
					$session->id = $args['user_id'];
					$session->key = $loggon_key;
					$response['authe'] = $authe;
					$response['error'] = 0;
					$response['msg'] = 'Thank you for verifying your account ownership. You can now change your password.';
				} else {
					$response['error'] = 1;
					$response['msg'] = 'You entered a wrong pin';
				}
				echo json_encode($response);
				exit();
				break;

			case 'get_site_logo':
				$response['logo'] = get_option("company-logo");
				$response['desc'] = get_option("company_name");
				echo json_encode($response);
				exit();
				break;

			case 'software_set_up':
				$company_logo = $args['imagebase64-company_logo'];
				$folder = 'customization';
				$path = ABSPATH.UPLOADFOLDER.'/'.$folder.'/company_logo/';
				if($company_logo != '') {
					$res = upload_base64_image($company_logo, 'company_logo', $path, $_FILES);
					if($res[0] == 1) {
						update_option('company-logo', str_replace(ABSPATH, '', $res[1]));
					} else {
						$response['error_msg'] = "logo image not uploaded";
					}
				}
				$company_icon = $args['imagebase64-company_icon'];
				$path = ABSPATH.UPLOADFOLDER.'/'.$folder.'/company_icon/';
				if($company_icon != '') {
					$res = upload_base64_image($company_icon, 'company_icon', $path, $_FILES);
					if($res[0] == 1) {
						update_option('company-icon', str_replace(ABSPATH, '', $res[1]));
					} else {
						$response['error_msg'] = "icon image not uploaded";
					}
				}
				
				// update_option('logo_width', $args['logo_width']);
				// update_option('logo_height', $args['logo_height']);
				// $send_emails = ($args['send_emails'] == 1) ? 1 : 0;
				update_option('send_emails', $args['send_emails'] ?? 0);
				update_option('mailer', $args['mailer']);
				update_option('smtp_username', $args['smtp_username']);
				update_option('smtp_password', $args['smtp_password']);
				update_option('smtp_host', $args['smtp_host']);
				update_option('smtp_port', $args['smtp_port']);
				update_option('smtp_email', $args['smtp_email']);
				update_option('email_template_id', $args['email_template_id']);
				update_option('smtp_name', $args['smtp_name']);
				update_option('home_url', $args['home_url']);
				update_option('footer_text', $args['footer_text']);
				update_option('footer_link', $args['footer_link']);
				update_option('login_user', $args['login_user']);
				update_option('login_pass', $args['login_pass']);
				update_option('current_theme', $args['current_theme']);
				update_option('company_name', $args['company_name']);
				update_option('company_email', $args['company_email']);
				update_option('company_motto', $args['company_motto']);
				update_option('company_address', $args['company_address']);
				update_option('company_website', $args['company_website']);
				update_option('company_phone', explode(',', $args['company_phone']));
				update_option('role_names', explode('\r\n', sanitize($args['role_names'])));
				update_option('dz_default_max_files', $args['dz_default_max_files']);
				update_option('excel_password', $args['excel_password']);
				update_option('password_rules', $args['password_rules']);
				update_option('min_password_length', $args['min_password_length']);
				update_option('primary_color', $args['primary_color']);
				update_option('secondary_color', $args['secondary_color']);
				update_option('landing_page', $args['landing_page']);
				// section database
				if(current_user_can("update_software")) :
					update_option('exempt_users', explode(',', $args['exempt_users']));
					// $section_database = ($args['section_database'] == 1) ? 1 : 0;
					update_option('section_database', $args['section_database'] ?? 0);
					update_option('section_field', strtolower($args['section_field']));
					// $authenticate_server = ($args['authenticate_server'] == 1) ? 1 : 0;
					update_option('authenticate_server', $args['authenticate_server'] ?? 0);
				endif;
				// $browser_update = ($args['browser_update'] == 1) ? 1 : 0;
				update_option('browser_update', $args['browser_update'] ?? 0);
				// section database
				refresh_software();
				do_action('save_more_settings_field', $args);
				$response['error'] = 0;
				$response['msg'] = 'Settings updated successfully';
				echo json_encode($response);
				exit();
				break;

			case 'get_db_sections':
				$all = (isset($args['all'])) ? $args['all'] : true;
				$response['deactivate'] = base64_encode("deactivate_post");
				$response['activate'] = base64_encode("activate_post");
				$response['sections'] = get_db_sections($all);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'add_db_section':
				$section_field = get_option("section_field");
				if(!db_section_field_name_is_valid($section_field)) {
					$response['error'] = 1;
					$response['msg'] = 'Please set up the section field first. If not empty, use a unique field name';
					echo json_encode($response);
					exit();
				}
				if(db_post_unique(["type" => $section_field, 'section_name' => $args['section_name']])) {
					$response['error'] = 1;
					$response['msg'] = 'Database section name is not unique';
					echo json_encode($response);
					exit();
				}
				$args['type'] = $section_field;
				$args['status'] = 'active';
				$post->add_post($args);
				$response['msg'] = "Database Section added successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'edit_db_section':
				$section_field = get_option("section_field");
				if(!db_section_field_name_is_valid($section_field)) {
					$response['error'] = 1;
					$response['msg'] = 'Please set up the section field first. If not empty, use a unique field name';
					echo json_encode($response);
					exit();
				}
				if($existing = db_post_unique(["type" => $section_field, 'section_name' => $args['section_name']])) {
					if($existing['id'] != $args['id']) {
						$response['error'] = 1;
						$response['msg'] = 'Database section name is not unique';
						echo json_encode($response);
						exit();
					}
				}
				$post->update_post_meta($args['id'], $args);
				$response['msg'] = "Database Section updated successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'registration':
				unset($args['c_password']);
				$args = apply_filters("registration_args_filters", $args);
				$response = $user->register_user($args);
				echo json_encode($response);
				exit();
				break;


			case 'add_user':
				unset($args['c_password']);
				$args = apply_filters("registration_args_filters", $args);
				$response = $user->register_user($args);
				echo json_encode($response);
				exit();
				break;


			case 'edit_profile':
				$args = apply_filters("edit_profile_args_filters", $args);

				if(isset($args['country_code'])) {
					$args['phone'] = internationalize_phone_number($args['phone'], $args['country_code']);
				} else $args['phone'] = internationalize_phone_number($args['phone']);

				$profile_picture = $args['imagebase64-profile_picture'];
				$response['args'] = $args;
				unset($args['profile_picture']);
				unset($args['imagebase64-profile_picture']);
				$folder = $args['id'];

				$path = '../../'.UPLOADFOLDER.'/'.$folder.'/profile_picture/';
				if($profile_picture != '') {
					$res = upload_base64_image($profile_picture, 'profile_picture', $path, $_FILES);
					$response['res'] = $res;
					if($res[0] == 1) {
						$args['profile_picture'] = substr($res[1], 6);
					} else {
						$response['error_msg'] = "image not uploaded";
					}
				}
				$response['msg'] = 'User data updated successfully';
				if(!current_user_can('edit_own_profile')) {
					$args = ['id' => $args['id'], 'profile_picture' => $args['profile_picture']];
					$response['msg'] = 'Sorry you cannot edit your information. Only your profile picture can be updated';
				}
				$result = $user->update_user_meta($args['id'], $args);
				if($result) {
					$response['error'] = 0;	
				}
				else {
					$response['msg'] = 'Nothing changed';
					$response['error'] = 1;	
				}
				echo json_encode($response);
				exit();
				break;

			case 'trumbowyg_upload':
				$ds = "/";
				$folder = UPLOADFOLDER.$ds.'ImageLibrary'.$ds.date('M-Y', time()).$ds.$session->id.$ds.$args['ref'];
				$storeFolder = '..'.$ds.'..'.$ds.$folder;

				if (!file_exists($storeFolder)) {
	                mkdir($storeFolder, 0777, true);
	            }
				if (!empty($_FILES)) {
				    $file_title = $_FILES["image"]["name"];
				    $file_type = $_FILES["image"]["type"];
			        $final_name = clean($file_title);

				    $tempFile = $_FILES['image']['tmp_name'];            
				      
				    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
				     
				    $targetFile =  $targetPath. $final_name;

				    $res = move_uploaded_file($tempFile,$targetFile);
				    if($res) {
				    	$img_lib = add_file_to_image_library_db($session->id, $args['ref'], $final_name, $folder, $file_title, $file_type);
				    	$img_lib['success'] = true;
				    	$response = $img_lib;
				    	$response['file'] = get_option("home_url").$response['file'];
				    	do_action("after_trumbowyg_upload", $response);
				    } 
				     
				}
				echo json_encode($response);
				exit();
				break;

			case 'dropzone_image_library':
				$ds = "/";
				$folder = UPLOADFOLDER.$ds.'ImageLibrary'.$ds.date('M-Y', time()).$ds.$args['user_id'].$ds.$args['ref'];
				$storeFolder = '..'.$ds.'..'.$ds.$folder;
				$response['args'] = $args;
				if (!file_exists($storeFolder)) {
	                mkdir($storeFolder, 0777, true);
	            }
				if (!empty($_FILES)) {
				    $file_title = $_FILES["file"]["name"];
				    $file_type = $_FILES["file"]["type"];
			        $final_name = clean($file_title);

				    $tempFile = $_FILES['file']['tmp_name'];            
				      
				    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
				     
				    $targetFile =  $targetPath. $final_name;
				    $res = move_uploaded_file($tempFile,$targetFile);

				    if($res) {
				    	$img_lib = add_file_to_image_library_db($args['user_id'], $args['ref'], $final_name, $folder, $file_title, $file_type);
				    	$response = array_merge($img_lib, $response);
				    	do_action("after_drag_n_drop_upload", $response);
				    	do_action("after_dz_upload_".$args['id'], $response);
				    } 
				     
				}
				echo json_encode($response);
				exit();
				break;

			case "remove_library_file":
				do_action("before_dz_remove_".$args['library_id'], $args);
				remove_library_file($args['library_id'], $args['serverfilename']);
				do_action("after_dz_remove_".$args['library_id'], $args);
				$response = $args;
				echo json_encode($response);
				exit();
				break;

			case "get_library_files":
				$existing = $post->get_post_by_meta_data(['type' => 'image_library', 'ref' => strtolower($args['ref']), 'user_id' => $args['user_id']]);
				if(_count($existing)) {
					$response['library_id'] = $existing[0]['id'];
					$response['files'] = unserialize($existing[0]['files']);
				}
				echo json_encode($response);
				exit();
				break;

			case "remove_post_item":
				$post->drop_post($args['id']);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'action':
				if(function_exists($args['actionCallback'])) {
					$response['ret'] = $args['actionCallback']($args);
					if($response['ret']['status']) {
						$response['msg'] = (isset($response['ret']['msg'])) ? $response['ret']['msg'] : "Success!!!";
						$response['error'] = 0;
					} else {
						$response['msg'] = (isset($response['ret']['msg'])) ? $response['ret']['msg'] : "Action Failed due to broken process. Contact the software developer.";
						$response['error'] = 1;
					}
				} else {
					$response['ret'] = false;
					$response['msg'] = 'You have not created the function <strong class="red">'.$args['actionCallback'].'</strong> to handle your request';
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

			case 'group_action':
				if(function_exists($args['actionCallback'])) {
					if(_count($args['selectedItems'])) {
						foreach ($args['selectedItems'] as $item) {
							$item = _unserialize($item);
							$selectArgs = $args;
							foreach ($selectArgs as $key => &$value) {
								if($key == $value){
									$value = isset($item[$key]) ? $item[$key] : $value;
								}
							}
							set_time_limit(200);
							$res = $args['actionCallback']($selectArgs);
							if($res['status']) {
								// $g .= $selectArgs['id'];
							}
						}
						$response['msg'] = 'Done';
						$response['error'] = 0;
					} else {
						$response['ret'] = false;
						$response['msg'] = 'You have not selected any item';
						$response['error'] = 1;
					}
				} else {
					$response['ret'] = false;
					$response['msg'] = 'You have not created the function <strong class="red">'.$args['actionCallback'].'</strong> to handle your request';
					$response['error'] = 1;
				}
				echo json_encode($response);
				exit();
				break;

			case 'get_menu_items':
				$menu = new menu;
				$response = $menu->get();
				echo json_encode($response);
				exit();
				break;

			case 'save_menu_items':
				$menu = new menu;
				$res = $menu->save($args);
				if($res) {
					$response['error'] = 0;
					$response['msg'] = "You have successfully updated menu items";
					update_option("stop_update_menu", 1);
				} else {
					$response['error'] = 1;
					$response['msg'] = "Nothing was changed";
				}
				echo json_encode($response);
				exit();
				break;

			case 'edit_roles':
				update_option('user_roles', $args['roles']);
				$response['error'] = 0;
				$response['msg'] = "You have successfully updated roles and capabilities";
				echo json_encode($response);
				exit();
				break;

			case 'edit_admin_page':
				$post->update_post_meta($args['id'], $args);
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case 'update_dynamic_select':
				$val = $args['val'];
				$args[$val] = apply_filters("dynamic_select_value_".$args['type'], $args[$val]);
				if(!$args[$val] && strtolower($val) !== 'id') {
					$response['error'] = 1;
					$response['val'] = $args[$val];
					echo json_encode($response);
					exit();
				}
				$table = $args['table'];
				unset($args['val']);
				unset($args['table']);
				unset($args['id']);
				switch ($table) {
					case 'post':
						if($existing = db_post_unique($args)) {
							$response['error'] = 1;
							$response['val'] = $existing[$val];
						} else {
							$args['id'] = $post->add_post($args);
							$response['val'] = $args[$val];
							$response['error'] = 0;

						}
						break;

					case 'user':
						if($existing = db_user_unique($args)) {
							$response['error'] = 1;
							$response['val'] = $existing[$val];
						} else {
							$args['id'] = $user->add_user($args);
							$response['val'] = $args[$val];
							$response['error'] = 0;
						}
						break;
					
					default:
						if($existing = db_item_unique($args, $table)) {
							$response['error'] = 1;
							$response['val'] = $existing[$val];
						} else {
							if(_count($args) && is_array($args)) {
								$query = new query;
								$keys = $values = "";
								foreach ($args as $k => $v) {
									$keys .= $k.", ";
									$values .="'".$v."', ";
								}
								$keys = substr($keys, 0, -2);
								$values = substr($values, 0, -2);
								$sql = "INSERT INTO $table ($keys) VALUES ($values)";
								$query->query($sql);
								$args['id'] = mysqli_insert_id($query->connection);
								$response['q'] = $sql;
								$response['val'] = $args[$val];
								$response['error'] = 0;
							} else {
								$response['error'] = 1;
								$response['val'] = "";
							}
							
						}
						break;
				}
				
				echo json_encode($response);
				exit();
				break;

			case 'get_dynamic_select_options':
				$table = $args['table'];
				unset($args['table']);
				$val = $args['val'];
				unset($args['val']);
				$key = $args['key'];
				unset($args['key']);
				switch ($table) {
					case 'post':
						$response['options'] = get_select_options_from_post($args['args'], $key, $val);
						break;

					case 'user':
						$response['options'] = get_select_options_from_user($args['args'], $key, $val);
						break;
					
					default:
						$response['options'] = get_select_options_from_db($table, $args['args'], $key, $val);
						break;
				}
				echo json_encode($response);
				exit();
				break;

			case 'load_more_api':
				if(function_exists($args['query_function'])) {
					$response = $args['query_function']($args);
				} else {
					$response['msg'] = "You have not defined a function ".$args['query_function'];
				}
				echo json_encode($response);
				exit();
				break;

			case "get_all_pages":
				$response = ($pages = $post->get_post_by_meta_data(['type' => 'page'])) ? $pages : array();
				foreach ($response as $key => $value) {
					if($value['permalink'] == LOGOUT_PAGE || !current_user_can($value['access'])) {
						unset($response[$key]);
					}
				}
				$response = array_values($response);
				echo json_encode($response);
				exit();
				break;

			case "get_not_required_fields":
				$response['notrequired'] = ($option = get_option("not_required_fields")) ? $option : array();
				$response['all'] = ($option = get_option("all_fields")) ? $option : array();
				echo json_encode($response);
				exit();
				break;

			case "edit_forms":
				$nrf = ($option = get_option("not_required_fields")) ? $option : array();
				$nrf[$args['page_permalink']] = $args["not_required_field"];
				update_option("not_required_fields", $nrf);

				$allf = ($option = get_option("all_fields")) ? $option : array();
				$allf[$args['page_permalink']] = $args["all_field"];
				update_option("all_fields", $allf);

				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "new_comment":
				$comment = new comment($args['obj']);
				$comment->set_comment_args(['comment' => $args['comment']]);
				if(isset($args['key'])) {
					$comment->key = $args['key'];
				}
				$comment->dictionary->label_plu = $args['label_plu'];
				$comment->dictionary->label = $args['label'];
				$res = $comment->new_comment($comment->args);
				if($res) {
					if(isset($args['key'])) {
						do_action("after_new_comment_".$args['key'], $args);
					}
					$response["error"] = 0;
				} else $response["error"] = 1;
				echo json_encode($response);
				exit();
				break;

			case "get_comments":
				$comment = new comment($args['obj']);
				$comment->dictionary->label = $args['label'];
				$comment->dictionary->label_plu = $args['label_plu'];
				$comment->set_comments();
				$response = $comment->display_comment();
				echo json_encode($response);
				exit();
				break;

			case "new_review":
				$review = new review($args['obj']);
				$review->set_review_args(['review' => $args['review'], 'rating' => $args['rating']]);
				if(isset($args['key'])) {
					$review->key = $args['key'];
				}
				$review->dictionary->label_plu = $args['label_plu'];
				$review->dictionary->label = $args['label'];
				$res = $review->new_review($review->args);
				if($res) {
					if(isset($args['key'])) {
						do_action("after_new_review_".$args['key'], $args);
					}
					$response["error"] = 0;
				} else $response["error"] = 1;
				echo json_encode($response);
				exit();
				break;

			case "get_reviews":
				$review = new review($args['obj']);
				$review->dictionary->label = $args['label'];
				$review->dictionary->label_plu = $args['label_plu'];
				$review->set_reviews();
				$response = $review->display_review();
				echo json_encode($response);
				exit();
				break;

			case "search_query_get_result":
				$query_function = $args['query_function'];
				unset($args['query_function']);
				if(function_exists($query_function)) {
					$response = $query_function($args);
				} else $response = "You have not created the function <strong>".$query_function."</strong> to handle your query";
				echo json_encode($response);
				exit();
				break;

			case "query_loader_api":
				if(function_exists($args['query_function'])) {
					$response = $args['query_function']($args);
				} else {
					$response['html'] = "You have not created the function <strong>".$args['query_function']."</strong> to handle your request";
				}
				echo json_encode($response);
				exit();
				break;

			case "get_new_notifications":
				$query = new query;
				$sql = "SELECT `id`, `content`, `action` FROM notification
						WHERE `user_id` LIKE '$session->id' 
						AND `status` LIKE 'unread'
						LIMIT 1";
				$response = $query->get_results($sql, ARRAY_A);
				if(_count($response) && is_array($response)) {
					
					$response = array_shift($response);
					$response['status'] = 'okay';
					$sql = "UPDATE notification
							SET `status` = 'read'
							WHERE `id` = '".$response['id']."'";
					$query->query($sql);
				} else {
					$response['status'] = 'empty';
				}
				echo json_encode($response);
				exit();
				break;

			case 'library_file_grabber_api':
				$response = get_upload_library_files( $args['ref'] );
				echo json_encode($response);
				exit();
				break;

			case "get_country_codes":
				$response['all'] = file_get_contents(ABSPATH."app/assets/country-codes/country-dial-code-with-space.json");
				$response['country'] = get_my_country();
				echo json_encode($response);
				exit();
				break;

			case "get_entries":
				if(isset($args['compare']) && (_count($args['compare']) > 0)) {
					$compare = $args['compare'];
				} else $compare = 'LIKE';
				$res = $post->get_post_by_meta_data($args['settings'], $compare, false, 0, 0, 'post_id', 'DESC');
				$table = new table($args['settings']['type']."_table", $res);
				if(isset($args['properties']))
					$table->set_properties($args['properties']);
				if(isset($args['columns']))
					$table->set_display_columns($args['columns']);
				if(isset($args['dynamicColumns']))
					$table->set_dynamic_columns($args['dynamicColumns']);
				if(isset($args['actionCallback']))
					$table->set_action_callback($args['actionCallback']);
				if(isset($args['actionLinks']))
					$table->set_action_links($args['actionLinks']);
				if(isset($args['actionAccess']))
					$table->set_action_access($args['actionAccess']);
				if(isset($args['actionArgs']))
					$table->set_action_args($args['actionArgs']);
				if(isset($args['actionCondition']))
					$table->set_action_condition($args['actionCondition']);
				if(isset($args['actionConditioner']))
					$table->set_action_conditioner($args['actionConditioner']);
				if(isset($args['actionPopup']))
					$table->set_action_popup($args['actionPopup']);
				if(isset($args['actionPrompt']))
					$table->set_action_prompt($args['actionPrompt']);
				echo json_encode($table->table_html());
				exit();
				break;

			case "load_more_search_result":
				$response = search_result_load_more($args['args']);
				echo json_encode($response);
				exit();
				break;

			case "new_site_binding_request":
				$args['role_binding'] = explode('\r\n', sanitize($args['role_binding']));
				$args['role_binding'] = serialize($args['role_binding']);
				$args['role_binding'] = base64_encode($args['role_binding']);
				$args['binding_id'] = generate_site_binding_id();
				$temp = $args;
				$url = trim($args['url']);
				$url .= (substr($url, -1) === "/" || substr($url, -1) === "\\") ? "" : "/";
				$url .= "app/includes/ajax.php";
				$args['type'] = "inward_site_binding";
				$cURLConnection = curl_init($url);
				if($cURLConnection) {
					$args['action'] = "register_binding_request";
					$args['ref_url'] = get_option("home_url");
					curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $args);
					curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
					$res = curl_exec($cURLConnection);
					curl_close($cURLConnection);
					$res = json_decode($res);
					$response['res'] = $res;
					$response['args'] = $args;
					if($res->status == true) {
						$args = $temp;
						$args['type'] = "outward_site_binding";
						$args['binding_id'] = $res->binding_id;
						$args['url'] = $url;
						if($existing = db_post_unique(['type' => 'outward_site_binding', 'url' => $url, 'binding_id' => $res->binding_id])) {
							$response['error'] = 1;
							$response['msg'] = "Site already binded.";
							if($res->binding_status === 'pending') {
								$response['msg'] .= " Request is awaiting approval.";
							} else if($res->binding_status === 'disallow') {
								$response['msg'] .= " However, the admin of the site disallowed the binding.";
							}
							echo json_encode($response);
							exit();
						} else {
							$post->add_post($args);
						}
						$response['error'] = 0;
						$response['msg'] = "Request Sent Successfully";
					} else {
						$response['error'] = 1;
						$response['msg'] = "Remote Server Refused Connection";
					}
				} else {
					$response['error'] = 1;
					$response['msg'] = "Invalid Connection";
				}
				echo json_encode($response);
				exit();
				break;

			case "register_binding_request":
				if($existing = db_post_unique(['type' => 'inward_site_binding', 'ref_url' => $args['ref_url']])) {
					$response['binding_id'] = $existing['binding_id'];
					$response['status'] = true;
					$response['binding_status'] = $existing['binding_status'];
					echo json_encode($response);
					exit();
				}
				if (db_post_unique(['binding_id' => $args['binding_id']])) {
					$args['binding_id'] = generate_site_binding_id();
				}
				$args['status'] = "pending";
				$response['binding_status'] = "pending";
				$id = $post->add_post($args);
				if($id) {
					$info = "You received a new inward site binding request from <a href =\"".$args['ref_url']."\">".$args['ref_url']."</a>. Please review the request and approve or disallow. <br />This will automatically extract user profile information from your site to the binded site on login and enable automatic account creation on the binded site as long as the user was registered in your site. <br />Need technical advise? write <a href=\"mailto:info@koweb.com.ng\">info@koweb.com.ng</a>.";
					$subject = "SITE BINDING REQUEST FROM ".$args['ref_url'];
					$action = get_option("home_url")."site-user-binding";
					inform_admins($info, $subject, $action, "software_engineer", "super_admin_tech");
					$response['binding_id'] = $args['binding_id'];
					$response['status'] = true;
				} else {
					$response['status'] = false;
				}
				echo json_encode($response);
				exit();
				break;

			case 'delete_site_binding':
				$site_binding = new site_binding;
				$site_binding->delete_site_binding($args['binding_id']);
				$response['status'] = true;
				echo json_encode($response);
				exit();
				break;

			case 'notify_binding':
				inform_admins($args['msg'], $args['subject'], get_option("home_url")."site-user-binding", "software_engineer", "super_admin_tech");
				echo json_encode($response);
				exit();
				break;

			case 'site_binding_pull_credentials':
				$site_binding = new site_binding;
				$binding = $site_binding->verify_binding($args['binding_id']);
				if($binding) {
					$user_meta = $site_binding->pull_user_credential($args['login'], $args['password']);
					if($user_meta) {
						$response['user_meta'] = $user_meta;
						$response['status'] = true;
					} else {
						$response['status'] = false;
					}
				} else {
					$response['status'] = false;
				}
				echo json_encode($response);
				exit();
				break;

			case "save_custom_css":
				$content = base64_encode($args['content']);
				update_option("custom_css", $content);
				echo json_encode($response);
				exit();
				break;

			case "search_users":
				if(trim($args['search_term']) !== "") {
					$query = ['surname' => '%'.$args['search_term'].'%'];
					if(_count($args['query_settings'] ?? array())) {
						$query = array_merge($query, $args['query_settings']);
					}
					$surname = $user->get_user_by_meta_data($query, "LIKE", false, 0, 0, 'user_id', 'ASC');
					$query = ['other_names' => '%'.$args['search_term'].'%'];
					if(_count($args['query_settings'] ?? array())) {
						$query = array_merge($query, $args['query_settings']);
					}
					$other_name = $user->get_user_by_meta_data($query, "LIKE", false, 0, 0, 'user_id', 'ASC');
					if(!empty($surname) || !empty($other_name)) {
						$response = array_merge($surname, $other_name);
					}
				}
				// $response = array_map("search_users_result_filter", $response);
				echo json_encode($response);
				exit();
				break;

			case "get_option":
				$options = new options;
				$response = $options->get_option($args['option'], false);
				echo json_encode($response);
				exit();
				break;

			case "get_record":
				$records = new records;
				$response = $records->get_record($args['record'], false);
				echo json_encode($response);
				exit();
				break;

			case "get_meta":
				switch ($args['meta_type']) {
					case 'user':
						$response = $user->get_user_meta($args['id'], $args['sel_col']);
						break;
					
					case 'post':
						$response = $post->get_post_meta($args['id']);
						break;

					default:
						$query = new query;
						$response = $query->quick_select($args['meta_type'], ["where" => ["id" => $args['id']]], ARRAY_A);
						if(_count($response)) {
							$response = array_shift($response);
						} else $response = false;
						break;
				}
				echo json_encode($response);
				exit();
				break;

			case "get_meta_by_data":
				switch ($args['meta_type']) {
					case 'user':
						$response = $user->get_user_by_meta_data($args['meta_data']);
						break;
					
					case 'post':
						$response = $post->get_post_by_meta_data($args['meta_data']);
						break;

					default:
						$query = new query;
						$response = $query->quick_select($args['meta_type'], ["where" => $args['meta_data']], ARRAY_A);
						break;
				}
				echo json_encode($response);
				exit();
				break;

			case "edit_post_action":
				$meta = $post->get_post_meta($args['id']);
				$response['meta'] = process_edit_post_in($meta);
				echo json_encode($response);
				exit();
				break;

			case "dir_get_countries":
				// $cURLConnection = curl_init("https://countriesnow.space/api/v0.1/countries/states");
				$response = file_get_contents(ABSPATH."app/assets/country-codes/country-states.json");
				// update_record("dir-countries", $response);
				echo $response;
				exit();
				break;

			default:
				$response['error'] = 1;
				$response['msg'] = 'You have not created a module to process this form submission';
				json_encode($response);
				break;
		}
		// json_encode($response);
	}

endif;