<?php
session_start();
if(!isset($_SESSION['auth'])) {
	header("location:../index.php");
}

require_once("../../inc/confNetisse.php");

$profile_header = "";
$phq = "SELECT * from ca_profils";
$phr = $GLOBALS['cnx']->query($phq);
$nb_profiles = $phr->rowCount();
$profiles = array();
while($p = $phr->fetchObject()) {
	$profile_header .= "<th id='profil_header_".$p->id_profil."'>".$p->nom."</th>";
	$profiles[] = $p->id_profil;
}
$DATA = "";
$currentRessource = "";
$ressources = array("accueil"=>"ACCUEIL","permissions"=>"ADMINISTRATION","performances"=>"SURVEILLANCE","user"=>"GESTION DES UTILISATEURS","agence"=>"GESTION DES AGENCES","orientations"=>"GESTION DES ORIENTATIONS","agent"=>"GESTION DES CONSEILLERS","calendrier"=>"GESTION DES MOBILITES","stats"=>"TABLEAU DE BORD");
$qp = "SELECT * FROM ca_permissions ORDER BY position ASC";
$rp = $GLOBALS['cnx']->query($qp);
while($o = $rp->fetchObject()) {
	if($currentRessource != $o->ressource){
		$DATA .= "<tr><th colspan='".($nb_profiles+1)."'><b>".$ressources[$o->ressource]."</b></th></tr>";
		$currentRessource = $o->ressource;
	}
	$DATA .= "<tr><th id=\"".$o->type_permission."\">".$o->description."</th>";
	$actionArray = explode("_",$o->type_permission);
	$action = $actionArray[0];
	$concern = ($actionArray[1] && $actionArray[1] == "all" || $actionArray[1] == "own") ? $actionArray[1] : "";
	for($i=0;$i<$nb_profiles;$i++){
		if($o->ressource == "calendrier" && $GLOBALS["BO_CONF"]["CALENDAR"] == false){
			$DATA .= '<td style="background-color:#eee"><input type="checkbox" id="'.$action.$profiles[$i].$concern.$o->ressource.'" name="'.$o->id_permission.'" value="'.$profiles[$i].'" disabled="disabled" ';
		}
		else{
			$DATA .= "<td><input type='checkbox' id='".$action.$profiles[$i].$concern.$o->ressource."' name='".$o->id_permission."' value='".$profiles[$i]."' ";
			$q = "select count(*) as checked from ca_profil_permission where id_profil = :id_profil and id_permission = :id_permission";
			$values = array(':id_profil' => intval($profiles[$i]), ':id_permission' => intval($o->id_permission));
			$result = excuteQuery($q, $values);
			$r = $result['stmt'];
			$row = $r->fetchObject();
			$DATA .= ($row->checked == 0) ? '' : ' ng-checked="true"';
			$DATA .= "ng-model='".$action.$profiles[$i].$concern.$o->ressource."' ";
			if($o->ressource != "performances" && $o->ressource != "permissions" && $o->ressource != "accueil"){
				if($action == "edit" || $action == "add"){
					$DATA .= "ng-disabled='!isActive(\"view".$profiles[$i].$concern.$o->ressource."\",\"".$action.$profiles[$i].$concern.$o->ressource."\")' ";
				}
				else if($action == "delete"){
					$DATA .= "ng-disabled='!isActive(\"edit".$profiles[$i].$concern.$o->ressource."\",\"".$action.$profiles[$i].$concern.$o->ressource."\")' ";
				}
			}
		}

		$DATA .= "/></td>";
	}
	$DATA .= "</tr>";
}


?>

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title><?php echo $PROJECT_TITLE;?> : Liste des permissions</title>
	<link rel="stylesheet" href="../css/font-awesome.min.css" />
	<link rel="stylesheet" type="text/css" href="../css/cadif.css" />
	<link rel="stylesheet" type="text/css" href="../css/dashboard.css" />
	<link rel="stylesheet" type="text/css" href="../css/cans/jquery-ui-1.8.17.custom.css" />
	<!--<link rel="stylesheet" type="text/css" href="css/tableTools_jui.css" />-->
	<link rel="stylesheet" type="text/css" href="../css/datatable_jui.css" />

	<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="../js/jquery-ui-1.8.22.custom.min.js"></script>
	<script type="text/javascript" src="../js/jquery.dataTables.js"></script>

	<script type="text/javascript" src="../js/angular.min.js"></script>

	<script type="text/javascript">
	var app = angular.module('myApp', []);
	app.controller("AppController",['$scope', function($scope) {
		$scope.selection = "";
		angular.element(document).ready( function () {
			 // Init selection variable which will contain permissions changes
			 // var selection = "";
			 $('input[type="checkbox"]').on('change',function() {
				 console.log('changed');
				 // Check if selection already exists
				 if ($scope.selection.indexOf($(this)[0].name+"-"+$(this)[0].value) >= 0){
					 // Delete this entry from the list of changes in selection variable
					 // If the substring is in the middle of the selection variable
					 if ($scope.selection.indexOf($(this)[0].name+"-"+$(this)[0].value+"_") >= 0){
						var index = $scope.selection.indexOf($(this)[0].name+"-"+$(this)[0].value+"_");
						var infos = $(this)[0].name+"-"+$(this)[0].value+"_";
						var remove = $scope.selection.substring(index,(index+infos.length+2));
						$scope.selection = $scope.selection.replace(remove,'');
					 }
					 else{
						// If the substring is at the end of the selection variable
						if($scope.selection.indexOf("_"+$(this)[0].name+"-"+$(this)[0].value) >= 0){
							var index = $scope.selection.indexOf("_"+$(this)[0].name+"-"+$(this)[0].value);
							var infos = "_"+$(this)[0].name+"-"+$(this)[0].value;
							var remove = $scope.selection.substring(index,(index+infos.length+2));
							$scope.selection = $scope.selection.replace(remove,'');
						}
						else{
							var index = $scope.selection.indexOf($(this)[0].name+"-"+$(this)[0].value);
							var infos = $(this)[0].name+"-"+$(this)[0].value;
							var remove = $scope.selection.substring(index,(index+infos.length+2));
							// If the substring is the first entry in the selection variable
							$scope.selection = $scope.selection.replace(remove,'');
							if($scope.selection.substring(0,1) == "_") $scope.selection = $scope.selection.substring(1,($scope.selection.length));
						}
					 }
				 }
				 else{
					 // Add separator if selection was already altered
					 if($scope.selection != "") $scope.selection+= "_";
					 // Append permission and profile informations
					 $scope.selection += $(this)[0].name+"-"+$(this)[0].value
					 var action = $(this).is(':checked') ? 1 : 0;
					 // Add insert/delete permission information
					 $scope.selection += "-"+action;
				 }
				 // console.log(selection);
			 });
			 $( "#savePerm" ).click(function( event ) {
				 if($scope.selection != ""){

					$('#loading').show();
					updatePermissions($scope.selection);
					$scope.selection = "";
					setTimeout(function() {
						$('#loading').hide("fade", {}, 1000);
					}, 2000);
				 }
				 else{
					 alert("Aucun changement!");
				 }
			 });
		});
		function updatePermissions(selection){
			$.ajax({
				type: 'POST',
				url: 'savePerm.php',
				data: "&permissions="+selection,
				success: function(response){
					setTimeout(function() {
						$('#loading').addClass('successPermContainer');
						$("#loadingMessage").addClass('successPerm');
						$("#loadingMessage").text("Informations enregistrées avec succès!");
					}, 1000);

					console.log(response);
				}
			});
		}
		$scope.isActive = function(targetID,elementID){
			if($("#"+elementID).is(":checked") == true && $("#"+targetID).is(":checked") == false){
				$("#"+elementID).attr('checked', false).trigger("change");
			}
			return $("#"+targetID).is(":checked");
		}
	}]);
	</script>
</head>

<body>

<div id="global" ng-app="myApp">

	<div id="home">
		<div id="logo"><a href="<?php echo $SERVER;?>admin/dashboard.php"><img src="<?php echo $SERVER; ?>assets/img/logo.png" height="110" border="0"/></a></div>
		<div id="username">
			<b><?php echo isset($_SESSION["nom"]) ? $_SESSION["nom"] : $_SESSION["matricule"];?></b> &nbsp; | &nbsp; <a href="<?php echo $SERVER;?>admin/close.php" class="link" title="Fermer et clore votre session">D&#233;connexion</a>
			<br/>
		</div>
	</div>
	<div id="panels">
	  <?php include "../menu.php";?>
	  <div class="main-content">
		<div id="title">
			Liste des permissions par profil
		</div>
		<div id="permissionList" ng-controller="AppController">
			<table cellpadding="0" cellspacing="0" border="0" class="display" id="AdminsDataTable">
				<thead>
				<tr>
					<th width="200">Ressource</th>
					<?php echo $profile_header; ?>
				</tr>
				</thead>
				<tbody>
					<?php
						echo $DATA;
					?>
				</tbody>
			</table>
			<br/>
			<input type="button" id="savePerm" value="Valider"/>
		</div>
	  </div>
	</div>
</div>

<?php include '../footer.php';?>


<br/><br/>
<div id="loading"><div id="loadingMessage">Enregistrement des permissions en cours...</div></div>
</body>

</html>