<?php 
/**
* Tumder Project - A platform for the fun
* @copyright (c) 2016 Loois Sndr. All rights reserved.
*
* @author Loois Sndr
* @since 2016
*/

require_once( dirname( __FILE__ ) . '/td-load.php');

$t = '';
$a = '';

if (isset($_GET['t'])) {
    $t = secureEncode($_GET['t']);
}

if (isset($_GET['a'])) {
    $a = secureEncode($_GET['a']);
}

$data = array(
    'status' => 417
);

if ($t == "login") {
	if(!empty($_POST['login_id']) && !empty($_POST['login_key'])) {
		if (isset($_POST['login_id']) && isset($_POST['login_key'])) {
			$login_user = secureEncode($_POST['login_id']);
			$login_key  = secureEncode($_POST['login_key']);
			$login_key_encript = sha1(str_rot13($login_key . $encryption));

			// Detect login type
			if (is_numeric($login_user)) {
        		$cc_login_part = "id = " . $login_user;
    		} elseif (preg_match('/@/', $login_user)) {
        		$cc_login_part = "email = '{$login_user}'";
    		} elseif (preg_match('/[A-Za-z0-9_]/', $login_user)) {
        		$cc_login_part = "username = '{$login_user}'";
    		}

    	    $sql_query_one = $Tumdconnect->query("SELECT * FROM ".ACCOUNTS." WHERE $cc_login_part AND password = '{$login_key_encript}'");

    	    if ($sql_query_one->num_rows == 1) {
    	    	$sql_fetch_one = mysqli_fetch_assoc($sql_query_one);
    	    	$continue = true;

    	    	if ($sql_fetch_one['active'] == false && $sql_fetch_one['admin'] == false) {
    	    		$continue = false;
    	    		$data['error_message'] = $lang['user_lock'];
    	    	}

    	    	if ($continue == true) {
    	       		setcookie('tumd_ac_u', $sql_fetch_one['id'], time() + (60 * 60 * 24 * 1), '/');
    	       		setcookie('tumd_ac_p', $login_key_encript, time() + (60 * 60 * 24 * 1), '/');
                    
                    $user_last_logged = $Tumdconnect->query("UPDATE ".ACCOUNTS." SET last_logged=$time WHERE id=" . $sql_fetch_one['id']);

                    $log_last_logged = $lang['normal_login'];
                    $Tumdconnect->query("INSERT INTO ".LOGS." (user_id, log_text, log_type, log_date, log_data) VALUES ('{$sql_fetch_one['id']}', '{$log_last_logged}', 'login', '{$date}', '{$time}')") or die();
    	       		$data['status'] = 200;
                    if(isset($_POST['redirect_url']) && !empty($_POST['redirect_url'])) {
                        $data['redirect_url'] = siteUrl().'/'.$_POST['redirect_url'];
                    }
                    else {
                        $data['redirect_url'] = siteUrl()."/home";
                    }
    	        }
    	    } else { $data['error_message'] = $lang['invalid_data']; }
		} else { $data['error_message'] = $lang['error_message']; }
	} else { $data['error_message'] = $lang['empty_place']; }

    if ($a == "secure_idlogin") {
        if(!empty($_POST['secure_secret_user']) && !empty($_POST['secure_secret_id'])) {
            if (isset($_POST['secure_secret_user']) && isset($_POST['secure_secret_id'])) {
                $secure_login_user = secureEncode($_POST['secure_secret_user']);
                $secure_login_id   = secureEncode($_POST['secure_secret_id']);
                $secure_login_id_encript = sha1(str_rot13($secure_login_id . $encryption));

                $sql_query_secure = $Tumdconnect->query("SELECT * FROM ".ACCOUNTS." WHERE username = '{$secure_login_user}' AND secret_sid = '{$secure_login_id_encript}'");

                if ($sql_query_secure->num_rows == 1) {
                    $sql_fetch_secure = mysqli_fetch_assoc($sql_query_secure);
                    $secure_continue = true;

                    if ($sql_fetch_secure['active'] == 0) {
                        $secure_continue = false;
                        $data['error_message'] = $lang['user_lock'];
                    }

                    if ($secure_continue == true) {
                        setcookie('tumd_ac_u', $sql_fetch_secure['id'], time() + (60 * 60 * 24 * 1), '/');
                        setcookie('tumd_ac_p', $sql_fetch_secure['password'], time() + (60 * 60 * 24 * 1), '/');
                        $log_last_logged = $lang['secure_login'];
                        $Tumdconnect->query("INSERT INTO ".LOGS." (user_id, log_text, log_type, log_date, log_data) VALUES ('{$sql_fetch_secure['id']}', '{$log_last_logged}', 'login', '{$date}', '{$time}')") or die();
                        $data['status'] = 200;
                        $data['redirect_url'] = siteUrl()."/home"; 
                     }
                } else { $data['error_message'] = $lang['invalid_data']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

	header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == "admin-login") {
    if(!empty($_POST['login_id']) && !empty($_POST['login_key']) && !empty($_POST['admin_pin'])) {
        if (isset($_POST['login_id']) && isset($_POST['login_key']) && isset($_POST['admin_pin'])) {
            $login_user = secureEncode($_POST['login_id']);
            $login_key  = secureEncode($_POST['login_key']);
            $login_key_encript = sha1(str_rot13($login_key . $encryption));
            $admin_pin = secureEncode($_POST['admin_pin']);

            if (is_numeric($login_user)) {
                $cc_login_part = "id = " . $login_user;
            } elseif (preg_match('/@/', $login_user)) {
                $cc_login_part = "email = '{$login_user}'";
            } elseif (preg_match('/[A-Za-z0-9_]/', $login_user)) {
                $cc_login_part = "username = '{$login_user}'";
            }

            $sql_query_one = $Tumdconnect->query("SELECT * FROM ".ACCOUNTS." WHERE $cc_login_part AND password = '{$login_key_encript}'");

            if ($sql_query_one->num_rows == 1) {
                $sql_fetch_one = mysqli_fetch_assoc($sql_query_one);
                
                if ($sql_fetch_one['admin'] == true) {
                    if ($admin_pin == $Tumd['config']['setting']['admin_pin']) {
                        setcookie('tumd_ac_u', $sql_fetch_one['id'], time() + (60 * 60 * 24 * 1), '/');
                        setcookie('tumd_ac_p', $login_key_encript, time() + (60 * 60 * 24 * 1), '/');
                        $user_last_logged = $Tumdconnect->query("UPDATE ".ACCOUNTS." SET last_logged=$time WHERE id=" . $sql_fetch_one['id']);
                        $data['status'] = 200;
                        $data['redirect_url'] = siteUrl()."/admin";
                    } else { $data['error_message'] = $lang['invalid_pin']; }
                } else { $data['error_message'] = $lang['user_not_admin']; }
            } else { $data['error_message'] = $lang['invalid_data']; }
        } else { $data['error_message'] = $lang['error_message']; }
    } else { $data['error_message'] = $lang['empty_place']; }

    header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == "register") {
	if (!empty($_POST["name"]) && !empty($_POST["username"]) && !empty($_POST["password"]) && !empty($_POST["secret_sid"]) && !empty($_POST["vsecret_sid"]) && !empty($_POST["email"])) {
		if (isset($_POST["name"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["secret_sid"]) && isset($_POST["vsecret_sid"]) && isset($_POST["email"])) {
	
			$user_ip = $_SERVER["REMOTE_ADDR"];
			$name                 = secureEncode($_POST["name"]);
			$user_name            = secureEncode($_POST["username"]);
			$user_password        = secureEncode($_POST["password"]);
			$password_encryption  = sha1(str_rot13($user_password . $encryption));
            $user_ssid            = secureEncode($_POST["secret_sid"]);
            $user_vssid           = secureEncode($_POST["vsecret_sid"]);
            $user_ssid_encryption = sha1(str_rot13($user_ssid . $encryption));
			$user_email           = secureEncode($_POST["email"]);
			$check_user  = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE username = '{$user_name}'");
			$check_email = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE email = '{$user_email}'");

			if (preg_match("/^[a-zA-Z0-9_]+$/", $user_name) && !ctype_digit($user_name)) {
				if(strlen($user_name) >= 4 && strlen($user_name) <= 10) {
					if(strlen($user_password) >= 6) {
                        if(strlen($user_ssid) >= 10) {
                            if ($user_ssid == $user_vssid) {
					             if ($check_user->num_rows < 1) {
						            if($check_email->num_rows < 1) {
						        		if (filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
						        			if ($name != NULL && $user_name != NULL && $user_password != NULL && $user_ssid != NULL && $user_vssid != NULL) {
						        				if (preg_match("/^[a-zA-Z- ]+$/", $name)) {
						        					if (strlen($name) <= 20) {
                                                        $Tumdconnect->query("INSERT INTO ".ACCOUNTS." (name, username, password, secret_sid, email, ip, registration_date, xp) VALUES ('{$name}', '{$user_name}', '{$password_encryption}', '{$user_ssid_encryption}', '{$user_email}', '{$user_ip}', '{$time}', '{$Tumd['config']['setting']['xp_register']}')") or die();
                                                        $ins_user_id = $Tumdconnect->insert_id;
                                                        $Tumdconnect->query("INSERT INTO ".USERS." (user_id, gender) VALUES ({$ins_user_id},'1')");

						        						setcookie("tumd_ac_u", $user_name, time() + (60 * 60 * 24 * 1), '/');
						        						setcookie("tumd_ac_p", $password_encryption, time() + (60 * 60 * 24 * 1), '/');
						        						sleep(1);
						        						$data['status'] = 200;
    	            	        						$data['redirect_url'] = siteUrl().'/home';
    	            	        					}else { $data['error_message'] = $lang['name_exceed']; }
    	            	        				}else { $data['error_message'] = $lang['name_char_invalid']; }
    	            	        			}else { $data['error_message'] = $lang['fields_spaces']; }
						        		}else { $data['error_message'] = $lang['invalid_email']; }
						        	}else { $data['error_message'] = $lang['email_used']; }
						        }else { $data['error_message'] = $lang['username_used']; }
                            }else { $data['error_message'] = $lang['sid_dont_match']; }
                        }else { $data['error_message'] = $lang['sid_contain_digits']; }
					}else { $data['error_message'] = $lang['password_contain_digits']; }
				}else { $data['error_message'] = $lang['user_contain_digits']; }
			}else { $data['error_message'] = $lang['user_char_invalid']; }
		}else{ $data['error_message'] = $lang['error_message']; }
	}else { $data['error_message'] = $lang['empty_place'];; }

	header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == "avatar") {
	if ($a == "new" && !empty($_POST['user_id']) && is_numeric($_POST['user_id']) && $_POST['user_id'] > 0) {
        $continue = false;
        
        if ($_POST['user_id'] == $Tumd['data']['id']) {
            $direct_uid = $Tumd['data'];
            $continue = true;
        }
        
        if (isset($_FILES['image']['tmp_name']) && $continue == true) {
        	if (($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"] == "image/jpg") || ($_FILES["image"]["type"] == "image/png") || ($_FILES["image"]["type"] == "image/JPG")) {
                if ($_FILES['image']['size'] > 1024) {
            	   $image = $_FILES['image'];
            	   $avatar = uploadMedia($image);
            
            	    if (isset($avatar['id'])) {
            	           $query_one = "UPDATE ".ACCOUNTS." SET avatar_id=" . $avatar['id'] . " WHERE id=" . $direct_uid['id'];
            	        $sql_query_one = $Tumdconnect->query($query_one);
                
            	        if ($sql_query_one) {
                            $data = array(
                       	        'status' => 200,
                       	        'success_message' => $lang['upload_image_success'],
                            	'avatar_url' => $Tumd['config']['setting']['site_url'].'/' . $avatar['url'] . '_100x100.' . $avatar['extension']
                       	    );
                            $log_last_logged = $lang['updated_profile_picture'];
                            $Tumdconnect->query("INSERT INTO ".LOGS." (user_id, log_text, log_type, log_date, log_data) VALUES ('{$direct_uid['id']}', '{$log_last_logged}', 'avatar', '{$date}', '{$time}')") or die();

            	   	    } else { $data['error_message'] = $lang['error_message']; }
                    } else { $data['error_message'] = $lang['error_message']; }
                } else { $data['error_message'] = $lang['image_small']; }
        	} else { $data['error_message'] = $lang['no_support_file']; }
        } else { $data['error_message'] = $lang['message_select_image']; }
        
        header("Content-type: application/json");
        echo json_encode($data);
        mysqli_close($Tumdconnect);
        exit();
    }
}

if ($t == 'user') {
	if ($GLOBALS['access'] !== true) {
        return false;
    }

	if ($a == 'info') {
		if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['gender'])) {
			if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['gender'])) {
				$update_name  = secureEncode($_POST["name"]);
				$update_email = secureEncode($_POST["email"]);
                $update_about = secureEncode($_POST["about"]);
                
				$check_update_email = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE id != '{$Tumd['data']['id']}' AND email = '{$update_email}'");
				$update_gender = '';
				if ($_POST["gender"] == 'male') {
					$update_gender = 1;
				} elseif ($_POST["gender"] == 'female'){
					$update_gender = 2;
				}
				if($check_update_email->num_rows < 1) {
					if (filter_var($update_email, FILTER_VALIDATE_EMAIL)) {
						if ($update_name != NULL && $update_email != NULL) {
							if (preg_match("/^[a-zA-Z ]+$/", $update_name)) {
								if (strlen($update_name) <= 20) {
                                    if (strlen($update_about) <= 132) {
									$Tumdconnect->query("UPDATE ".ACCOUNTS." SET name='{$update_name}', email='{$update_email}', last_update_info='{$time}' WHERE id='{$Tumd['data']['id']}'") or die();
									$Tumdconnect->query("UPDATE ".USERS." SET gender='{$update_gender}', about='{$update_about}' WHERE user_id='{$Tumd['data']['id']}'") or die();
                                    $log_last_logged = "Se cambio la información del perfil";
                                    $Tumdconnect->query("INSERT INTO ".LOGS." (user_id, log_text, log_type, log_date, log_data) VALUES ('{$Tumd['data']['id']}', '{$log_last_logged}', 'info', '{$date}', '{$time}')") or die();
									$data['status'] = 200;
									$data['success_message'] = $lang['info_saved'];
                                    } else { $data['error_message'] = $lang['description_long']; }
								} else { $data['error_message'] = $lang['name_exceed']; }
							} else { $data['error_message'] = $lang['name_char_invalid']; }
						} else { $data['error_message'] = $lang['fields_spaces']; }
					} else { $data['error_message'] = $lang['invalid_email']; }
				} else { $data['error_message'] = $lang['email_used']; }
			} else { $data['error_message'] = $lang['error_message']; }
		} else { $data['error_message'] = $lang['empty_place']; }
	}

    if ($a == 'update_theme') {
        if (isset($_POST['theme_pilot'])) {
            if (!empty($_POST['theme_pilot'])) {
                $update_theme = secureEncode($_POST["theme_pilot"]);
                $sql_theme_query = $Tumdconnect->query("SELECT * FROM ".THEMES." WHERE theme_id = '{$update_theme}'");
                if ($sql_theme_query->num_rows > 0) {
                    $theme_data = mysqli_fetch_assoc($sql_theme_query);
                    $Tumdconnect->query("UPDATE ".ACCOUNTS." SET profile_theme='{$theme_data['theme_class']}' WHERE id='{$Tumd['data']['id']}'");
                    $data['status'] = 200;
                    $data['success_message'] = $lang['theme_updated'];
                }
            }
        }
    }

    if ($a == 'logs') {
        if ( isset($_POST['init']) != NULL ) {

            $init = $_POST['init'];

            if( $init == 0 ){
                $limit = 9;   
            } else {
                $limit = 4;
            }

            $rs_query = $Tumdconnect->query("SELECT COUNT(`log_id`) AS log_item FROM ".LOGS." WHERE user_id = '{$Tumd['data']['id']}'");
            $c_log_total = $rs_query->fetch_assoc();

            $data = array(
               'c_log_total' => (int) $c_log_total['log_item'],
               'c_log_rest' => NULL,
               'logs_data' => array()
            );

            $format = "SELECT * FROM ".LOGS." ORDER BY log_data DESC LIMIT %d, %d";
            $sql = sprintf($format, $init, $limit);

            $rs_query = $Tumdconnect->query($sql);

            while( $log_article = $rs_query->fetch_assoc() ){
               $data['logs_data'][] = $log_article;
            }

            $data['c_log_rest'] = ($c_log_total['log_item'] - $rs_query->num_rows ) - $init;
            sleep(2);
        }
    }

    if ($a == 'password') {
        if (!empty($_POST['current_password']) && !empty($_POST['new_password']) && !empty($_POST['new_password_v'])) {
            if (isset($_POST['current_password']) && isset($_POST['new_password']) && isset($_POST['new_password_v'])) {
                $v_pass = sha1(str_rot13($_POST['current_password'] . $encryption));
                if ($v_pass == $Tumd['data']['password']) {
                    if ($_POST['new_password'] == $_POST['new_password_v']) {
                        $new_password = secureEncode($_POST['new_password']);
                        $password_encryption = sha1(str_rot13($new_password . $encryption));
                        $log_pass_changed = "Se cambio la contraseña del usuario";
                        $Tumdconnect->query("INSERT INTO ".LOGS." (user_id, log_text, log_type, log_date, log_data) VALUES ('{$Tumd['data']['id']}', '{$log_pass_changed}', 'info', '{$date}', '{$time}')") or die();
                        $Tumdconnect->query("UPDATE ".ACCOUNTS." SET password='{$password_encryption}' WHERE id='{$Tumd['data']['id']}'");
                        $data['status'] = 200;
                        $data['success_message'] = $lang['password_changed'];
                    } else { $data['error_message'] = $lang['password_dont_match']; }
                } else { $data['error_message'] = $lang['current_password_invalid']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

	header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}

if ($t == 'update_favourite') {
    if ($Tumd['access'] == true && isset($_POST['id'])) {

        $game_id = secureEncode($_POST['id']);
        $userid  = secureEncode($Tumd['data']['id']);
        $photo_avatar = getAvatar($Tumd['data']['avatar_id'], $Tumd['info']['gender'], 'medium');

        if ($Tumd['access'] == true) {
            $user_fav_game = $Tumdconnect->query("SELECT * FROM ".USER_GAME." WHERE user_id='{$userid}' AND game_id='{$game_id}' AND type='favorite'");
    
            if ($user_fav_game->num_rows > 0) {
                // Remove favourite
                $Tumdconnect->query("DELETE FROM ".USER_GAME." WHERE user_id='{$userid}' AND game_id='{$game_id}' AND type='favorite'");
            }
            else {
                // Add favourite
                $Tumdconnect->query("INSERT INTO ".USER_GAME." (user_id, game_id, type) VALUES ('{$userid}', '{$game_id}', 'favorite')");

                $data['success_message'] = '
                    <div class="_a-c _xp-34f9">
                        <img class="_xp-34mn" src="'.siteUrl().'/templates/'.$Tumd['theme_name'].'/image/icon-color/star.png">
                        <img class="_xp-34mn" src="'.$photo_avatar.'">
                    </div>
                    <h2 class="color-d">'.$lang['favorited'].'</h2>
                    '.$lang['msg_alert_fv_1'];
            }
        }
        header("Content-type: application/json");
        echo json_encode($data);
        $Tumdconnect->close();
        exit();
    }
}


if ($t == 'gameplayed') {
    $game_id = secureEncode($_POST['gid']);
    $Tumdconnect->query("UPDATE ".GAMES." SET plays=plays+1 WHERE game_id='{$game_id}'");

    header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == 'get_xp') {
    if ($Tumd['access'] == true) {
        $xp_play = $Tumd['config']['setting']['xp_play'];
        $Tumdconnect->query("UPDATE ".ACCOUNTS." SET xp = xp+$xp_play WHERE id='{$Tumd['data']['id']}'");
        $photo_avatar = getAvatar($Tumd['data']['avatar_id'], $Tumd['info']['gender'], 'medium');

        $data['access'] = true;
        $data['success_message'] = '
            <div class="_a-c _xp-34f9">
                <img class="_xp-34mn" src="'.siteUrl().'/templates/'.$Tumd['theme_name'].'/image/icon-color/star_xp.png">
                <img class="_xp-34mn" src="'.$photo_avatar.'">
            </div>
            <h2>'.$lang['congrats'].'</h2> 
            '.$lang['msg_alert_xp_1'].' <b class="color-c">+'.$xp_play.'</b> '.$lang['msg_alert_xp_2'];
    } else {
        $data['access'] = false;
        $data['success_message'] = '
            <div class="_a-c _xp-34f9">
                <img class="_xp-34mn" src="'.siteUrl().'/templates/'.$Tumd['theme_name'].'/image/icon-color/star_xp.png">
                <img class="_xp-34mn" src="'.siteUrl().'/templates/'.$Tumd['theme_name'].'/image/icon-color/star_xp.png">
            </div>
            <div class="_xp-sts-0">
                <a class="spf-link" href="'.siteUrl().'/login">'.$lang['sign_in'].'</a> '.$lang['or'].'
                <a class="spf-link" href="'.siteUrl().'/signup">'.$lang['sign_up'].'</a>
            </div> '.$lang['msg_alert_xp_3'];
    }

    header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == 'send_report') {
    if (isset($_POST['gid']) && isset($_POST['report']) && !empty($_POST['gid']) && !empty($_POST['report'])) {
        $game_reported = secureEncode($_POST['gid']);
        $info_report   = secureEncode(shortStr($_POST['report'], 100));
        
        if ($Tumd['access'] == true) {
            $user_report = $Tumd['data']['id'];
        } else {
            $user_report = '0';
        }

        $Tumdconnect->query("INSERT INTO ".REPORTS." (id_reported, report_info, user_id, report_date) VALUES ('{$game_reported}', '{$info_report}', '{$user_report}', '{$time}')");

        $data['status'] = 200;
        $data['success_message'] = $lang['msg_alert_report'];
    } else {
        $data['error_message'] = $lang['msg_alert_report_error'];
    }

    header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


if ($t == 'search') {
    if (isset($_POST['search_parameter'])) {
        $data['status'] = 200;
        $data['redirect_url'] = siteUrl().'/search/'.$_POST['search_parameter'];
    }

    header("Content-type: application/json");
    echo json_encode($data);
    $Tumdconnect->close();
    exit();
}


/*+=========================+*\
  |  ADMIN PANEL REQUESTS   |
\*+=========================+*/

if ($t == 'admin' && $Tumd['access'] == true && $Tumd['data']['admin'] == true) {
    $p = '';
    if (isset($_GET['p'])) {
        $p = secureEncode($_GET['p']);
    }

    if ($a == 'addgame') {
        if (!empty($_POST['game_name']) && !empty($_POST['game_width']) && !empty($_POST['game_height']) && !empty($_POST['game_category'])) {
            if (isset($_POST['game_name']) && isset($_POST['game_width']) && isset($_POST['game_height']) && isset($_POST['game_category']) && isset($_POST['game_published']) && isset($_POST['game_featured'])) {
                $addgame = array();
                $addgame['name']         = secureEncode($_POST['game_name']);
                $addgame['description']  = secureEncode($_POST['game_description']);
                $addgame['instructions'] = secureEncode($_POST['game_instructions']);
                $addgame['width']        = secureEncode($_POST['game_width']);
                $addgame['height']       = secureEncode($_POST['game_height']);
                $addgame['category']     = secureEncode($_POST['game_category']);
                $addgame['published']    = secureEncode($_POST['game_published']);
                $addgame['featured']     = secureEncode($_POST['game_featured']);
                $addgame['import']       = secureEncode($_POST['game_import']);
                $addgame['game_type']    = secureEncode($_POST['game_file_type']);
                $addgame['rating']       = secureEncode($_POST['game_rating']);

                if ($addgame['import'] == 0) {
                    if (!empty($_POST['game_image'])) {
                        if (!empty($_POST['game_file'])) {
                            $addgame_mediaurl = secureEncode($_POST['game_image']);
                            $addgame['file']  = secureEncode($_POST['game_file']);

                            $Tumdconnect->query("INSERT INTO ".GAMES." (name, image, import, category, description, instructions, file, game_type, w, h, date_added, published, featured, rating) VALUES ('{$addgame['name']}', '{$addgame_mediaurl}', '0', '{$addgame['category']}', '{$addgame['description']}', '{$addgame['instructions']}', '{$addgame['file']}', '{$addgame['game_type']}', '{$addgame['width']}', '{$addgame['height']}', '{$time}', '{$addgame['published']}', '{$addgame['featured']}', '{$addgame['rating']}')");

                            $data['status'] = 200;
                            $data['success_message'] = $lang['game_saved'];
                        } else { $data['error_message'] = $lang['fileurl_empty']; }
                    } else { $data['error_message'] = $lang['imageurl_empty']; }
                } 
                else if ($addgame['import'] == 1) {
                    if (isset($_FILES['__game_image']['tmp_name']) && isset($_FILES['__game_file']['tmp_name'])) {
                        if ($_FILES['__game_image']['size'] > 1024) {
                            $addgame_media = $_FILES['__game_image'];
                            $addgame['image'] = uploadGameMedia($addgame_media);
                            $addgame_mediaurl = $addgame['image']['url'].'.'.$addgame['image']['extension'];

                            $game_target_path = "data-photo/data-game/games/";
                            $game_target_path = $game_target_path.basename($_FILES['__game_file']['name']); 
                            if ($_FILES['__game_file']['type'] == "application/x-shockwave-flash") {
                                if(move_uploaded_file($_FILES['__game_file']['tmp_name'], $game_target_path)) {
                                   $Tumdconnect->query("INSERT INTO ".GAMES." (name, image, import, category, description, instructions, file, game_type, w, h, date_added, published, featured) VALUES ('{$addgame['name']}', '{$addgame_mediaurl}', '1', '{$addgame['category']}', '{$addgame['description']}', '{$addgame['instructions']}', '{$game_target_path}', '{$addgame['game_type']}', '{$addgame['width']}', '{$addgame['height']}', '{$time}', '{$addgame['published']}', '{$addgame['featured']}')");

                                    $data['status'] = 200;
                                    $data['success_message'] = $lang['game_saved'];
                                } else { $data['error_message'] = $lang['error_file_upload']; }
                            } else { $data['error_message'] = $lang['error_file_extension']; }
                        } else { $data['error_message'] = $lang['error_image_size']; }
                    } else { $data['error_message'] = $lang['message_select_img_files']; }
                } else { $data['error_message'] = $lang['error_message']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

    if ($a == 'editgame') {
        if (!empty($_POST['eg_name']) && !empty($_POST['eg_width']) && !empty($_POST['eg_height']) && !empty($_POST['eg_category'])) {
            if (isset($_POST['eg_name']) && isset($_POST['eg_width']) && isset($_POST['eg_height']) && isset($_POST['eg_category'])) {
                $editgame = array();
                $editgame['name']         = secureEncode($_POST['eg_name']);
                $editgame['description']  = secureEncode($_POST['eg_description']);
                $editgame['instructions'] = secureEncode($_POST['eg_instructions']);
                $editgame['width']        = secureEncode($_POST['eg_width']);
                $editgame['height']       = secureEncode($_POST['eg_height']);
                $editgame['category']     = secureEncode($_POST['eg_category']);
                $editgame['import']       = secureEncode($_POST['eg_import']);
                $editgame['type']         = secureEncode($_POST['eg_file_type']);
                $editgame['id']           = secureEncode($_POST['eg_id']);
                $editgame['rating']       = secureEncode($_POST['eg_rating']);

                if ($editgame['import'] == 0) {
                    if (!empty($_POST['eg_image'])) {
                        if (!empty($_POST['eg_file'])) {
                            $editgame_mediaurl = secureEncode($_POST['eg_image']);
                            $editgame['file'] = secureEncode($_POST['eg_file']);

                            $Tumdconnect->query("UPDATE ".GAMES." SET name='{$editgame['name']}', image='{$editgame_mediaurl}', import='0', category='{$editgame['category']}', description='{$editgame['description']}', instructions='{$editgame['instructions']}', file='{$editgame['file']}', game_type='{$editgame['type']}', w='{$editgame['width']}', h='{$editgame['height']}', rating='{$editgame['rating']}' WHERE game_id='{$editgame['id']}'");

                            $data = array(
                                'status' => 200,
                                'success_message' => $lang['game_saved'],
                                'game_name' => $editgame['name'],
                                'game_img' => $editgame_mediaurl
                            );
                        } else {
                            $data['error_message'] = $lang['fileurl_empty'];
                        }
                    } else {
                        $data['error_message'] = $lang['imageurl_empty'];
                    }
                } 
                else if ($editgame['import'] == 1) {
                    if (isset($_FILES['__eg_image']['tmp_name']) && isset($_FILES['__eg_file']['tmp_name'])) {
                        if ($_FILES['__eg_image']['size'] > 1024) {
                            $editgame_media = $_FILES['__eg_image'];
                            $editgame['image'] = uploadGameMedia($editgame_media);
                            $editgame_mediaurl = $editgame['image']['url'].'.'.$editgame['image']['extension'];

                            $game_target_path = "data-photo/data-game/games/";
                            $game_target_path = $game_target_path.basename($_FILES['__eg_file']['name']); 
                            if ($_FILES['__eg_file']['type'] == "application/x-shockwave-flash") {
                                if(move_uploaded_file($_FILES['__eg_file']['tmp_name'], $game_target_path)) {

                                   $Tumdconnect->query("UPDATE ".GAMES." SET name='{$editgame['name']}', image='{$editgame_mediaurl}', import='1', category='{$editgame['category']}', description='{$editgame['description']}', instructions='{$editgame['instructions']}', file='{$game_target_path}', game_type='{$editgame['type']}', w='{$editgame['width']}', h='{$editgame['height']}', rating='{$editgame['rating']}' WHERE game_id='{$editgame['id']}'");

                                    $data = array(
                                        'status' => 200,
                                        'success_message' => $lang['game_saved'],
                                        'game_name' => $editgame['name'],
                                        'game_img' => $editgame_mediaurl
                                    );
                                } else { $data['error_message'] = $lang['error_file_upload']; }
                            } else { $data['error_message'] = $lang['error_file_extension']; }
                        } else { $data['error_message'] = $lang['error_image_size']; }
                    } else { $data['error_message'] = $lang['message_select_img_files']; }
                } else { $data['error_message'] = $lang['error_message']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

    if ($a == 'mg_published') {
        if ($Tumd['access'] == true && isset($_POST['gid'])) {
            $manage_game_id = secureEncode($_POST['gid']);
            $sql_manage_pb = $Tumdconnect->query("SELECT published FROM ".GAMES." WHERE game_id='{$manage_game_id}'");
            $manage_pb = mysqli_fetch_array($sql_manage_pb);

            if ($manage_pb['published'] == 1) {
                # Private game
                $Tumdconnect->query("UPDATE ".GAMES." SET published='0' WHERE game_id='{$manage_game_id}'");
            } else {
                # Publish game
                $Tumdconnect->query("UPDATE ".GAMES." SET published='1' WHERE game_id='{$manage_game_id}'");
            }
        }
    }

    if ($a == 'mg_featured') {
        if ($Tumd['access'] == true && isset($_POST['gid'])) {
            $manage_game_id = secureEncode($_POST['gid']);
            $sql_manage_ft = $Tumdconnect->query("SELECT featured FROM ".GAMES." WHERE game_id='{$manage_game_id}'");
            $manage_ft = mysqli_fetch_array($sql_manage_ft);

            if ($manage_ft['featured'] == 1) {
                $Tumdconnect->query("UPDATE ".GAMES." SET featured='0' WHERE game_id='{$manage_game_id}'");
            } else {
                # Featured game
                $Tumdconnect->query("UPDATE ".GAMES." SET featured='1' WHERE game_id='{$manage_game_id}'");
            }
        }
    }

    if ($a == 'mg_delete') {
        if ($Tumd['access'] == true && isset($_POST['gid'])) {
            $manage_game_id = secureEncode($_POST['gid']);
            $sql_manage_dlt = $Tumdconnect->query("SELECT game_id FROM ".GAMES." WHERE game_id='{$manage_game_id}'");

            if ($sql_manage_dlt->num_rows > 0) {
                $Tumdconnect->query("DELETE FROM ".GAMES." WHERE game_id='{$manage_game_id}'");
            }
        }
    }

    if ($a == 'addcategory') {
        if (!empty($_POST['ac_name'])) {
            if (isset($_POST['ac_name'])) {
                $category_name = secureEncode($_POST['ac_name']);
                $sql_chk_category = $Tumdconnect->query("SELECT id FROM ".CATEGORIES." WHERE name='{$category_name}'");
                if ($sql_chk_category->num_rows < 1) {
                    if (preg_match("/^[a-zA-Z- ]+$/", $category_name)) {
                        if (strlen($category_name) <= 15) {
                            $Tumdconnect->query("INSERT INTO ".CATEGORIES." (name) VALUES ('{$category_name}')");

                            $data['status'] = 200;
                            $data['success_message'] = $lang['category_registered'];
                        } else { $data['error_message'] = $lang['category_name_exceed']; }
                    } else { $data['error_message'] = $lang['invalid_characters']; }
                } else { $data['error_message'] = $lang['category_exists']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['must_enter_name']; }
    }

    if ($a == 'editcategory') {
        if (!empty($_POST['ec_name'])) {
            if (isset($_POST['ec_name'])) {
                $ec_name = secureEncode($_POST['ec_name']);
                $ec_id   = secureEncode($_POST['ec_id']);
                $sql_chk_category = $Tumdconnect->query("SELECT id FROM ".CATEGORIES." WHERE name='{$ec_name}'");
                if ($sql_chk_category->num_rows == 0) {
                    if (preg_match("/^[a-zA-Z- ]+$/", $ec_name)) {
                        if (strlen($ec_name) <= 15) {
                            $Tumdconnect->query("UPDATE ".CATEGORIES." SET name='{$ec_name}' WHERE id='{$ec_id}'");
                            $data = array(
                                'status' => 200,
                                'success_message' => $lang['category_edited']
                            );
                        } else { $data['error_message'] = $lang['category_name_exceed']; }
                    } else { $data['error_message'] = $lang['invalid_characters']; }
                } else { $data['error_message'] = $lang['category_exists']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['must_enter_name']; }
    }

    if ($a == 'mc_delete') {
        if ($Tumd['access'] == true && isset($_POST['cid'])) {
            $category_id = secureEncode($_POST['cid']);
            $sql_category_dlt = $Tumdconnect->query("SELECT id FROM ".CATEGORIES." WHERE id='{$category_id}'");

            if ($sql_category_dlt->num_rows > 0) {
                $Tumdconnect->query("DELETE FROM ".CATEGORIES." WHERE id='{$category_id}' AND id!='1'");
            }
        }
    }

    if ($a == 'setting') {
        if (!empty($_POST['ss_sitename']) && !empty($_POST['ss_siteurl']) && !empty($_POST['ss_sitetheme']) && !empty($_POST['ss_sitelang']) && !empty($_POST['ss_pin'])) {
            if (isset($_POST['ss_sitename']) && isset($_POST['ss_siteurl']) && isset($_POST['ss_sitetheme']) && isset($_POST['ss_sitelang']) && isset($_POST['ss_pin'])) {
                $adm_ss = array();
                $adm_ss['site_name']        = secureEncode($_POST['ss_sitename']);
                $adm_ss['site_url']         = secureEncode($_POST['ss_siteurl']);
                $adm_ss['site_theme']       = secureEncode($_POST['ss_sitetheme']);
                $adm_ss['site_maintenance'] = (isset($_POST['ss_maintenance'])) ? '1' : '0';
                $adm_ss['maintenance_msg']  = secureEncode($_POST['ss_maintenance_msg']);
                $adm_ss['site_description'] = secureEncode($_POST['ss_sitedescription']);
                $adm_ss['site_keywords']    = secureEncode($_POST['ss_sitekeywords']);
                $adm_ss['site_lang']        = secureEncode($_POST['ss_sitelang']);
                $adm_ss['site_ads']         = (isset($_POST['ss_ads'])) ? '1' : '0';
                $adm_ss['xp_play']          = secureEncode($_POST['ss_xp_play']);
                $adm_ss['xp_report']        = secureEncode($_POST['ss_xp_report']);
                $adm_ss['xp_register']      = secureEncode($_POST['ss_xp_register']);
                $adm_ss['featured_game_limit'] = secureEncode($_POST['ss_featured_game_limit']);
                $adm_ss['mp_game_limit']    = secureEncode($_POST['ss_mp_game_limit']);
                $adm_ss['pin']              = secureEncode($_POST['ss_pin']);

                if (empty($adm_ss['xp_play']) && $adm_ss['xp_play'] == NULL && is_numeric($adm_ss['xp_play'])) {
                    $adm_ss['xp_play'] = '0';
                } if (empty($adm_ss['xp_report']) && $adm_ss['xp_report'] == NULL && is_numeric($adm_ss['xp_report'])) {
                    $adm_ss['xp_report'] = '0';
                } if (empty($adm_ss['xp_register']) && $adm_ss['xp_register'] == NULL && is_numeric($adm_ss['xp_register'])) {
                    $adm_ss['xp_register'] = '0';
                } if (empty($adm_ss['featured_game_limit']) && $adm_ss['featured_game_limit'] == NULL && is_numeric($adm_ss['featured_game_limit'])) {
                    $adm_ss['featured_game_limit'] = '0';
                } if (empty($adm_ss['mp_game_limit']) && $adm_ss['mp_game_limit'] == NULL && is_numeric($adm_ss['mp_game_limit'])) {
                    $adm_ss['mp_game_limit'] = '0';
                }
                
                $Tumdconnect->query("UPDATE ".SETTING." SET site_name='{$adm_ss['site_name']}', site_url='{$adm_ss['site_url']}', site_theme='{$adm_ss['site_theme']}', site_maintenance='{$adm_ss['site_maintenance']}', maintenance_msg='{$adm_ss['maintenance_msg']}', site_description='{$adm_ss['site_description']}', site_keywords='{$adm_ss['site_keywords']}', language='{$adm_ss['site_lang']}', ads_status='{$adm_ss['site_ads']}', xp_play='{$adm_ss['xp_play']}', xp_report='{$adm_ss['xp_report']}', xp_register='{$adm_ss['xp_register']}', featured_game_limit='{$adm_ss['featured_game_limit']}', mp_game_limit='{$adm_ss['mp_game_limit']}', admin_pin='{$adm_ss['pin']}' WHERE id='1'");

                $data['status'] = 200;
                $data['success_message'] = $lang['setting_saved'];
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

    if ($a == 'edituser') {
        if (!empty($_POST['eu_username']) && !empty($_POST['eu_name']) && !empty($_POST['eu_email'])) {
            if (isset($_POST['eu_username']) && isset($_POST['eu_name']) && isset($_POST['eu_email'])) {
                $eu_ss = array();
                $eu_id['id']         = secureEncode($_POST['eu_id']);
                $eu_ss['username']   = secureEncode($_POST['eu_username']);
                $eu_ss['name']       = secureEncode($_POST['eu_name']);
                $eu_ss['admin']      = secureEncode($_POST['eu_admin']);
                $eu_ss['email']      = secureEncode($_POST['eu_email']);
                $eu_ss['xp']         = secureEncode($_POST['eu_xp']);
                $eu_ss['status']     = (isset($_POST['eu_active'])) ? '1' : '0';
                $eu_ss['lang']       = secureEncode($_POST['eu_lang']);
                $eu_ss['about']      = secureEncode($_POST['eu_about']);
                $eu_ss['gender']     = secureEncode($_POST['eu_gender']);
                $eu_ss['check_user'] = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE username='{$eu_ss['username']}' AND id!='{$eu_id['id']}'");
                $eu_ss['check_email'] = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE email='{$eu_ss['email']}' AND id!='{$eu_id['id']}'");

                if (preg_match("/^[a-zA-Z0-9_]+$/", $eu_ss['username']) && !ctype_digit($eu_ss['username'])) {
                    if (strlen($eu_ss['username']) >= 4 && strlen($eu_ss['username']) <= 10) {
                        if ($eu_ss['check_user']->num_rows < 1) {
                            if($eu_ss['check_email']->num_rows < 1) {
                                if (filter_var($eu_ss['email'], FILTER_VALIDATE_EMAIL)) {
                                    if ($eu_ss['username'] != NULL && $eu_ss['name'] != NULL) {
                                        if (preg_match("/^[a-zA-Z- ]+$/", $eu_ss['name'])) {
                                            if (strlen($eu_ss['name']) <= 20) {
                                                if (strlen($eu_ss['about']) <= 132) {
                                                    $Tumdconnect->query("UPDATE ".ACCOUNTS." SET name='{$eu_ss['name']}', username='{$eu_ss['username']}', email='{$eu_ss['email']}', admin='{$eu_ss['admin']}', xp='{$eu_ss['xp']}', language='{$eu_ss['lang']}', active='{$eu_ss['status']}' WHERE id='{$eu_id['id']}'") or die();
                                                    $Tumdconnect->query("UPDATE ".USERS." SET gender='{$eu_ss['gender']}', about='{$eu_ss['about']}' WHERE user_id='{$eu_id['id']}'") or die();
                                                    $data['status'] = 200;
                                                    $data['success_message'] = $lang['info_saved'];
                                                } else { $data['error_message'] = $lang['description_long']; }
                                            } else { $data['error_message'] = $lang['name_exceed']; }
                                        } else { $data['error_message'] = $lang['name_char_invalid']; }
                                    } else { $data['error_message'] = $lang['fields_spaces']; }
                                } else { $data['error_message'] = $lang['invalid_email']; }                         
                            } else { $data['error_message'] = $lang['email_used']; }
                        } else { $data['error_message'] = $lang['username_used']; }
                    } else { $data['error_message'] = $lang['user_contain_digits']; }
                } else { $data['error_message'] = $lang['name_char_invalid']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

    if ($a == 'searchUserEdit') {
        if (!empty($_POST['uid'])) {
            if (isset($_POST['uid'])) {
                $s_uid = secureEncode($_POST['uid']);
                if ($s_uid != NULL) {
                    if (is_numeric($s_uid)) {
                        $s_userType_part = "id = " . $s_uid;
                    } elseif (preg_match('/[A-Za-z0-9_]/', $s_uid)) {
                        $s_userType_part = "username = '{$s_uid}'";
                    }
                    $s_check_user = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE $s_userType_part");
                    if ($s_check_user->num_rows == 1) {
                        $data['status'] = 200;
                        $data['redirect_url'] = siteUrl().'/admin/users/edit/' . $s_uid;
                    } else { $data['error_message'] = $lang['user_not_exists']; }
                } else { $data['error_message'] = $lang['fields_spaces']; }
            } else { $data['error_message'] = $lang['error_message']; }
        } else { $data['error_message'] = $lang['empty_place']; }
    }

    if ($a == 'manageAdsArea') {
        $ads_area = array();
        $ads_area['header']     = '';
        $ads_area['footer']     = '';
        $ads_area['column_one'] = '';
        $ads_area['gametop']    = '';
        $ads_area['gamebottom'] = '';
        $ads_area['gameinfo']   = '';
        if (!empty($_POST['ad_header'])) {
        	$ads_area['header'] = $_POST['ad_header'];
        	$ads_area['header'] = str_replace("'", '"', $ads_area['header']);
        }
        if (!empty($_POST['ad_footer'])) {
        	$ads_area['footer'] = $_POST['ad_footer'];
        	$ads_area['footer'] = str_replace("'", '"', $ads_area['footer']);
        }
        if (!empty($_POST['ad_column_one'])) {
        	$ads_area['column_one'] = $_POST['ad_column_one'];
        	$ads_area['column_one'] = str_replace("'", '"', $ads_area['column_one']);
        }
        if (!empty($_POST['ad_gameTop'])) {
        	$ads_area['gametop'] = $_POST['ad_gameTop'];
        	$ads_area['gametop'] = str_replace("'", '"', $ads_area['gametop']);
        }
        if (!empty($_POST['ad_gameBottom'])) {
        	$ads_area['gamebottom'] = $_POST['ad_gameBottom'];
        	$ads_area['gamebottom'] = str_replace("'", '"', $ads_area['gamebottom']);
        }
        if (!empty($_POST['ad_gameInfo'])) {
        	$ads_area['gameinfo'] = $_POST['ad_gameInfo'];
        	$ads_area['gameinfo'] = str_replace("'", '"', $ads_area['gameinfo']);
        }

        $Tumdconnect->query("UPDATE ".ADS." SET header='{$ads_area['header']}', footer='{$ads_area['footer']}', column_one='{$ads_area['column_one']}', gametop='{$ads_area['gametop']}', gamebottom='{$ads_area['gamebottom']}', gameinfo='{$ads_area['gameinfo']}'") or die();
        $data['status'] = 200;
        $data['success_message'] = $lang['ads_saved'];
    }

    if ($a == 'act_report') {
        $report_id = secureEncode($_POST['rp_id']);

        if (isset($_POST['uid'])) {
            $uid = secureEncode($_POST['uid']);
            $xp_report = $Tumd['config']['setting']['xp_report'];
            $Tumdconnect->query("UPDATE ".ACCOUNTS." SET xp = xp+$xp_report WHERE id='{$uid}'");
        }
        $Tumdconnect->query("DELETE FROM ".REPORTS." WHERE report_id='{$report_id}'");
    }

    if ($a == 'game_feed') {
        $i = 0;
        if ($p == 'getfeed_type_1') {
            # FEED URL
            $feed_pilot = 'http://www.kongregate.com/games_for_your_site.xml';
            $feed_data = file_get_contents($feed_pilot);

            # FEED TYPE = XML
            $xml = simplexml_load_string($feed_data);
            foreach($xml->game as $game) {  
                $feedgame_id = intval($game->id);
                $query_feed_game = $Tumdconnect->query("SELECT gid FROM ".CATALOG." WHERE pilot='feed_one' AND gid='{$feedgame_id}'");
                if ($query_feed_game->num_rows == 0) {
                    $game_data = array();
                    $game_data['name'] = secureEncode($game->title);
                    $game_data['desc'] = secureEncode($game->description);
                    $game_data['inst'] = secureEncode($game->instructions);
                    $game_data['cate'] = secureEncode($game->category);
                    $game_data['image'] = secureEncode($game->thumbnail);
                    $game_data['file'] = secureEncode($game->flash_file);
                    $find_ext = strpos($game_data['file'], '.swf');
                    $game_data['type'] = ($find_ext == true) ? 'swf':'web';
                    $game_data['w'] = $game->width;
                    $game_data['h'] = $game->height;

                    $Tumdconnect->query("INSERT INTO ".CATALOG." (gid, name, description, instruction, category, image, file, w, h, pilot, game_type) VALUES ('{$feedgame_id}', '{$game_data['name']}', '{$game_data['desc']}', '{$game_data['inst']}', '{$game_data['cate']}', '{$game_data['image']}', '{$game_data['file']}', '{$game_data['w']}', '{$game_data['h']}', 'feed_one', '{$game_data['type']}')");

                    $i = $i+1;
                }
            }

            $data['redirect_url'] = siteUrl().'/admin/catalog/1';
        }
        
        else if ($p == 'getfeed_type_2') {
            # FEED URL
            $feed_pilot = 'https://publishers.spilgames.com/es/rss-3?limit=100&format=json&platform=Desktop&page=1';
            $feed_data = file_get_contents($feed_pilot);

            # FEED TYPE = JSON
            $json = json_decode($feed_data, true);
            foreach($json['entries'] as $game) {
                # Generated ID from our length
                $id_gen = feedID($game['id'], 5, 'f2');

                $query_feed_game = $Tumdconnect->query("SELECT id FROM ".CATALOG." WHERE gid='{$id_gen}' AND pilot='feed_two'");
                if ($query_feed_game->num_rows == 0) {
                    $game_data = array();
                    $game_data['name'] = secureEncode($game['title']);
                    $game_data['desc'] = secureEncode($game['description']);
                    $game_data['cate'] = secureEncode($game['category']);
                    $game_data['image'] = secureEncode($game['thumbnails']['large']);
                    $game_data['file'] = secureEncode($game['gameUrl']);
                    $find_ext = strpos($game_data['file'], '.swf');
                    $game_data['type'] = ($find_ext == true) ? 'swf':'web';
                    $game_data['w'] = $game['width'];
                    $game_data['h'] = $game['height'];
                    
                    $Tumdconnect->query("INSERT INTO ".CATALOG." (gid, name, description, category, image, file, w, h, pilot, game_type) VALUES ('{$id_gen}', '{$game_data['name']}', '{$game_data['desc']}', '{$game_data['cate']}', '{$game_data['image']}', '{$game_data['file']}', '{$game_data['w']}', '{$game_data['h']}', 'feed_two', '{$game_data['type']}')");

                    $i = $i+1;
                }
            }

            $data['redirect_url'] = siteUrl().'/admin/catalog/2';
        }

        else if ($p == 'getfeed_type_3') {
            # FEED URL
            $feed_pilot = 'https://games.gamepix.com/games';
            $feed_data = file_get_contents($feed_pilot);

            # FEED TYPE = JSON
            $json = json_decode($feed_data, true);
            foreach($json['data'] as $game) {
                $query_feed_game = $Tumdconnect->query("SELECT id FROM ".CATALOG." WHERE pilot='feed_three' AND gid='{$game['id']}'");
                if ($query_feed_game->num_rows == 0) {
                    $game_data = array();
                    $game_data['name'] = secureEncode($game['title']);
                    $game_data['desc'] = secureEncode($game['description']);
                    $game_data['image'] = secureEncode($game['thumbnailUrl']);
                    $game_data['file'] = secureEncode($game['url']);
                    $find_ext = strpos($game_data['file'], '.swf');
                    $game_data['type'] = ($find_ext == true) ? 'swf':'web';
                    $game_data['w'] = $game['width'];
                    $game_data['h'] = $game['height'];
                    
                    $Tumdconnect->query("INSERT INTO ".CATALOG." (gid, name, description, image, file, w, h, pilot, game_type) VALUES ('{$game['id']}', '{$game_data['name']}', '{$game_data['desc']}', '{$game_data['image']}', '{$game_data['file']}', '{$game_data['w']}', '{$game_data['h']}', 'feed_three', '{$game_data['type']}')");

                    $i = $i+1;
                }
            }

            $data['redirect_url'] = siteUrl().'/admin/catalog/3';
        }

        $data['success_message'] = $i . ' '.$lang['games_added_catalog'];
    }

    if ($a == 'game_install') {
        if (!empty($_POST['c_id'])) {
            if (isset($_POST['c_id'])) {
                $gi_id = secureEncode($_POST['c_id']);
                $query_catalog_item = $Tumdconnect->query("SELECT * FROM ".CATALOG." WHERE id='{$gi_id}'");

                if ($query_catalog_item->num_rows == 1) {
                    $array_item = mysqli_fetch_array($query_catalog_item);
                    $query_verItem = $Tumdconnect->query("SELECT game_id FROM ".GAMES." WHERE catalog_id='{$array_item['gid']}'");
                    if ($query_verItem->num_rows == 0) {
                        $Tumdconnect->query("INSERT INTO ".GAMES." (catalog_id, name, image, description, instructions, category, file, game_type, w, h, date_added, published) VALUES ('{$array_item['gid']}','{$array_item['name']}','{$array_item['image']}','{$array_item['description']}','{$array_item['instruction']}','1','{$array_item['file']}','{$array_item['game_type']}','{$array_item['w']}','{$array_item['h']}','{$time}', '0')");
                    }  
                }
            }
        }
    }

    if ($a == 'game_delete') {
        if (!empty($_POST['c_id'])) {
            if (isset($_POST['c_id'])) {
                $game_id = secureEncode($_POST['c_id']);
                $sql_game_c_dlt = $Tumdconnect->query("SELECT id FROM ".CATALOG." WHERE id='{$game_id}'");

                if ($sql_game_c_dlt->num_rows > 0) {
                    $Tumdconnect->query("DELETE FROM ".CATALOG." WHERE id='{$game_id}' AND id!='0'");
                }
            }
        }
    }

    header("Content-type: application/json");
    echo json_encode($data);
    mysqli_close($Tumdconnect);
    exit();
}