<?php
if (!defined("root")) {
	define("root", $_SERVER['DOCUMENT_ROOT']);
}
require(root."/___simple_config.php");
session_start();
require(root."/".adminFolder."/_common.php");
require(root."/".adminFolder."/_lib/db.php");
require(root."/".adminFolder."/_lib/main.php");
require(root."/".adminFolder."/_lib/auth.php");
require(root."/".adminFolder."/_lib/bootstraps.php");
$pageSubOf = "pages";
$pageName = "accounts";
$pageTitle = "Accounts";
$thisUrl = "accounts";
$ajax_page = "ajax_accounts.php";
$pageUrl = "/".adminFolder."/$thisUrl";
$a = cekpost(cleanQuery($_GET["a"]), "");
$err = "";
if ($a=="section_main") {
	if (!authorizedModule("accounts_main", $ses_kduser)) {
		unAuthorizedAccess("accounts_main");
	} else {
		$fil_kdgame = trim(cekpost(cleanQuery($_REQUEST["fil_kdgame"]), ""));
		$fil_username = trim(cekpost(cleanQuery($_REQUEST["fil_username"]), ""));
		$fil_password = trim(cekpost(cleanQuery($_REQUEST["fil_password"]), ""));
		$fil_isactive = trim(cekpost(cleanQuery($_REQUEST["fil_isactive"]), ""));
		$fil_assigned = trim(cekpost(cleanQuery($_REQUEST["fil_assigned"]), ""));
		$swhere = '';
		if ($fil_username!="") { $swhere .= " AND a.username LIKE '%$fil_username%' "; }
		if ($fil_kdgame!="") { $swhere .= " AND a.kdgame = '$fil_kdgame' "; }
		if ($fil_password!="") { $swhere .= " AND a.pass LIKE '%$fil_password%' "; }
		if ($fil_assigned!="") {
			if (intval($fil_assigned)==0) { $swhere .= " AND a.kdmember = '0' "; }
			if (intval($fil_assigned)==1) { $swhere .= " AND a.kdmember <> '0' "; }
		}
		if ($fil_isactive!="") { $swhere .= " AND a.isactive = '$fil_isactive' "; }
		
		$rs=array(); $q="SELECT a.*, b.nama AS nama_game FROM accounts a LEFT JOIN games b ON b.kdgame=a.kdgame WHERE 1=1 $swhere ORDER BY a.cretime DESC";
		callRS($rs, $q);
		
		if (count($rs)!=0) {
			$ld = 40;
			$cp = cekpost(cleanQuery($_GET["cp"]), "1");
			$tp = intval(count($rs) / $ld) + (count($rs)%$ld==0?0:1);
			$sr = ($cp-1) * $ld;
			$pagination = '';
			if ($tp!=1) {
				$pagination .= ('<ul class="pagination pagination-sm">');
					$disabled = '';
					$purl = '#';
					$onclick = '';
					if ($cp<=1) {
						$disabled = 'disabled';
						$onclick = ' onclick="return false;" ';
					}
					$pagination .= ('<li class="'.$disabled.'"><a href="'.$purl.'" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', 1);return false;"').'>&lt;&lt;</a></li>');
					$pagination .= ('<li class="'.$disabled.'"><a href="'.$purl.'" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.($cp-1).');return false;"').'>&lt;</a></li>');
					for ($c=1;$c<=$tp;$c++) {
						$active = '';
						$purl = '#';
						$disabled = '';
						$onclick = '';
						if ($c==$cp) {
							$active = 'active';
						} else {
							$purl = '#';
							$onclick = ' onclick="filterReload(\''.$pageName.'\', '.$c.');return false;" ';
						}
						$pagination .= ('<li class="'.$active.' '.$disabled.'"><a href="'.$purl.'" '.$onclick.'>'.$c.'</a></li>');
					}
					$disabled = '';
					$onclick = '';
					if ($cp>=$tp) {
						$disabled = 'disabled';
						$onclick = ' onclick="return false;" ';
					}
					$pagination .= ('<li class="'.$disabled.'"><a href="#" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.($cp+1).');return false;"').'>&gt;</a></li>');
					$pagination .= ('<li class="'.$disabled.'"><a href="#" '.($onclick!=""?$onclick:'onclick="filterReload(\''.$pageName.'\', '.$tp.');return false;"').'>&gt;&gt;</a></li>');
				$pagination .= ('</ul>');
			}
			cout('<div class="alert alert-info" role="alert"><strong>Total whole data</strong> <span class="badge">'.count($rs).'</span></div>');
			
			if ($tp!=1) {
				cout($pagination);
			}
			cout('<table class="table table-striped table-bordered">');
				cout('<thead>');
					cout('<tr>');
						cout('<th class="text-center">#</th>');
						cout('<th class="text-center">#ID</th>');
						if (authorizedModule("accounts_element_games", $ses_kduser)) {
							cout('<th class="text-center">Games</th>');
						}
						if (authorizedModule("accounts_element_username", $ses_kduser)) {
							cout('<th class="text-center">Username</th>');
						}
						if (authorizedModule("accounts_element_password", $ses_kduser)) {
							cout('<th class="text-center">Password</th>');
						}
						if (authorizedModule("accounts_element_active", $ses_kduser)) {
							cout('<th class="text-center">Active?</th>');
						}
						if (authorizedModule("accounts_element_assign", $ses_kduser)) {
							cout('<th class="text-center">Assigned?</th>');
						}
						cout('<th class="text-center"></th>');
						cout('<th class="text-center"></th>');
						cout('<th class="text-center"></th>');
					cout('</tr>');
				cout('</thead>');
				cout('<tbody>');
				$cnt = 0;
				for ($i=$sr;$i<count($rs) && $cnt<$ld;$i++) {
					$cnt++;
					$kdaccount = $rs[$i]["kdaccount"];
					if (intval($rs[$i]["isactive"])==0) {
						$isactive = '<a href="#" title="Activate" onclick="chActive(\''.$pageName.'\', '.$kd.', '.$rs[$i]["isactive"].');return false;">Non-Active</a>';
					} else {
						$isactive = '<a href="#" title="Deactivate" onclick="chActive(\''.$pageName.'\', '.$kd.', '.$rs[$i]["isactive"].');return false;">Active</a>';
					}
					$isactive = (intval($rs[$i]["isactive"])==1)?'<span class="label label-success">Active</span>':'<span class="label label-danger">Non-Active</span>';
					$isassigned=intval($rs[$i]["kdmember"])==0?'<span class="label label-success">Available</span>':'<span class="label label-danger">Assigned&nbsp;<span class="badge">&nbsp;&nbsp;'.$rs[$i]["kdmember"].'&nbsp;&nbsp;</span></span>';
					if (intval($rs[$i]["kdmember"])==0) {
						$isassigned = '<span class="label label-success">Available</span>';
					} else {
						$isassigned = '<span class="label label-danger">Assigned&nbsp;<span class="badge">&nbsp;&nbsp;'.$rs[$i]["kdmember"].'&nbsp;&nbsp;</span></span>';
						$rsnow = array(); $qnow = "SELECT a.*, b.username AS acc_username FROM members a LEFT JOIN accounts b ON b.kdaccount=a.kdaccount WHERE a.kdmember = '".$rs[$i]["kdmember"]."' AND b.kdaccount!='".$rs[$i]["kdaccount"]."'";
						callRS($rsnow, $qnow);
						#$rsnow = array(); $qnow = "SELECT a.*, b.username AS acc_username FROM members a LEFT JOIN accounts b ON b.kdmember=a.kdmember WHERE a.kdmember = '".$rs[$i]["kdmember"]."' AND b.kdaccount!='".$rs[$i]["kdaccount"]."'";
						#callRS($rsnow, $qnow);
						for ($j=0;$j<count($rsnow);$j++) {
							$isassigned .= '<br/>';
							$isassigned .= $rsnow[$j]["acc_username"];
						}
					}
					$isi = str_replace("\n", "<br/>", $rs[$i]["isi"]);
					cout('<tr class="tr-data'.$kdaccount.'">');
						cout('<td class="text-center">'.($i+1).'</td>');
						cout('<td class="text-center">'.$kdaccount.'</td>');
						if (authorizedModule("accounts_element_games", $ses_kduser)) {
							cout('<td class="text-center"><div class="nfkdgame'.$kdaccount.'">'.$rs[$i]["nama_game"].'</div></td>');
						}
						if (authorizedModule("accounts_element_username", $ses_kduser)) {
							cout('<td class="text-center"><div class="nfusername'.$kdaccount.'"><a href="#" onclick="prepareAct(\'tryview\', '.$kdaccount.');return false;" data-toggle="tooltip" title="View Detail">'.$rs[$i]["username"].'</a></div></td>');
						}
						if (authorizedModule("accounts_element_password", $ses_kduser)) {
							cout('<td class="text-center" style="font-family:droid_sans_monoregular;"><div class="nfpass'.$kdaccount.'">'.$rs[$i]["pass"].'</div></td>');
						}
						if (authorizedModule("accounts_element_active", $ses_kduser)) {
							cout('<td class="text-center isactive'.$kd.'"><div class="nfisactive'.$kdaccount.'">'.$isactive.'</div></td>');
						}
						if (authorizedModule("accounts_element_assign", $ses_kduser)) {
							cout('<td class="text-center">'.$isassigned.'</td>');
						}
						$creby = (trim($rs[$i]["creby"])!=""?'<strong>'.$rs[$i]["creby"].'</strong>':'&lt;<em>no data</em>&gt;').(trim($rs[$i]["cretime"])?' ('.date('d M Y, H:i:s A', $rs[$i]["cretime"]).')':' &lt;<em>no data</em>&gt;');
						$modby = (trim($rs[$i]["modby"])!=""?'<strong>'.$rs[$i]["modby"].'</strong>':'&lt;<em>no data</em>&gt;').(trim($rs[$i]["modtime"])?' ('.date('d M Y, H:i:s A', $rs[$i]["modtime"]).')':' &lt;<em>no data</em>&gt;');
						if (authorizedModule("accounts_element_creation", $ses_kduser)) {
							cout('<td class="text-center"><div class="simple">'.$creby.'</div></td>');
						}
						if (authorizedModule("accounts_element_modification", $ses_kduser)) {
							cout('<td class="text-center"><div class="simple">'.$modby.'</div></td>');
						}
						cout('<td class="text-center">');
							cout('<span class="option'.$kdaccount.'">');
								#cout('<a href="'.$pageUrl.'/edit/'.$kd.'/"><span class="glyphicon glyphicon-pencil"></span><span class="hidden-xs hidden-sm"> Edit</span></a>');
								cout('<a href="#" onclick="prepareAct(\'edit\', '.$kdaccount.');return false;"><span class="glyphicon glyphicon-pencil"></span><span class="hidden-xs hidden-sm"> Edit</span></a>');
								if ($rs[$i]["kdmember"]==0) {
									cout(BSTextSeparator());
									cout('<a href="#" onclick="prepareAct(\'delete\', '.$kdaccount.');return false;"><span class="glyphicon glyphicon-trash"></span><span class="hidden-xs hidden-sm"> Delete</span></a>');
								}
							cout('</span>');
						cout('</td>');
					cout('</tr>');
				}
				cout('</tbody>');
			cout('</table>');
			
			if ($tp!=1) {
				cout($pagination);
			}
			cout('<div class="alert alert-info" role="alert"><strong>Total whole data</strong> <span class="badge">'.count($rs).'</span></div>');
			$act_ket = "Accounts: Main List";
			if ($swhere!="") { $act_ket .= ": ".cleanQuery($swhere).""; }
			updateUserActivities($act_ket);
		} else {
			cout('<div class="alert alert-info" role="alert">');
				cout('<strong>No data available.</strong> Please add new data for display.');
			cout('</div>');
		}
	}
}
if ($a=="chactive") {
	$kd = cekpost(cleanQuery($_REQUEST["kd"]), "");
	$ca = cekpost(cleanQuery($_REQUEST["ca"]), "");
	$kd = (trim($kd)=="undefined")?'':$kd;
	$ca = (trim($ca)=="undefined")?'':$ca;
	if ($kd!="" && $kd!=0 && $ca!="") {
		$na = $ca==0?1:0;
		$modby = $_SESSION["user"]["inisial"];
		$modtime = time();
		$qu = "UPDATE accounts SET isactive='$na', modby='$modby', modtime='$modtime' WHERE kd='$kd'";
		execRS($qu);
		$act_ket = "Accounts: Ch. Active [kd: $kd][from Act: $ca][to Act: $na]";
		updateUserActivities($act_ket);
		if (intval($na)==0) {
			$isactive = '<a href="#" title="Activate" onclick="chActive(\''.$pageName.'\', '.$kd.', '.$na.');return false;">Non-Active</a>';
		} else {
			$isactive = '<a href="#" title="Deactivate" onclick="chActive(\''.$pageName.'\', '.$kd.', '.$na.');return false;">Active</a>';
		}
		echo $isactive;
	}
}
if ($a=="do") {
	$type = cekpost(cleanQuery($_GET["type"]), "");
	$kd = cekpost(cleanQuery($_GET["kd"]), "");
	
	if ($type=="cancel") {
		$rs=array();$q="SELECT a.*, c.nama AS nama_game 
			FROM accounts a 
			LEFT JOIN games c ON c.kdgame=a.kdgame 
			WHERE kdaccount='$kd'";
		callRS($rs, $q);
		$isactive = (intval($rs[0]["isactive"])==1)?'<span class="label label-success">Active</span>':'<span class="label label-danger">Non-Active</span>';
		$target .= 'nfkdgame'.$kd.'$$'.$rs[0]["nama_game"].'$$$';
		$target .= 'nfusername'.$kd.'$$<a href="#" onclick="prepareAct(\'tryview\', '.$kd.');return false;" data-toggle="tooltip" title="View Detail">'.$rs[0]["username"].'</a>$$$';
		$target .= 'nfpass'.$kd.'$$'.$rs[0]["pass"].'$$$';
		$target .= 'nfisactive'.$kd.'$$'.$isactive.'$$$';
		$target .= 'option'.$kd.'$$';
			$target .= '<a href="#" onclick="prepareAct(\'edit\', '.$kd.');return false;"><span class="glyphicon glyphicon-pencil"></span><span class="hidden-xs hidden-sm"> Edit</span></a>';
			$target .= BSTextSeparator();
			$target .= '<a href="#" onclick="prepareAct(\'delete\', '.$kd.');return false;"><span class="glyphicon glyphicon-trash"></span><span class="hidden-xs hidden-sm"> Delete</span></a>';
		echo $target;
		$act_ket = "Accounts: Cancelling previous action";
		updateUserActivities($act_ket);
		exit;
	}
	if ($type=="delete") {
		$rsacc=array();$qacc = "SELECT * FROM accounts WHERE kdaccount='$kd'";
		callRS($rsacc, $qacc);
		$rscek=array();$qcek = "SELECT * FROM members WHERE kdaccount='$kd' AND isdeleted=0";
		callRS($rscek, $qcek);
		if (count($rscek)!=0) {
			
		} else {
			$qd = "DELETE FROM accounts WHERE kdaccount='$kd'";
			execRS($qd);
			$target .= 'deleterow$$$'.$kd.'';
			echo $target;
			$act_ket = "Accounts: Delete: Deleted: [kdaccount: $kd] [username: ".$rsacc[0]["username"]."] [pass: ".$rsacc[0]["pass"]."]";
			updateUserActivities($act_ket);
			exit;
		}
	}
	if ($type=="edit") {
		$nfkdgame = cekpost(cleanQuery($_GET["nfkdgame$kd"]), "");
		$nfusername = cekpost(cleanQuery($_GET["nfusername$kd"]), "");
		$nfpass = cekpost(cleanQuery($_GET["nfpass$kd"]), "");
		$nfisactive = cekpost(cleanQuery($_GET["nfisactive$kd"]), "");
		if ($nfkdgame=="" || $nfusername=="" || $nfpass=="") {
			
		} else {
			$modby = $_SESSION["user"]["inisial"];
			$modtime = time();
			$qu = "UPDATE accounts SET kdgame='$nfkdgame', username='$nfusername', pass='$nfpass' WHERE kdaccount='$kd'";
			execRS($qu);
			$rs=array();
			$q = "SELECT a.*, c.nama AS nama_game FROM accounts a 
				LEFT JOIN games c ON c.kdgame=a.kdgame
				WHERE kdaccount='$kd'";
			callRS($rs, $q);
			$isactive = (intval($rs[0]["isactive"])==1)?'<span class="label label-success">Active</span>':'<span class="label label-danger">Non-Active</span>';
			$target .= 'nfkdgame'.$kd.'$$'.$rs[0]["nama_game"].'$$$';
			$target .= 'nfusername'.$kd.'$$<a href="#" onclick="prepareAct(\'tryview\', '.$kd.');return false;" data-toggle="tooltip" title="View Detail">'.$rs[0]["username"].'</a>$$$';
			$target .= 'nfpass'.$kd.'$$'.$rs[0]["pass"].'$$$';
			$target .= 'nfisactive'.$kd.'$$'.$isactive.'$$$';
			$target .= 'option'.$kd.'$$';
				$target .= '<a href="#" onclick="prepareAct(\'edit\', '.$kd.');return false;"><span class="glyphicon glyphicon-pencil"></span><span class="hidden-xs hidden-sm"> Edit</span></a>';
				$target .= BSTextSeparator();
				$target .= '<a href="#" onclick="prepareAct(\'delete\', '.$kd.');return false;"><span class="glyphicon glyphicon-trash"></span><span class="hidden-xs hidden-sm"> Delete</span></a>';
		}
		echo $target;
		$act_ket = "Accounts: Edit: Edited: [".cleanQuery($qu)."]";
		updateUserActivities($act_ket);
		exit;
	}
}
if ($a=="prepare") {
	$type = cekpost(cleanQuery($_GET["type"]), "");
	$kd = cekpost(cleanQuery($_GET["kd"]), "");
	$rs=array();$q="SELECT * FROM accounts WHERE kdaccount='$kd'";
	callRS($rs, $q);
	$kdgame = $rs[0]["kdgame"];
	$rsa=array();$qa="SELECT * FROM accounts WHERE isactive=1 AND kdmember=0 AND kdgame='$kdgame'";
	callRS($rsa, $qa);
	$target='';
	if ($type=="edit") {
		$target .= 'nfkdgame'.$kd.'$$<select name="nfkdgame'.$kd.'" id="nfkdgame'.$kd.'" class="form-control input-sm">';
			$rsb=array();$qb="SELECT * FROM games WHERE isactive=1";
			callRS($rsb, $qb);
			for ($i=0;$i<count($rsb);$i++) {
				$sel = intval($rsb[$i]["kdgame"])==intval($rs[0]["kdgame"])?'selected="selected"':'';
				$target .= '<option value="'.$rsb[$i]["kdgame"].'" '.$sel.'>'.$rsb[$i]["nama"].'</option>';
			}
		$target .= '</select>$$$';
		$target .= 'nfusername'.$kd.'$$<input type="text" name="nfusername'.$kd.'" id="nfusername'.$kd.'" value="'.$rs[0]["username"].'" class="form-control input-sm" />$$$';
		$target .= 'nfpass'.$kd.'$$<input type="text" name="nfpass'.$kd.'" id="nfpass'.$kd.'" value="'.$rs[0]["pass"].'" class="form-control input-sm" />$$$';
		$isactive0 = intval($rs[0]["isactive"])==0?'selected="selected"':'';
		$isactive1 = intval($rs[0]["isactive"])==1?'selected="selected"':'';
		$target .= 'nfisactive'.$kd.'$$<select name="nfisactive'.$kd.'" id="nfisactive'.$kd.'" class="form-control input-sm">
			<option value="0" '.$isactive0.'>Non-Active</option>
			<option value="1" '.$isactive1.'>Active</option>
		</select>$$$';
		$target .= 'option'.$kd.'$$<input type="button" value="Update" onclick="doAct(\''.$type.'\', '.$kd.');" />&nbsp;
			<input type="button" value="Cancel" onclick="doAct(\'cancel\', '.$kd.');" />';
		echo $target;
		$act_ket = "Accounts: Prepare: [Type: $type]";
		updateUserActivities($act_ket);
	}
	
	if ($type=="delete") {
		$target .= 'option'.$kd.'$$Sure?&nbsp;<input type="button" value="Yes" onclick="doAct(\''.$type.'\', '.$kd.');" />&nbsp;
			<input type="button" value="Cancel" onclick="doAct(\'cancel\', '.$kd.');" />';
		echo $target;
		$act_ket = "Accounts: Prepare: [Type: $type]";
		updateUserActivities($act_ket);
	}
	
}
if ($a=="quick_add") {
	$ikdgame = cekpost(cleanQuery($_POST["ikdgame"]), "");
	$iusername = strtoupper(trim(cekpost(cleanQuery($_POST["iusername"]), "")));
	$ipassword = cekpost(cleanQuery($_POST["ipassword"]), "");
	if ($ikdgame=="") { $err.= BSErrorMessage('Game must be chosen'); }
	if ($iusername=="") { $err.= BSErrorMessage('Username must be filled'); }
	if ($ipassword=="") { $err.= BSErrorMessage('Password must be filled'); }
	$rs=array();$q="SELECT * FROM accounts WHERE username='$iusername' AND kdgame='$ikdgame'";
	callRS($rs, $q);
	if (count($rs)!=0) { $err.= BSErrorMessage('Username already exists'); }
	if ($err=="") {
		$isactive=1;
		$creby = $_SESSION["user"]["inisial"];
		$cretime = time();
		$kdaccount = getID("accounts", "kdaccount");
		$q = "INSERT INTO accounts (kdaccount, username, pass, kdgame, isactive, creby, cretime) 
			VALUES ('$kdaccount', '$iusername', '$ipassword', '$ikdgame', '$isactive', '$creby', '$cretime')";
		execRS($q);
		cout('<script>parent.clearQuickAdd();parent.filterReload(\''.$pageName.'\', 1);</script>');
	} else {
		cout('<script>parent.showError(\''.$err.'\');</script>');
	}
	
}
if ($a=="randpass") {
	$randomString="";
	$possible="346789bcdfhjkmnprtwxyBCDFGHJKLMNPQRTWXY";
	$possibleCaps = "BCDFGHJKLMNPQRTWXY";
	$possibleLow = "bcdfhjkmnprtwxy";
	$possibleNum = "346789";
	$possibleSpecial = "!~#$*@";
	if($usevowels) $possible .= "AUEaue";
	
	$lenC = 1;
	$lenL = 3;
	$lenN = 3;
	$lenS = 1;
	$maxlength=strlen($possible);
	$maxlenC=strlen($possibleCaps);
	$maxlenL=strlen($possibleLow);
	$maxlenN=strlen($possibleNum);
	$maxlenS=strlen($possibleSpecial);
	
	if($length > $maxlength) $length=$maxlength;
	$i=0;
	while($i<$lenC) {
		$char=substr($possibleCaps, mt_rand(0, $maxlenC - 1), 1);
		if(!strstr($randomString, $char)) { $randomString .= $char; $i++; }
	}
	$j=0;
	while($j<$lenL) {
		$char=substr($possibleLow, mt_rand(0, $maxlenL - 1), 1);
		if(!strstr($randomString, $char)) { $randomString .= $char; $j++; }
	}
	$k=0;
	while($k<$lenN) {
		$char=substr($possibleNum, mt_rand(0, $maxlenN - 1), 1);
		if(!strstr($randomString, $char)) { $randomString .= $char; $k++; }
	}
	$x=0;
	while($x<$lenS) {
		$char=substr($possibleSpecial, mt_rand(0, $maxlenS - 1), 1);
		if(!strstr($randomString, $char)) { $randomString .= $char; $x++; }
	}
	echo $randomString;
	#echo generateRandomString(7);
}
?>