<?php

header('Content-Type: application/json');

require_once  '../../../Config/odbc.php';
require_once  '../../utils.php';
require_once  '../../global.php';


$response = [];
$response['success'] = false;

if ( !isset($_POST['username'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	$response['message'] = 'Please fill both the username and password field!';
	echo json_encode($response);
	exit();
}

class ActiveSessionData 
{
	function __construct()
	{
	}

  function initData()
  {

    //exam filter list
    $modlist = array('rx','mg','ct','nm');
    foreach ($modlist as $mod) {
      if(isset($_SESSION['exam_'.$mod.'_filter']) == false)
      {
        $_SESSION['filter_'.$mod.'_data'] = array();
        $_SESSION['filter_'.$mod.'_data']['datefrom'] = date("d/m/Y");
				$_SESSION['filter_'.$mod.'_data']['dateto'] = date("d/m/Y");
      }
    }

		//fetch licence, if failed initialize with test value;
		//php check are only for visual purpose
		$_SESSION[LICENCE_MAXMODALITY] = 0;
		$_SESSION[LICENCE_EXPIREDATE] = '29991231';
		$_SESSION[LICENCE_MAXMODALITY] = get_number_of_modality();
		$conn = get_dbconnection();
		if($conn)
		{
		  $sql = "select data1, to_char(to_date(validitydate,'YYYYMMDD'),'DD/MM/YYYY') from licencemanager where lower(data2) = 'eodacs'";

		  if($query=pg_query($conn,$sql))
		  {
		    if($row = pg_fetch_row($query))
		    {
					$_SESSION[LICENCE_MAXMODALITY] = $row[0];
					$_SESSION[LICENCE_EXPIREDATE] = $row[1];
					$ok = true;
				}
			}
		}
		$this->initUserAccess();
	}

	function initUserAccess()
	{
			$conn = get_dbconnection();
			if($conn)
			{
					// 	$sql = "select theaccess.inst_id,v_fullinfo_department.inst_name, v_fullinfo_department.dep_name, alldep::integer from (
				 // select inst_id,taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) as alldep,dep_id, sum((tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]))::integer) over (partition by inst_id) as nbr
				 // from v_taglink_instdep  where taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) or tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) and instordepremoved  = false
				 // ) theaccess,v_fullinfo_department where theaccess.inst_id = v_fullinfo_department.inst_id and v_fullinfo_department.dep_id = theaccess.dep_id and instordepremoved = false;";

				 $sql = " select distinct inst_id,instname,dep_id,depname, (bool_and(selected) over (partition by inst_id))::integer,selected ::integer
 from (select institution.name as instname, institution.inst_id,department.name as depname, department.dep_id, room.name as roomname
 , modality.mod_id, bool_and(modality.mod_id = any('{{$_SESSION['filter_modalitylist']}}'::integer[])) over (partition by department.dep_id) as selected
 from modality,room,department,institution
 where institution.removed = false and room.removed  = false and department.removed = false and modality.removed = false and
 institution.inst_id = department.inst_id and department.dep_id  = room.dep_id  and room.room_id = modality.room_id and institution.inst_id != -1) selectedfilter
 order by instname,depname";

				$listInstitution = array();
				if($query = pg_query($conn,$sql))
				{
					while($row = pg_fetch_row($query))
					{
			        if(!array_key_exists($row[0],$listInstitution))
			        {
			          $tt = new stdClass();
			          $tt->name =trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
								$tt->checked = $row[4];
			          $tt->children = array();
			          $listInstitution[$row[0]] = $tt;
			        }
							$institution = &$listInstitution[$row[0]];
							$child = new stdClass();
							$child->name = trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[3],ENT_QUOTES)));
							$child->selected = $row[5];
							$institution->children[] = $child;
					}
				}

				$_SESSION['useraccessdetails'] = $listInstitution;

				

				global $_All;
				global $_None;
				$_SESSION['alertfilter_group_name'] = $_None;
				$_SESSION['alertfilter_group_id'] = '-2';
				$_SESSION["alertfilter_group_pro_id"] = '';

				$sql = " select string_agg(pro_id::text,','),alertfilter_group.name,alertfilter_group.afg_id from alertfilter_group,alertfilter_group_link,account,modality_profile,modality_identity where alertfilter_group_link.afg_id = account.alertfilter_group_id
							 and  modality_profile.modident_id = modality_identity.modident_id and modality_identity.mod_id = alertfilter_group_link.mod_id and alertfilter_group.afg_id  = alertfilter_group_link.afg_id
							 and  acc_id= {$_SESSION['id']} group by alertfilter_group.afg_id,alertfilter_group.name";

				if($query=pg_query($conn,$sql))
				{
					if($row = pg_fetch_row($query))
					{
						$_SESSION['alertfilter_group_pro_id'] = $row[0];
						$_SESSION['alertfilter_group_name'] =  trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
						$_SESSION['alertfilter_group_id'] = $row[2];
						$ok = true;
					}
				}
		 }
  	}
}

$conn = get_dbconnection();

if($conn)
{
	$_POST['password'] = trim($_POST['password']);
	$_POST['username'] = trim($_POST['username']);

	$result = pg_prepare($conn, "query", "SELECT lastname,firstname,role,acc_id,userconfig,coalesce(modlist,'-42'),password FROM account left join v_modalitylist_by_role on account.loginrole_id = v_modalitylist_by_role.lro_id  WHERE removed = false and username = $1");

	if($query = pg_execute($conn, "query", array($_POST['username'])))
	{
		if($row = pg_fetch_row($query))
		{
			if($_POST['password'] == $row[6] || password_verify($_POST['password'],$row[6]))
			{
				session_name("eoDACS");
				session_start();
				session_regenerate_id();

				$_SESSION['loggedin'] = TRUE;
				$_SESSION['username'] = $_POST['username'];
				$_SESSION['lastname'] = trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[0],ENT_QUOTES)));
				$_SESSION['firstname'] = trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
				$_SESSION['role'] = $row[2];
				$_SESSION['id'] = $row[3];
				if (!empty($_POST['lang'])) {
					$_SESSION['lang'] = $_POST['lang'];
				} else {
					$_SESSION['lang'] = $GLOBALS['default_language'] ?? 'fr';
				}
				
				$userconfig = json_decode($row[4], true);
				foreach($userconfig as $key => $value) {
					$_SESSION[$key] = $value; // 1 or 0
				}

				$_SESSION['filter_modalitylist'] = $row[5];

				//special IPC à généraliser
				//	$_SESSION['hide_accessionnumber_study'] = "0";
				//	$_SESSION['hide_patientid_study'] = "1";

				$session_data = new ActiveSessionData();
				$session_data->initData();
				$response['success'] = true;
				$response['message'] = 'Logged successfully';
				
				$response['id'] 				= $_SESSION['id'];
				$response['lastname'] 	= $_SESSION['lastname'];
				$response['firstname'] 	= $_SESSION['firstname'];
				$response['lang']				= $_SESSION['lang'];
			}
			else
			{
				$response['message'] = 'Failed to log in!';
			}
		}
		else 
		{
			$response['message'] = 'Failed to log in!';
		}
	}
	else
	{
		$response['message'] = 'query failed';
	}
}
else
{
	$response['message'] = 'no DB connection';
}

echo json_encode($response);

?>
