<?php
// load composer's classes
require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
// Site's configuration
require_once $_SERVER['DOCUMENT_ROOT'].'/src/config/config.php';
// load local classes
require_once $_SERVER['DOCUMENT_ROOT'].'/src/class/autoload.php';

if($_POST["Action"] != "")
{
  $Action = $_POST["Action"];
} else {
  $Action = $_GET["Action"];
}
$TOKEN = $_COOKIE["aduc"];
error_log("Action : $Action");

switch($Action)
{
  case 'validLogin':
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(validLogin($_POST["Email"],$_POST["Password"]));
    break;

  case "get_node":
    include_once("getNode.php");
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(getNode($Cfg, $_GET["id"]));
    break;

  default:
    echo "Action : ".$_POST["Action"];
}



function validLogin($sEmail, $sPassword)
{
  $ret = ['Errno' => 0, 'Errmsg' => "OK"];
  $Usr=new userClass();
  include $_SERVER['DOCUMENT_ROOT'].'/src/config/config.php';

  if($Usr->isValid($Cfg, $sEmail,$sPassword))
  { // Good credentials

    // Get a new token
    $TOKEN = uniqid("aduc_",true);
    // put it in a cookie
    setcookie("aduc",$TOKEN,time()+$Cfg['delay']);
    // Save session on redis server
    $User = ["Login" => $sEmail, "Password" => $sPassword, "Start" => date('Y-m-d H:i:s',time()), "TimeOut" => date('Y-m-d H:i:s',time()+3600)];
    $redis = new Redis();
    $redis->connect($Cfg['redishost'], 6379);
    $redis->set($TOKEN,json_encode($User));
    // load main page
    $template='main.smarty';
    $component='main';    
    return $ret;
  } else {
    return ['Errno' => -1, 'Errmsg' => 'Compte ou mot de passe invalide'];
  }
}

