<?
// Точка входа /services/... — отдельный класс сервиса (в show_page задаётся options['class_name']), не c_page / не c_page_cabinet: редиректа на форму входа в ЛК нет.
class c_services_esmo_magnit_instruction_personals_planned_instruction
{
	function get_request_filter()
	{
		$filter=[] ;
		if (isset($_REQUEST['filter']) && is_array($_REQUEST['filter'])) $filter=$_REQUEST['filter'] ;

		$arr_names=['name','uid','type','event_id','event_name','age_from','age_to','temp_fired'] ;
		foreach($arr_names as $name) if (isset($_REQUEST[$name]) && !isset($filter[$name])) $filter[$name]=$_REQUEST[$name] ;

		$arr_multi=['org_ids','otdel_ids','working_ids','group_pers','group_medic'] ;
		foreach($arr_multi as $name)
		{
			if (isset($_REQUEST[$name]) && !isset($filter[$name]))
			{
				if (is_array($_REQUEST[$name])) $filter[$name]=$_REQUEST[$name] ;
				else if (strlen(trim((string)$_REQUEST[$name])))
				{   $filter[$name]=[] ;
					foreach(explode(',',$_REQUEST[$name]) as $id)
					{   $id=trim($id) ;
						if ($id!=='') $filter[$name][$id]=1 ;
					}
				}
			}
		}

		return $filter ;
	}

	function get_max_rows_per_response()
	{
		$def=10000 ;
		if (!isset($GLOBALS['LS_esmo_magnit_planned_instruction_max_rows_per_response'])) return $def ;
		$v=trim((string)$GLOBALS['LS_esmo_magnit_planned_instruction_max_rows_per_response']) ;
		if ($v==='') return $def ;
		$n=(int)$v ;
		return ($n>0)? $n:$def ;
	}

	function get_request_pagination()
	{
		$max=$this->get_max_rows_per_response() ;
		$limit=(isset($_REQUEST['limit']))? (int)$_REQUEST['limit']:1000 ;
		if ($limit<=0) $limit=1000 ;
		if ($limit>$max) $limit=$max ;

		$page=(isset($_REQUEST['page']))? (int)$_REQUEST['page']:1 ;
		if ($page<=0) $page=1 ;

		$offset=(isset($_REQUEST['offset']))? (int)$_REQUEST['offset']:(($page-1)*$limit) ;
		if ($offset<0) $offset=0 ;

		return ['limit'=>$limit,'page'=>$page,'offset'=>$offset] ;
	}

	function check_access_token()
	{
		$secret=isset($GLOBALS['LS_esmo_magnit_planned_instruction_access_token'])? trim((string)$GLOBALS['LS_esmo_magnit_planned_instruction_access_token']):'' ;
		if ($secret==='') return true ;

		$provided='' ;
		if (function_exists('getallheaders'))
		{   $headers=@getallheaders() ;
			if (is_array($headers)) foreach ($headers as $k=>$v)
				if (strtolower($k)==='authorization')
				{   if (preg_match('/^\s*Bearer\s+(\S+)/i',$v,$m)) $provided=trim($m[1]) ;
					else $provided=trim($v) ;
					break ;
				}
		}
		if ($provided==='' && isset($_REQUEST['access_token'])) $provided=(string)$_REQUEST['access_token'] ;

		return hash_equals($secret,$provided) ;
	}

	function show()
	{
		if (!$this->check_access_token())
		{   if (ob_get_length()) ob_clean() ;
			header('HTTP/1.0 401 Unauthorized') ;
			header('Content-Type: application/json; charset=utf-8') ;
			echo json_encode(array('error'=>'Unauthorized'),JSON_UNESCAPED_UNICODE) ;
			exit ;
		}
		include_once(_DIR_EXT.'/esmo_magnit_instruction/report_personals_planned_instruction.php') ;
		$report_obj=new report_personals_planned_instruction(['filter'=>$this->get_request_filter()]) ;
		$pagination=$this->get_request_pagination() ;
		$max_rows=$this->get_max_rows_per_response() ;
		$options=[] ;
		$options['limit']='limit '.$pagination['offset'].', '.$pagination['limit'] ;

		$usl=$report_obj->create_usl_select_obj('', $options) ;
		$total=(int)$report_obj->get_cnt_items($usl,$options) ;
		$recs=$report_obj->get_items($usl,$options) ;

		$items=[] ;
		if (_sizeof($recs)) foreach($recs as $rec) $items[]=$report_obj->get_export_row($rec) ;

		if (ob_get_length()) ob_clean() ;
		header('Content-Type: application/json; charset=utf-8') ;
		echo json_encode(array('meta'=>array('total'=>$total,
											 'count'=>_sizeof($items),
											 'limit'=>$pagination['limit'],
											 'offset'=>$pagination['offset'],
											 'page'=>$pagination['page'],
											 'pages'=>($pagination['limit'])? ceil($total/$pagination['limit']):0,
											 'has_next'=>(($pagination['offset']+_sizeof($items))<$total)? 1:0,
											 'max_rows_per_response'=>$max_rows
										),
						 'items'=>$items
					),JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) ;
		exit ;
	}

}

?>
