<?php
if (!file_exists(__DIR__ .'/config/config.php')){
    header('location: install.php');
}
require_once 'functions.php';
if (!isset($_SESSION['user'])){
    header('Location: index.php');
}


if ($_POST){ //Aquí limpieza de los campos POST y GET
    foreach ($_POST as $key => $value){
        $_POST[$key] = cleanData($_POST[$key]);
    }
}
if ($_GET){ //Aquí limpieza de los campos POST y GET
    foreach ($_GET as $key => $value){
        $_GET[$key] = cleanData($_GET[$key]);
    }
}

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

switch ($namepage){
    case 'savenewserver':
        //Here, checks
        if ($_POST['name']){ //Input checking
            list($name,$ip,$so,$description) = array($_POST['name'],$_POST['IP'],$_POST['so'],$_POST['description']);

            $db_conn = dbconn(); //Connect


            //Check if server exists
            $count = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM SERVERS WHERE IP='$ip'")[0];
            if ($count){
                sendmsg('error','Este servidor ya existe!');
            }else{
                $result = dbw_query($db_conn,"INSERT INTO SERVERS (`Name`,IP,SO,`Description`) VALUES ('$name','$ip','$so','$description')");
				
                if ($result){ //If query ran
                    $ID_SERV = dbw_last_id($db_conn);
                    sendmsg('ok','Servidor añadido con éxito');
					if ($_POST['ssh']){
						$sshport = (int)$_POST['ssh'];
						dbw_query($db_conn,"UPDATE SERVERS SET SSHPort = '$sshport' WHERE ID_SERV='$ID_SERV'");
					}

                    if ($_POST['userserv'] != "" && $_POST['passw'] != ""){
                        $user = addslashes ($_POST['userserv']);
                        $IV = randomString(16); //For secure encoding
                        $password = encodePassword($_POST['passw'],$IV);
                        dbw_query($db_conn,"UPDATE SERVERS SET `User`='$user', `Password` = '$password',`IV`='$IV' WHERE ID_SERV='$ID_SERV'");
                        $RETRIEVE_DATA = $ID_SERV;
                        require 'cron/cron.php'; #run cron for new server to retrieve data
                        #exec("php -f ".dirname(__FILE__).'/cron/cron.php '.$ID_SERV); //Retrieve data
                    }
                }else{
                    sendmsg('error','Error al añadir el servidor a la base de datos');
                }
            }
        }

    //break; //For add another.?

    case 'newserver':
        $db_conn = dbconn();
        $sql = dbw_query ($db_conn,"SELECT * FROM GROUPS");
        while ($line = dbw_fetch_array($db_conn,$sql)){
            $groups[] = $line;
        }
        if (!isset($groups)){
            $groups = array();
        }
        renderPage('a_newserver.twig',array('mode' => 'new'));
    break;

    case 'deleteserver':
        $ID_SERV = (int)$_GET['id_serv'];
        if ($ID_SERV == 0){
            sendmsg('error', 'Parametros incorrectos');
        }else{
            if (getPerm('PE_admin')){
                $db_conn = dbconn();
                dbw_query($db_conn,"DELETE FROM ALERTS WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM MAIL WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM S_HDDSTAT WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM S_HISTPING WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM S_HISTRAM WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM S_HISTSERVICES WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM S_SERVICES WHERE ID_SERV='$ID_SERV'");
                dbw_query($db_conn,"DELETE FROM SERVERS WHERE ID_SERV='$ID_SERV'");
                sendmsg('ok','Servidor eliminado con éxito');
            }else{
                sendmsg('error', 'No tienes permisos');
            }
        }

        header('Location: admin.php');

    break;

    case 'saveeditserver':
        //Here, checks
        if (isset($_GET['id_serv'],$_POST['name'])){ //Input checking
            list($ID_SERV,$name,$ip,$description) = array((int)$_GET['id_serv'],$_POST['name'],$_POST['IP'],$_POST['description']);


            $db_conn = dbconn(); //Connect


            dbw_query($db_conn,"UPDATE SERVERS SET `Name`='$name',`IP`='$ip', `Description`='$description' WHERE ID_SERV='$ID_SERV'");
			if ($_POST['ssh']){
				$sshport = (int)$_POST['ssh'];
				dbw_query($db_conn,"UPDATE SERVERS SET SSHPort = '$sshport' WHERE ID_SERV='$ID_SERV'");
			}
            if ($_POST['userserv'] != "" && $_POST['passw'] != ""){
                $user = addslashes ($_POST['userserv']);
                $IV = randomString(16);
                $password = encodePassword($_POST['passw'],$IV);
                dbw_query($db_conn,"UPDATE SERVERS SET `User`='$user', `Password` = '$password',`IV`='$IV' WHERE ID_SERV='$ID_SERV'");

            }
            sendmsg('ok','Servidor editado');
        }else{
            sendmsg('error','Te faltaban campos por poner o son incorrectos');
        }
        header('Location: admin.php?page=servers&id_serv='.$ID_SERV); //Go to server page

    break;

    case 'editserver':
        $db_conn = dbconn();
        $server = serverData((int)$_GET['id_serv']);
        renderPage('a_newserver.twig',array('mode' => 'edit','server' => $server));

    break;

    case 'users':
        $db_conn = dbconn();

        if (isset($_POST['pass1']) && ($_POST['pass1'] == $_POST['pass2']) ){ //Si se quiere cambiar la contraseña propia
            $ID_U = $_SESSION['user']['ID_U'];
            $password = hash("sha256",$ID_U.$_POST['pass1']); //Password with salt (id_u)
            dbw_query($db_conn,"UPDATE USERS SET `Password`='$password' WHERE ID_U='$ID_U'");
            sendmsg('ok','Contraseña cambiada correctamente.');
        }
        else if (isset($_POST['name']) && $_POST['password']){ //Si rellenó el formulario de nuevo usuario
            $name = $_POST['name'];
            $checkuser = dbw_query($db_conn,"SELECT * FROM USERS WHERE `Name`='$name'");
            $checkuser = dbw_num_rows($db_conn,$checkuser);
            if ($checkuser){
                sendmsg('error','El usuario ya existe');
            }else{
                dbw_query($db_conn,"INSERT INTO USERS (`Name`,`Password`,`Enabled`) VALUES('$name','x','1')");
                $id_u = dbw_last_id($db_conn);
                $password = hash("sha256",$id_u.$_POST['password']); //Password with salt (id_u)
                dbw_query($db_conn,"UPDATE USERS SET `Password`='$password' WHERE ID_U='$id_u'");
                sendmsg('error','Usuario creado correctamente.');
            }
        }else if (isset($_GET['delete'])){
            $deleteid = (int)$_GET['delete'];
            if(getPerm('PE_admin')){ //Solo puede borrar el administrador
                dbw_query($db_conn,"DELETE FROM USERS WHERE ID_U='$deleteid'");
                sendmsg('ok','Usuario borrado correctamente');
            }else{
                sendmsg('error','Sin permisos para borrar usuarios');
            }

        }


        //Datos de usuarios
        if (getPerm('PE_admin')){
            $sql = dbw_query($db_conn,"SELECT * FROM USERS");
            while ($line = dbw_fetch_array($db_conn,$sql)){
                $users[] = $line;
            }
        }else{ //No tiene permiso más que para verse a si mismo
            sendmsg('info','Solo podrás ver tu usuario ya que no eres administrador');
            $users[] = $_SESSION['user'];
        }

        renderPage('a_users.twig',array("users" => $users));

    break;


    case 'servers':
        $db_conn = dbconn();
        $ID_SERV = (int)$_GET['id_serv'];

        if ($ID_SERV == 0){ //Not valid
            renderPage('err_404.twig');
            die();
        }

        $server = serverData($ID_SERV); //Load server data
        if ($server == NULL){ //Not valid
            renderPage('err_404.twig');
            die();
        }

        /*list($pas,$ivv) = dbw_query_fetch_array($db_conn,"SELECT `Password`,IV FROM SERVERS WHERE ID_SERV='$ID_SERV'");
        sendmsg('debug',decodePassword($pas,$ivv));*/


        if (isset($_GET['do'],$_GET['name']) && $_GET['do'] =='deletesvc'){
            $name = $_GET['name'];
            dbw_query($db_conn,"DELETE FROM S_HISTSERVICES WHERE ID_SERV='$ID_SERV' AND `Name`='$name'");
            dbw_query($db_conn,"DELETE FROM S_SERVICES WHERE ID_SERV='$ID_SERV' AND `Name`='$name'");
            $typeS = 'SERVICE.'.$name;
            dbw_query($db_conn,"DELETE FROM P_ALERTS WHERE ID_SERV='$ID_SERV' AND `Type`='$type' AND `Param`='$service'");
            dbw_query($db_conn,"DELETE FROM MAIL WHERE ID_SERV='$ID_SERV' AND `Type`='$typeS'");
        }else if (isset($_POST['groupsel']) && $_GET['do'] == 'changegrp'){
            sendmsg('ok','Grupos cambiados');
            dbw_query($db_conn,"DELETE FROM S_INGROUP WHERE ID_SERV='$ID_SERV'");
            $groupsel = $_POST['groupsel'];
            foreach ($groupsel as $grpid=>$value) {
                dbw_query($db_conn,"INSERT INTO S_INGROUP (ID_G,ID_SERV) VALUES('$value','$ID_SERV')");
            }
        }else if (isset($_GET['name'],$_GET['do']) && $_GET['do'] == 'togglesvc'){
            
            $namesrv = $_GET['name'];
            toggle_server_svc($ID_SERV,$namesrv);
            sendmsg('ok','Hecho. Por favor, refresca los datos del servidor en unos segundos');
            
        }else if ($ID_SERV != 0 && isset($_POST['name'], $_POST['descr'])){ //If form of new service was filled
            $name = $_POST['name'];
            $descr = $_POST['descr'];

            $count = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM S_SERVICES WHERE ID_SERV='$ID_SERV' AND `Name`='$name'")[0];
            if ($count){
                sendmsg('error','Ya hay un servicio con ese nombre');
            }else{
                dbw_query($db_conn,"INSERT INTO S_SERVICES(ID_SERV,`Name`,`Type`,`Description`) VALUES ('$ID_SERV','$name','SERVICE','$descr')");
                sendmsg('ok','Servicio añadido con éxito');
            }
        }

        //Load services
        $servicessql = dbw_query($db_conn,"SELECT * FROM S_SERVICES WHERE ID_SERV = '$ID_SERV'");

        if (dbw_num_rows($db_conn,$servicessql) == 0){
            $services = array(); //Empty, no services
        }
        while ($line = dbw_fetch_array($db_conn,$servicessql)){

            $all = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM S_HISTSERVICES WHERE ID_SERV='$ID_SERV' AND `Name`='$line[Name]'")[0];
            if ($all){
                $on = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM S_HISTSERVICES WHERE ID_SERV='$ID_SERV' AND `Name`='$line[Name]' AND `Status`=1")[0];
                $uptimepercent = round(($on / $all)  * 100,2);
            }else{ //Si no hay histórico
                $uptimepercent = "NODATA";
                $line['Status'] = "NULL";
               
            }
            $services[] = array ( 
                'ID_SERV' => $line['ID_SERV'],
                'Enabled' => $line['Enabled'],
                'Name' => $line['Name'],
                'Status' => $line['Status'],
                'Description' => $line['Description'],
                'UptimePercent' => $uptimepercent
            );

        }

        //Load ram history
        $ramsql = dbw_query($db_conn,"SELECT * FROM S_HISTRAM WHERE ID_SERV = '$ID_SERV' ORDER BY `Timestamp` DESC LIMIT 30");

        if (dbw_num_rows($db_conn,$ramsql) == 0){
            $histram = array(); //Empty, no services
        }
        while ($line = dbw_fetch_array($db_conn,$ramsql)){

            $histram[] = array ( 
                'ID_SERV' => $line['ID_SERV'],
                'Timestamp' => timestampToHuman($line['Timestamp']),
                'Freeram' => bytesToHuman($line['Freeram'],0,1),
                'Detram' => bytesToHuman($line['Detram'],0,1)
            );

        }

        //Load group names
        $groups = array();
        $sql = dbw_query($db_conn,"SELECT ID_G,`Name` FROM GROUPS");
        while ($line = dbw_fetch_array($db_conn,$sql)){
            $groups[] = array ( 
                'ID_G' => $line['ID_G'],
                'Name' => $line['Name']
            );
        }


        renderPage('a_server.twig',array("server" => $server,"services" => $services, "histram" => $histram, 'groups' => $groups));
    break;

    case 'settings':

        if (getPerm('PE_admin')){
            if ($_POST){
                $hdd = (int)$_POST['alerthdd'];
                $ram = (int)$_POST['alertram'];
                $autodelete = (int)$_POST['autodelete'];
                dbw_query(dbconn(),"UPDATE SYS SET `Value`='$hdd' WHERE `Option`='HDDALERT'");
                dbw_query(dbconn(),"UPDATE SYS SET `Value`='$ram' WHERE `Option`='RAMALERT'");
                dbw_query(dbconn(),"UPDATE SYS SET `Value`='$autodelete' WHERE `Option`='AUTODELETE'");
            }
            list($sys['HDDALERT'],$sys['RAMALERT'],$sys['AUTODELETE']) = array(percalertfor('HDD'),percalertfor('RAM'),getsysopt('AUTODELETE') );
            renderPage('a_settings.twig',array('sys' => $sys));
        }else{ //No tiene permiso más que para verse a si mismo
            sendmsg('error','No eres administrador');
            renderPage('err_403.twig');
        }

    break;

    case 'groups':
    $db_conn = dbconn();

        if (isset($_GET['do'], $_GET['id_g']) && $_GET['do'] == 'deletegrp'){
            $ID_G = (int)$_GET['id_g'];
            dbw_query($db_conn,"DELETE FROM GROUPS WHERE ID_G='$ID_G'");
        }else if (isset($_GET['do'], $_GET['id_g'],$_POST['name'.$_GET['id_g']]) && $_GET['do'] == 'changename' && $_POST['name'.$_GET['id_g']] != ""){
            $ID_G = (int)$_GET['id_g'];
            $name = $_POST['name'.$ID_G];
            dbw_query($db_conn,"UPDATE GROUPS SET `Name`='$name' WHERE ID_G='$ID_G'");
        }

        if (isset($_POST) && isset($_POST['newgrp'])){
            dbw_query($db_conn,"INSERT INTO GROUPS (`Name`) VALUES('$_POST[newgrp]')");
        }

        //Load group names
        $groups = array();
        $sql = dbw_query($db_conn,"SELECT ID_G,`Name` FROM GROUPS");
        while ($line = dbw_fetch_array($db_conn,$sql)){
            $groups[] = array ( 
                'ID_G' => $line['ID_G'],
                'Name' => $line['Name']
            );
        }

        renderPage('a_groups.twig', array('groups' => $groups));
    break;

    //"Home"
    case 'index':
    default:
        $db_conn = dbconn();

        //Calculemos estadísticas
        $servs = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM SERVERS")[0];
        
        //Sacar datos de cada servidor
        $serverssql = dbw_query($db_conn,"SELECT ID_SERV FROM SERVERS"); //Todos los ID_SERV
        $numrows['all'] = dbw_num_rows($db_conn,$serverssql);
        $numrows['on'] = 0;
        $numrows['enabled'] = dbw_query_fetch_array($db_conn,"SELECT COUNT(*) FROM SERVERS WHERE `Enabled`=1")[0];

        $SEnabled = 0;
        $STotal = 0;
        $SActive = 0;

        while ($id = dbw_fetch_array($db_conn,$serverssql)){
            $server = serverData($id['ID_SERV']);
            if ($server['Online']){$numrows['on']++;}
            $servers[$id['ID_SERV']] = $server; //Insert data array

            $STotal += $server['STotal'];
            $SEnabled += $server['SEnabled'];
            $SActive += $server['SActive'];
        }
        $numrows['off'] = $numrows['all'] - $numrows['on'];

        $numrows['allsensors'] = $STotal + $numrows['all'];
        $numrows['activesensors'] = $SActive + $numrows['on'];

        if (!isset($servers)){
            $servers = NULL;
        }
        renderPage('a_index.twig',array('servers' => $servers,'numrows' => $numrows));
    break;
}

?>