<?php
require_once 'load.php';
requirelogin();

//Calculo día 1 del mes en curso
$dia = date('j');
$hora = date('H');
$datemes = time() - ($dia * 24 * 3600) + ($hora * 3600);


$page = isset($_GET['page']) ? $_GET['page'] : '';

//"Fast" check for pages that only an admin can view
$arrPagesFullRigths = array('addcheck','editcheck','savenewcheck','updatecheck','delcheck','modcheckgrp','modcheckname','addgroup','modgroup','delgroup','newnews','editnews','delnews','edituserperm','deluser','adduser','settings');
if (in_array($page,$arrPagesFullRigths) && $you['fullRights'] != 1){
	$page = 'notperm'; //Why here? For switch not loading the other (Original) page
}

switch($page){
	case 'notperm':
		echo $twig->render('panel/p_notperm.twig', array('T_' => $T_, 'you' => $you));
	break;
	case 'checks':
		//Groups (For "fast-change-group option in html")
		$results = dbw_query($db_conn,"SELECT * FROM GROUPS"); //All groups
		while ($group = dbw_fetch_array($db_conn,$results)){
			$groups[] = array(
				'ID_G' =>$group['ID_G'],
				'name' => $group['name']
			);
		}


		$results = dbw_query($db_conn,"SELECT * FROM CHECKS ORDER BY ID_G"); //All checks
		while ($onechk = dbw_fetch_array($db_conn,$results)){
			$idchk = $onechk['ID_C'];
			$chks[$idchk] = $onechk; //First array data
			$ID_G = $chks[$idchk]['ID_G']; //For nameGroup
			$chks[$idchk]['nameGroup'] = dbw_query_fetch_array($db_conn,"SELECT * FROM GROUPS WHERE ID_G='$ID_G'")['name'];
			$ID_TC = $chks[$idchk]['ID_TC'];
			$chks[$idchk]['nameTCheck'] = textTypeChk($ID_TC);
		}


		$results = dbw_query($db_conn,"SELECT name FROM GROUPS WHERE ID_G NOT IN (SELECT DISTINCT ID_G FROM CHECKS)");
		while ($emptygrp = dbw_fetch_array($db_conn,$results)){
			$emptyG[] = array('name' =>$emptygrp['name']);
		}

		renderPage('panel/p_checks.twig',array('mpage' => 'checks','you' => $you, 'checks' => $chks,'groups' => $groups,'emptygrp' => $emptyG));
	break;

	//Forms to add or edit a check (Not saving, only forms)
	case 'addcheck':
	case 'editcheck':
		//General data
		$results = dbw_query($db_conn,"SELECT * FROM GROUPS"); //All groups
		while ($group = dbw_fetch_array($db_conn,$results)){
			$groups[] = array(
				'ID_G' =>$group['ID_G'],
				'name' => $group['name']
			);
		}
		//$results = arrayTypeChk(); //All Type Checks
		foreach(arrayTypeChk() as $key => $value){
			$tchecks[] = array(
				'ID_TC' =>$key,
				'name' => textTypeChk($key)
			);
		}

		//En este if hago las diferencias entre add y edit, para no repetir código.
		if ($page == 'addcheck'){
		renderPage('panel/p_addedit.twig', array('mpage' => 'checks', 'type' => 'new','groups' => $groups,'tchecks' => $tchecks));
		}elseif ($page == 'editcheck'){
			$ID_C = (int)$_GET['ID_C']; //Check to edit
			$checkdata = dbw_query_fetch_array($db_conn,"SELECT * FROM CHECKS WHERE ID_C='$ID_C'"); //Checkdata

			renderPage('panel/p_addedit.twig', array('mpage' => 'checks', 'you' => $you, 'type' => 'edit','groups' => $groups,'tchecks' => $tchecks,'check' => $checkdata));
		}
	break;

	case 'savenewcheck': //Crea los registros de la BD para pasarlo a updatecheck
		$name = $_POST['name'];
		dbw_query($db_conn,"INSERT INTO CHECKS(name) VALUES('$name')"); //Para crear un nuevo vacío
		$ID_C = dbw_last_id($db_conn); //Sacar la ID del nuevo check
	case 'updatecheck': //Guarda los cambios de un check (También lo uso para el primer guardado)
		$ID_C = isset($ID_C) ? $ID_C : (int)$_GET['ID_C'];
		$name = $_POST['name'];
		$ID_G = $_POST['group'];
		$ID_TC = $_POST['tcheck'];
		//Datos que dependen del tipo de check
		if ($ID_TC == 1){
			$URL = $_POST['t1url'] . ':' . $_POST['t1port'];
			dbw_query($db_conn,"UPDATE CHECKS SET URL='$URL' WHERE ID_C='$ID_C'");
		}elseif ($ID_TC == 2){
			$URL = $_POST['t2url'];
			$TCParam = isset($_POST['t2code']) ? $_POST['t2code'] : '';
			dbw_query($db_conn,"UPDATE CHECKS SET URL='$URL',TCParam = '$TCParam' WHERE ID_C='$ID_C'");
		}elseif ($ID_TC == 4){
			$URL = $_POST['t4url'];
			dbw_query($db_conn,"UPDATE CHECKS SET URL='$URL' WHERE ID_C='$ID_C'");
		}//Si es 3 no hay datos que guardar (de momento)
		
		//Guardamos el resto de datos
		dbw_query($db_conn,"UPDATE CHECKS SET name='$name', ID_G='$ID_G', ID_TC='$ID_TC' WHERE ID_C='$ID_C'");

		header('Location: panel.php?page=checks'); //Return to checks
	break;


	case 'delcheck':
		$ID_C = (int)$_GET['ID_C']; //Check to delete

		//Deleting all
		dbw_query($db_conn,"DELETE FROM CHECKS WHERE ID_C='$ID_C'");
		dbw_query($db_conn,"DELETE FROM CHKHIST WHERE ID_C='$ID_C'");

		header('Location: panel.php?page=checks');
	break;

	case 'modcheckgrp': //Changes the group of a check "fast"
		$ID_C = (int)$_GET['ID_C'];
		$newID_G = $_POST['group_'.$ID_C]; //Name in form post is GN_XX
		dbw_query($db_conn,"UPDATE CHECKS SET ID_G='$newID_G' WHERE ID_C='$ID_C'");
		header('Location: panel.php?page=checks');
	break;

	case 'modcheckname': //Changes the name of a check "fast"
		$ID_C = (int)$_GET['ID_C'];
		$newName = $_POST['name_'.$ID_C]; //Name in form post is GN_XX
		dbw_query($db_conn,"UPDATE CHECKS SET name='$newName' WHERE ID_C='$ID_C'");
		header('Location: panel.php?page=checks');
	break;


	case 'groups':
		//All group names and IDs
		$results = dbw_query($db_conn,"SELECT * FROM GROUPS"); //All groups
		while ($group = dbw_fetch_array($db_conn,$results)){
			$countchk = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM CHECKS WHERE ID_G = '$group[ID_G]'")[0];
			$groups[] = array(
				'ID_G' =>$group['ID_G'],
				'name' => $group['name'],
				'checks' => $countchk
			);
		}
		renderPage('panel/p_groups.twig', array('you' => $you, 'mpage' => 'groups', 'groups' => $groups));
	break;

	case 'addgroup':
		$namegrp = $_POST['grpname']; //Name in form post is GN_XX
		dbw_query($db_conn,"INSERT INTO GROUPS(name) VALUES('$namegrp')");
		header('Location: panel.php?page=groups');
	break;
	case 'changegroup':
		$ID_G = (int)$_GET['ID_G'];
		$name = $_POST['GN_'.$ID_G]; //Name in form post is GN_XX
		dbw_query($db_conn,"UPDATE GROUPS SET name='$name' WHERE ID_G='$ID_G'");
		header('Location: panel.php?page=groups');
	break;

	case 'delgroup':
		$ID_G = (int)$_GET['ID_G'];
		dbw_query($db_conn,"DELETE FROM CHECKS WHERE ID_G='$ID_G'");
		dbw_query($db_conn,"DELETE FROM GROUPS WHERE ID_G='$ID_G'");
		header('Location: panel.php?page=groups');
	break;

	case 'news':
		require_once "lib/parsedown.php"; //Import parsedown (once)
		//Groups (For "fast-change-group option in html")
		$results = dbw_query($db_conn,"SELECT * FROM NEWS ORDER BY `timestamp` DESC"); //All groups
		while ($result = dbw_fetch_array($db_conn,$results)){
			$ID_N = $result['ID_N'];
			$news[$ID_N]['ID_N'] = $ID_N;
			$news[$ID_N]['date'] = date('j/n/Y', $result['timestamp']);
			/*$news[$ID_N]['sentBy'] = $result['sentBy'];
			if ($result['sentBy'] != NULL && substr($result['sentBy'],0,1) == "S"){ // Sent by a page 
				$pageinc = substr($result['sentBy'],1);
				$pageinc = dbw_query_fetch_array($db_conn,"SELECT name FROM CHECKS WHERE ID_C = '$pageinc'")[0];
				$news[$ID_N]['sentBy'] = $pageinc;
			}*/
			$news[$ID_N]['text'] = Parsedown::instance()
					->setMarkupEscaped(true) # escapes markup (HTML)
					->text($result['text']);
			$news[$ID_N]['mdtext'] = $result['text']; //Raw text
		}
		renderPage('panel/p_news.twig', array('you' => $you, 'mpage' => 'news', 'allnews' => $news));
	break;

	case 'newnews':
		$text = dbw_escape_string($db_conn,$_POST['text_new']);
		$timestamp = time();
		dbw_query($db_conn,"INSERT INTO NEWS(`text`,`timestamp`) VALUES('$text','$timestamp')");
		header('Location: panel.php?page=news');
	break;
	case 'editnews':
		$ID_N = (int)$_GET['ID_N'];
		$text = dbw_escape_string($db_conn,$_POST['text_'.$ID_N]);
		dbw_query($db_conn,"UPDATE NEWS SET `text`='$text' WHERE ID_N='$ID_N'");
		header('Location: panel.php?page=news');
	break;
	case 'delnews':
		$ID_N = (int)$_GET['ID_N'];
		dbw_query($db_conn,"DELETE FROM NEWS WHERE ID_N='$ID_N'");
		header('Location: panel.php?page=news');
	break;

	case 'savesettings':
		//All group names and IDs
		dbw_query($db_conn,"UPDATE SYS SET `value`='$_POST[name]' WHERE `option`='name'");
		dbw_query($db_conn,"UPDATE SYS SET `value`='$_POST[maxTimeSave]' WHERE `option`='maxTimeSave'");
	case 'settings':
		//All group names and IDs
		$results = dbw_query($db_conn,"SELECT * FROM SYS"); //All groups
		while ($syso = dbw_fetch_array($db_conn,$results)){
			$sys[$syso['option']] = $syso['value'];
		}
		renderPage('panel/p_settings.twig', array('you' => $you, 'mpage' => 'settings', 'sys' => $sys));
	break;

	case 'users':
		//All user data
		$results = dbw_query($db_conn,"SELECT * FROM USERS"); //All groups
		while ($us = dbw_fetch_array($db_conn,$results)){
			$ID_U = $us['ID_U'];
			$user[$ID_U] = array(
				'ID_U' =>$ID_U,
				'nick' => $us['nick'],
				'fullrights' => $us['fullRights']
			);
		}
		renderPage('panel/p_users.twig', array('mpage' => 'users', 'you' => $you, 'users' => $user));
	break;

	case 'adduser':
		//Nuevo usuario
		$nick = $_POST['nuser_name'];
		$passw = hash("sha256",$_POST['nuser_pass']);
		$perms = $_POST['nuser_type'];
		dbw_query($db_conn,"INSERT INTO USERS(`nick`,`passw`,`fullRights`) VALUES('$nick','$passw','$perms')");
		header('Location: panel.php?page=users');
	break;
	case 'editusername':
		//Editar nombre de usuario
		$ID_U = (int)$_GET['ID_U'];
		$nick = $_POST['name_'.$ID_U];
		dbw_query($db_conn,"UPDATE USERS SET `nick`='$nick' WHERE ID_U='$ID_U'");
		header('Location: panel.php?page=users');
	break;
	case 'edituserperm':
		//Editar nombre de usuario
		$ID_U = (int)$_GET['ID_U'];
		$newperm = $_POST['nperm_'.$ID_U];
		dbw_query($db_conn,"UPDATE USERS SET `fullRights`='$newperm' WHERE ID_U='$ID_U'");
		header('Location: panel.php?page=users');
	break;
	case 'edituserpass':
		//Editar tu contraseña
		$passw = hash("sha256",$_POST['userpass1']);
		dbw_query($db_conn,"UPDATE USERS SET `passw`='$passw' WHERE SessionID='$_COOKIE[SessionID]'");
		header('Location: panel.php?page=users');
	break;
	case 'deluser':
		$ID_U = (int)$_GET['ID_U'];
		dbw_query($db_conn,"DELETE FROM USERS WHERE ID_U='$ID_U'");
		header('Location: panel.php?page=users');
	break;


	//History of checks for a ID_C
	case 'viewhist':
		//All page data
		$ID_C = (int)$_GET['ID_C'];
		$page = dbw_query_fetch_array($db_conn,"SELECT name FROM CHECKS WHERE ID_C='$ID_C'");
		$cant = 100;
		$results = dbw_query($db_conn,"SELECT * FROM CHKHIST WHERE ID_C='$ID_C' ORDER BY `timestamp` DESC LIMIT $cant");

		//TODO TIMESTAMPS FAILS
		$cgood = 0;$cbad = 0; $fails = array();
		while ($us = dbw_fetch_array($db_conn,$results)){
			if ($us['code'] == 0){
				$cgood++;
			}else{
				$cbad++;
				$fails[] = date('d/m/Y H:i',$us['timestamp']); //Record timestamps
			}
		}

		$group = nameGroupFromIDG(IDGFromIDC($ID_C));
		$pagedata = array('cgood' => $cgood,'cbad' => $cbad,'name' => nameFromIDC($db_conn,$ID_C), 'group' => $group,'cant' => $cant,'fails' => $fails);

		renderPage('panel/p_viewhist.twig', array('mpage' => 'viewhist', 'you' => $you,'pagedata' => $pagedata));
	break;

		// Página principal
	case 'status':
	default:
		//Estadísticas
		$data['checks'] =  dbw_query_fetch_array($db_conn, "SELECT COUNT(*) FROM CHECKS")[0];
		$data['err'] =  dbw_query_fetch_array($db_conn, "SELECT COUNT(*) FROM CHKHIST WHERE code !=0 AND `Timestamp` > $datemes ")[0];
		$data['errinidate'] = date ('j/n/Y',$datemes );
		//Load lastest fails
		$failssql = dbw_query($db_conn,"SELECT * FROM CHKHIST WHERE code !=0 AND ID_C IN (SELECT ID_C FROM CHECKS) ORDER BY `timestamp` DESC LIMIT 10");
		if ($failssql != false){
			while ($fail = dbw_fetch_array($db_conn,$failssql)){ //Create array
				$fails[] = array (
					'ID_C' => $fail['ID_C'],
					'name' => nameFromIDC($fail['ID_C']),
					'groupName' => nameGroupFromIDG(IDGFromIDC($fail['ID_C'])),
					'typeCheck' => textTypeChk($T_,$fail['ID_TC']),
					'errorText' => $fail['errorText'],
					'date' => date('j/n/Y',$fail['timestamp']),
					'hour' => date('H:i',$fail['timestamp'])
				);
			};
		}else{
			$fails = array(); //Empty
		}

		renderPage('panel/p_index.twig', array('you' => $you, 'mpage' => 'index', 'data' => $data,'fails' => $fails)); //Render
	break;

}

?>