<?php
    error_reporting(3);
	require_once('files/nusoap/nusoap.php');
 	require_once('files/lib/DB.config.php');
	require_once('files/lib/DBManager.class.php');
	require_once('files/lib/TicketModel.class.php');
 	
	$NAMESPACE = 'http://labmatic.networds.pl/';
	DEFINE('BASE_URL','http://labmatic.networds.pl/');

	
	 
	$server = new soap_server;
	$server->configureWSDL('ticketsWSDL', $NAMESPACE);
	$server->wsdl->schemaTargetNamespace = $NAMESPACE;
	$ini = ini_set("soap.wsdl_cache_enabled", 0);
	$server->soap_defencoding = 'UTF-8';
	$server->decode_utf8 = false;
	
	//login('admin','admin'); 
	
	$server->wsdl->addComplexType(
	    'Admin',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' => array('name'=>'id'				,'type'=>'xsd:string'),
	        'name' => array('name'=>'name'			,'type'=>'xsd:string'),
	        'password' => array('name'=>'password'	,'type'=>'xsd:string'),
	        'email' => array('name'=>'email'		,'type'=>'xsd:string')
	    )
	);
	
	$server->wsdl->addComplexType('Admins',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Admin[]')
					),
					'tns:Admin'
				);	

	//status
	$server->wsdl->addComplexType(
	    'Status',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 	=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'nazwa' => array('name'=>'nazwa'			,'type'=>'xsd:string'),
	    )
	);
	
	$server->wsdl->addComplexType('Statusy',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Status[]')
					),
					'tns:Status'
				);	
	//end of status
	
	//Kategorie
	$server->wsdl->addComplexType(
	    'Kategoria',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 	=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'nazwa' => array('name'=>'nazwa'		,'type'=>'xsd:string')
	    )
	);
	
	
	
	$server->wsdl->addComplexType('Kategorie',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Kategoria[]')
					),
					'tns:Kategoria'
				);
	//end of kategorie
	
	//priorytety
	$server->wsdl->addComplexType(
	    'Priorytet',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 	=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'nazwa' => array('name'=>'nazwa'		,'type'=>'xsd:string')
	    )
	);
	
	
	
	$server->wsdl->addComplexType('Priorytety',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Priorytet[]')
					),
					'tns:Priorytet'
				);					
		
	//user
	$server->wsdl->addComplexType(
	    'User',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 		=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'id_konta'  => array('name'=>'id_konta'		,'type'=>'xsd:string'),
			'name' 		=> array('name'=>'name'			,'type'=>'xsd:string'),
			'password'  => array('name'=>'password'		,'type'=>'xsd:string'),
			'email'  	=> array('name'=>'email'		,'type'=>'xsd:string'),
			'user_type' => array('name'=>'user_type'	,'type'=>'xsd:string')
	    )
	);	
	

	
	//Zalacznik
	$server->wsdl->addComplexType(
	    'Zalacznik',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 			=> array('name'=>'id'			,'type'=>'xsd:string'),
			'ticket_id' 	=> array('name'=>'ticket_id'	,'type'=>'xsd:string'),
	        'sciezka' 		=> array('name'=>'sciezka'		,'type'=>'xsd:string')
	    )
	);	
	
	$server->wsdl->addComplexType('Zalaczniki',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Zalacznik[]')
					),
					'tns:Zalacznik'
				);	

	
	
	//ticket
	$server->wsdl->addComplexType(
	    'Ticket',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 				=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'parent_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'kategoria_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'status_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'priorytet_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'nadawca_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'odbiorca_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'temat' 			=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'wiadomosc' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'data_wyslania' 	=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'data_odebranie' 	=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
	    )
	);
	
	$server->wsdl->addComplexType('Tickets',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:Tickets[]')
					),
					'tns:Tickets'
				);	
	//end of ticket
	
	
	//ticket extended
	$server->wsdl->addComplexType(
	    'TicketExtended',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 				=> array('name'=>'id'			,'type'=>'xsd:string'),
	        'parent_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'kategoria_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'status_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'priorytet_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'nadawca_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'odbiorca_id' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'temat' 			=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'wiadomosc' 		=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'data_wyslania' 	=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'data_odebranie' 	=> array('name'=>'nazwa'		,'type'=>'xsd:string'),
			'kategoria' 	=> array('name'=>'kategoria'		,'type'=>'xsd:string'),
			'status' 		=> array('name'=>'status'			,'type'=>'xsd:string'),
			'priorytet' 	=> array('name'=>'priorytet'		,'type'=>'xsd:string'),
			'zalaczniki' 	=> array('name'=>'zalaczniki'		,'type'=>'tns:Zalaczniki'),
			'nadawca' 		=> array('name'=>'nadawca'			,'type'=>'xsd:string'),
			'odbiorca' 		=> array('name'=>'odbiorca'			,'type'=>'xsd:string'),
	    )
	);
	
	$server->wsdl->addComplexType('TicketsExtended',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:TicketExtended[]')
					),
					'tns:TicketExtended'
				);			
				
	//end of ticket extended
	
	$server->wsdl->addComplexType(
		'ShowTicketResponse',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'ticket' 				=> array('name'=>'ticket'			,'type'=>'tns:TicketExtended'),
			'owner_id' 				=> array('name'=>'owner_id'			,'type'=>'xsd:string'),
			'child_tickets'			=> array('name'=>'ticket'			,'type'=>'tns:TicketsExtended')
			)
	    );
	
	
	$server->wsdl->addComplexType(
		'AddResponseFormResponse',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'statusy' 					=> array('name'=>'statusy'					,'type'=>'tns:Statusy'),
			'kategorie' 				=> array('name'=>'kategorie'				,'type'=>'tns:Kategorie'),
			'priorytety'				=> array('name'=>'priorytety'				,'type'=>'tns:Priorytety'),
			'parent_ticket'				=> array('name'=>'parent_ticket'			,'type'=>'tns:TicketExtended'),
			'child_tickets'				=> array('name'=>'child_tickets'			,'type'=>'tns:TicketsExtended'),
			'can_response'				=> array('name'=>'can_response'				,'type'=>'xsd:boolean')
	    )
	);		
					
	//ticket list item
	$server->wsdl->addComplexType(
	    'ticket_list_item',
	    'complexType',
	    'struct',
	    'all',
	    '',
	    array(
	        'id' 				=> array('name'=>'id'					,'type'=>'xsd:string'),
	        'parent_id' 		=> array('name'=>'parent_id'			,'type'=>'xsd:string'),
	        'kategoria_id' 		=> array('name'=>'kategoria_id'			,'type'=>'xsd:string'),
	        'status_id' 		=> array('name'=>'status_id'			,'type'=>'xsd:string'),
			'priorytet_id' 		=> array('name'=>'priorytet_id'			,'type'=>'xsd:string'),
			'nadawca_id' 		=> array('name'=>'nadawca_id'			,'type'=>'xsd:string'),
			'odbiorca_id' 		=> array('name'=>'odbiorca_id'			,'type'=>'xsd:string'),
			'temat' 			=> array('name'=>'temat'				,'type'=>'xsd:string'),
			'wiadomosc' 		=> array('name'=>'wiadomosc'			,'type'=>'xsd:string'),
			'data_wyslania' 	=> array('name'=>'data_wyslania'		,'type'=>'xsd:string'),
			'data_odebrania' 	=> array('name'=>'data_odebrania'		,'type'=>'xsd:string'),
			'odebrano' 			=> array('name'=>'odebrano'				,'type'=>'xsd:string'),
			'kategoria' 		=> array('name'=>'kategoria'			,'type'=>'xsd:string'),
			'liczba_odpowiedzi' => array('name'=>'liczba_odpowiedzi'	,'type'=>'xsd:string'),
			'status' 			=> array('name'=>'status'				,'type'=>'xsd:string'),
			'priorytet' 		=> array('name'=>'priorytet'			,'type'=>'xsd:string'),
			'zalaczniki' 		=> array('name'=>'zalaczniki'		    ,'type'=>'tns:Zalaczniki'),
			'nadawca' 			=> array('name'=>'nadawca'				,'type'=>'xsd:string'),
			'odbiorca' 			=> array('name'=>'odbiorca'				,'type'=>'xsd:string'),
			'nadawca_pelne' 	=> array('name'=>'nadawca_pelne'		,'type'=>'xsd:string'),
			'odbiorca_pelne'	=> array('name'=>'odbiorca_pelne'		,'type'=>'xsd:string')
	    )
	);	
	
	$server->wsdl->addComplexType('ticket_list_items',
					'complexType',
					'array',
					'',
					'SOAP-ENC:Array',
					array(),
					array(
						array('ref'=>'SOAP-ENC:arrayType',
						'wsdl:arrayType'=>'tns:ticket_list_item[]')
					),
					'tns:ticket_list_item'
				);
	
	$server->register(
	    'login',
	    array('name'=>'xsd:string','password'=>'xsd:string'),
	    array('return'=>'tns:User'),
	    $NAMESPACE);				
	
	$server->register(
	    'login2',
	    array('name'=>'xsd:string','password'=>'xsd:string'),
	    array('return'=>'tns:User'),
	    $NAMESPACE);
			
	$server->register(
		'getOdebrane',
	    array('user'=>'tns:User','monthCondition'=>'xsd:int'),
	    array('return'=>'tns:ticket_list_items'),
	    $NAMESPACE);
		
	$server->register(
		'getWyslane',
	    array('user'=>'tns:User','monthCondition'=>'xsd:int'),
	    array('return'=>'tns:ticket_list_items'),
	    $NAMESPACE);	

	$server->register(
		'getClientTickets',
	    array('user'=>'tns:User','accountId'=>'xsd:int'),
	    array('return'=>'tns:ticket_list_items'),
	    $NAMESPACE);
			
	$server->register(
		'showTicket',
		 array('user'=>'tns:User','ticketId'=>'xsd:int'),
		 array('return'=>'tns:ShowTicketResponse'),
		 $NAMESPACE);		
		
	$server->register(
		'addTicket',
		 array('user'=>'tns:User','ticket'=>'tns:Ticket','zalaczniki'=>'tns:Zalaczniki'),
		 array('return'=>'xsd:boolean'),
		 $NAMESPACE);
		 
	$server->register(
		'addResponse',
		 array('user'=>'tns:User','ticket'=>'tns:Ticket','zalaczniki'=>'tns:Zalaczniki'),
		 array('return'=>'xsd:boolean'),
		 $NAMESPACE);
		 
	$server->register(
		'addResponseForm',
		 array('user'=>'tns:User','$ticket_parent_id'=>'xsd:int'),
		 array('return'=>'tns:AddResponseFormResponse'),
		 $NAMESPACE);	
		 
	$server->register(
		'getMinutesToEndSession',
		 array('ticket_id'=>'xsd:int'),
		 array('return'=>'xsd:int'),
		 $NAMESPACE);	
		 
	$server->register(
		'resetSession',
		 array('ticket_id'=>'xsd:int'),
		 array('return'=>'xsd:boolean'),
		 $NAMESPACE);

	$server->register(
		'editTicketStatus',
		 array('user'=>'tns:User','ticketId'=>'xsd:int','statusId'=>'xsd:int'),
		 array('return'=>'xsd:boolean'),
		 $NAMESPACE);
	    	    
	function getAdmins()
	{
		try{
				$mysqli = DBManager::getConnection();
				$sql    = 'SELECT * FROM admin';
				$result = $mysqli->query($sql);
					if($mysqli->error)
						throw new Exception($mysqli->error);
					$data;	
					    while ($row = $result->fetch_assoc()) {
						       $data[] = $row;
						    }					
						
						return $data;
			}
		catch(Exception $e)
			{
				//echo 'Wystąpił błąd: '.$e->getMessage().'<br />';
			}
		return FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function login($name,$password)
	{
			
		try
		{
			$mysqli = DBManager::getConnection();
			$sql    = 'SELECT a.id AS id,k.id AS id_konta,a.name AS name,a.password AS password ,a.email AS email, \'admin\' AS user_type
			           FROM konta k JOIN admin a ON k.origin_id=a.id
			           WHERE a.name=\''.$name.'\' AND a.password=md5(\''.$password.'\') AND k.origin_table = \'admin\'';
					   
							   
			$result = $mysqli->query($sql);
			$data = array();
			
			if($mysqli->error)
				throw new Exception($mysqli->error);
			if($result->num_rows == 1)
			{
				$user 				= $result->fetch_assoc();
				return check_result_if_not_null($user);				
			}
			$result->close();
		}	
		catch(Exception $e)
		{
			//echo 'Error'.$e->getMessage().'<br />';							
		}	
		return FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function login2($name,$password)
	{
			
		try
		{
			$mysqli = DBManager::getConnection();
			$sql    = 'SELECT a.id AS id,k.id AS id_konta,a.name AS name,a.password AS password ,a.email AS email, \'admin\' AS user_type
			           FROM konta k JOIN admin a ON k.origin_id=a.id
			           WHERE a.name=\''.$name.'\' AND a.password=\''.$password.'\' AND k.origin_table = \'admin\'';
					   
							   
			$result = $mysqli->query($sql);
			$data = array();
			
			if($mysqli->error)
				throw new Exception($mysqli->error);
			if($result->num_rows == 1)
			{
				$user 				= $result->fetch_assoc();
				return check_result_if_not_null($user);
										
			}
			$result->close();
		}	
		catch(Exception $e)
		{
			//echo 'Error'.$e->getMessage().'<br />';							
		}	
		return FALSE;
	}	
	/*----------------------------------------------------------------------------------------------------------------*/
	function getOdebrane($user,$monthCondition=null)
	{
		if(login2($user['name'],$user['password']))
		{
			$ticketModel = new TicketModel();
			
			try
			{
				$ids = $ticketModel->get_received_list_of_ticket_id($user['id_konta'],$monthCondition);
				$data = array();
				
				for($i=0;$i<count($ids);$i++)
				{
					$ticket = $ticketModel->get_ticket_list_item((int)$ids[$i],$monthCondition);
					$ticket['parent_id']  = (is_null($ticket['parent_id']) ? 0:$ticket['parent_id']);
					$ticket['zalaczniki'] = $ticketModel->get_attachment_list($ticket['id']);
					$data[] = $ticket;
				}
				
				return check_result_if_not_null($data);
			}
			catch(Exception $e)
			{
				//echo 'Error'.$e->getMessage().'<br />';							
			}	
			return FALSE;	
		}
		else
			return FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/			
	function getWyslane($user,$monthCondition=null)
	{
		if(login2($user['name'],$user['password']))
		{
			$ticketModel = new TicketModel();
			
			try		
			{
				$ids 	= $ticketModel->get_sended_list_of_ticket_id($user['id_konta'],$monthCondition);
				$data 	= array();

                
                
				for($i=0;$i<count($ids);$i++)
				{
					//if($i<count($ids))
					//	$data[] = $ticketModel->get_received_ticket_list_item((int)$ids[$i],$monthCondition);
					$ticket = $ticketModel->get_ticket_list_item((int)$ids[$i],$monthCondition);
                    
					$ticket['zalaczniki'] = $ticketModel->get_attachment_list($ticket['id']);
					$data[] = $ticket;							
				}
				return check_result_if_not_null($data);			
			}
			catch(Exception $e)
			{
				//echo 'Error'.$e->getMessage().'<br />';							
			}	
			return FALSE;	
		}
		else
			return FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function getClientTickets($user,$account_id)
	{
		if(login2($user['name'],$user['password']))
		{
			try
			{
				$ticketModel = new TicketModel();
				$account 	 = $ticketModel->get_account($account_id);
				$data    	 = array();
				
				if(is_array($account) && ($account['origin_table'] == 'user'))
				{
					$data = $ticketModel->get_tickets($account_id);
				} 	
				if(is_array($data) && (count($data)>0))
				{
					foreach($data as $k=>$v)
						$data[$k]['zalaczniki'] = $ticketModel->get_attachment_list($v['id']);
				}
				return check_result_if_not_null($data);					
			}
			catch(Exception $e)
			{
				//print_r($e);
				return FALSE;				
			}
			return TRUE;
		}
		else
			return FALSE;		
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	//zwraca dane ticketa - parent + liste danych ticketów zwiazanych - childs
	function showTicket($user,$ticketId)
	{
		$ticketModel = new TicketModel();
		if(login2($user['name'],$user['password']) && $user['user_type'] = 'admin' /*&& $ticketModel->does_user_have_permision_to_ticket($ticketId,$user['id_konta'])*/)
		{
			$data					=	array();
			$data['ticket']			= $ticketModel->get($ticketId);
			
			if(empty($data['ticket']['data_odebrania']) && ($data['ticket']['odbiorca_id']==$user['id_konta']))
                $ticketModel->set_data_odebrania($ticketId);
			
			$ticketModel->clear_ticket_owners_session();	//czyszczenie starych sesji odpowiedzi do ticketów
			$data['owner_id']		= $ticketModel->get_ticket_owner($ticketId);	

            
            
			if(!empty($data['ticket']['parent_id']))
				{
                    
					$data['ticket']	= $ticketModel->get($data['ticket']['parent_id']);
					$ticketId       = $data['ticket']['id'];
				}


	
			$data['child_tickets'] 			= $ticketModel->get_child_tickets_by($ticketId);
            if(!empty($data['child_tickets']))
            {
                //$ticketModel->set_data_odebrania($data['child_tickets'][count($data['child_tickets'])-1]['id']);
				foreach($data['child_tickets'] as $k=>$v)
					if($v['odbiorca_id'] == $user['id_konta'])
						$ticketModel->set_data_odebrania($v['id']);
            }
			$data['ticket']['zalaczniki']	= $ticketModel->get_attachment_list($ticketId);
			
			if(is_array($data['child_tickets']) && count($data['child_tickets']) > 0)
			{
				foreach($data['child_tickets'] as $k=>$v)
					$data['child_tickets'][$k]['zalaczniki'] = $ticketModel->get_attachment_list($v['id']);
			}

			return check_result_if_not_null($data);	
		}
		else
			echo FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function addTicket($user,$ticket,$zalaczniki)
	{
		//add($nadawca,$odbiorca,$kategoria,$status,$priorytet,$temat,$wiadomosc,$files,$parent_id=0)
		//print_r($ticket);
		
		if(login2($user['name'],$user['password']))
		{
			try
			{
				$ticketModel = new TicketModel();
				
				if(!$ticketModel->add($ticket['nadawca_id'],$ticket['odbiorca_id'],$ticket['kategoria_id'],$ticket['status_id'],$ticket['priorytet_id'],$ticket['temat'],$ticket['wiadomosc'],$zalaczniki))
					throw new Exception();
				
				
				//nadawca
				$status_name 		= $ticketModel->get_status_name_by_id($ticket['status_id']);
				$nadawca_email		= $ticketModel->get_user_email_by_account_id($ticket['nadawca_id']);
				$nadawca_type   	= $ticketModel->get_user_type_by_account_id($ticket['nadawca_id']);
                //send_email($ticket_id,$status_name,$ticket['kategoria_id'],$nadawca_email,$nadawca_type); //do nadawcy
				
				//odbiorca					
				$odbiorca_email		= $ticketModel->get_user_email_by_account_id($ticket['odbiorca_id']);
				$odbiorca_type   	= $ticketModel->get_user_type_by_account_id($ticket['odbiorca_id']);
				//send_email($ticket_id,$status_name,$ticket['kategoria_id'],$odbiorca_email,$odbiorca_type);
				
			}
			catch(Exception $e)
			{
				//var_dump($e);
				return FALSE;				
			}
			return TRUE;
		}
		else
			return FALSE;
		
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function addResponse($user,$ticket,$zalaczniki)
	{
		
		if(login2($user['name'],$user['password']))
		{
			
			try
			{
							
				$ticketModel = new TicketModel();
				
				if(!$ticketModel->add($ticket['nadawca_id'],$ticket['odbiorca_id'],$ticket['kategoria_id'],
				        $ticket['status_id'],$ticket['priorytet_id'],$ticket['temat'],
				        $ticket['wiadomosc'],$zalaczniki,$ticket['parent_id']))		
					throw new Exception();
					
				//usuniecie sesji ticket ownera
				$ticketModel->delete_ticket_owner_session($parent_id);

				//wysylanie wiadomosci email
				//nadawca
				$status_name 		= $ticketModel->get_status_name_by_id($ticket['status_id']);
				$nadawca_email		= $ticketModel->get_user_email_by_account_id($ticket['nadawca_id']);
				$nadawca_type   	= $ticketModel->get_user_type_by_account_id($ticket['nadawca_id']);
				//send_email($ticket['parent_id'],$status_name,$ticket['kategoria_id'],$nadawca_email,$nadawca_type); //do nadawcy
                
				
				//odbiorca					
				$odbiorca_email		= $ticketModel->get_user_email_by_account_id($ticket['odbiorca_id']);
				$odbiorca_type   	= $ticketModel->get_user_type_by_account_id($ticket['odbiorca_id']);
				//send_email($ticket['parent_id'],$status_name,$ticket['kategoria_id'],$odbiorca_email,$odbiorca_type);

                //echo $nadawca_email;

                
			}
			catch(Exception $e)
			{
                //echo $e;
				return FALSE;
			}
			return TRUE;	
		}
		else
			return FALSE;
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function addResponseForm($user,$ticket_parent_id)
	{
		if(login2($user['name'],$user['password']))
		{
						
			$ticketModel 				= new TicketModel();
			$data						= array();
			$data['statusy']			= $ticketModel->get_status_list();
			$data['kategorie']			= $ticketModel->get_category_list();
			$data['priorytety']			= $ticketModel->get_priority_list();
			
			$data['parent_ticket']					= $ticketModel->get($ticket_parent_id);
			$data['parent_ticket']['zalaczniki']	= $ticketModel->get_attachment_list($ticket_parent_id);
			
			
			$data['child_tickets'] 		= $ticketModel->get_child_tickets_by($ticket_parent_id);
			
					
			if(count($data['child_tickets'] ))
			{		
				foreach($data['child_tickets'] as $key=>$value)
				{
					$data['child_tickets'][$key]['zalaczniki']	=	$ticketModel->get_attachment_list($value["id"]);	
				}	
			}
			
			
			$data['can_response'] 		= false;		
			
			//ustawienie ownera - gdy admin
			if($user['type'] == 'admin')
			{
				$owner_id = $ticketModel->get_ticket_owner($ticket_parent_id);
				if(empty($owner_id))
				{
					$ticketModel->set_owner($data['user_account']['id'],$ticket_parent_id);
					$data['can_response'] = true;
				}
				else
				{
					if($user['id_konta'] == $owner_id)
					{
						$data['can_response'] = true;
						//update session
						$ticketModel->update_ticket_owner($ticket_parent_id);
					}
					else
					{
						$data['can_response'] = false;						
					}
				}
			}
			return check_result_if_not_null($data);			
			
		}	
		else
			return FALSE;		
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function getMinutesToEndSession($ticketId)
	{
		if(login2($user['name'],$user['password']))
		{
			$ticketModel = new TicketModel();
			$data		 =	$ticketModel->get_minutes_to_end_session($ticket_id);
			
			return check_result_if_not_null($data);
	 
		}
		else
			return -1;	
	}
	/*----------------------------------------------------------------------------------------------------------------*/
	function resetSession($ticketId)
	{
		if(login2($user['name'],$user['password']))
		{
			$ticketModel = new TicketModel();
			if($ticketModel->update_ticket_owner($ticket_id))
				return TRUE;
			else
				return FALSE;
		}
		else
			return FALSE;			
	}	
	/*----------------------------------------------------------------------------------------------------------------*/
    function editTicketStatus($user,$ticketId,$statusId)
    {
		if(login2($user['name'],$user['password']))
		{

			$ticketModel 				= new TicketModel();
			$data						= array();
            try
            {
                if($ticketModel->editStatus($ticketId,$statusId))
                    return TRUE;
                else
                    return FALSE;
            }
			catch(Exception $e)
			{
				return FALSE;
			}
		}
		else
			return FALSE;
    }
	/*----------------------------------------------------------------------------------------------------------------*/
	// Use the request to (try to) invoke the service
	$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
	$server->service($HTTP_RAW_POST_DATA);
	
	
	//$us = login('test','test');
	/*
                $t['parent_id'] = "";
                $t['kategoria_id'] = "1";
                $t['nadawca_id'] = "48";
                $t['odbiorca_id'] = "48";
                $t['priorytet_id'] = "1";
                $t['status_id'] = "1";
                $t['temat'] = "WStest";
                $t['wiadomosc'] = "wiadomosc testowa";

				$z = array();
                $z['id'] 		= 99;
                $z['sciezka'] = "test/test2.jpg";

                $zals[] = $z;

*/
    
	//var_dump($us);
	//echo '<br/><hr/>';
	
	//print_r(getOdebrane($us));
    //echo '<br/><hr/>';
    //print_r(showTicket($us,1));

	//echo '<br/><hr/>';
	//print_r(getWyslane($us));
    //print_r(getWyslane($us));
    
	//echo '<br/><hr/>';
	//print_r(showTicket($us,147));
    
	//echo '<br/><hr/>';
	//var_dump(addTicket($us,$t,$zals));
	/*echo '<br/><hr/>';
	var_dump(addResponseForm($us,111));
	echo '<br/><hr/>';
	print_r(getMinutesToEndSession(1));
	echo '<br/><hr/>';
	print_r(resetSession(1));
	echo '<br/><hr/>';	*/
	//var_dump(addResponse($us,$t,$z));
	/*echo '<br/><hr/>';
	print_r(getClientTickets($us,4));
	echo '<br/><hr/>';
	print_r(showTicket($us,111));
		*/			
	
				
	//print_r(addResponseForm($us,1));
	//print_r(showTicket($us,6));
	//var_dump($us);
	//print_r(add(22,23,1,1,1,'XoX','Xcxc',null,0));
	//var_dump(getOdebrane());
	//logout();
	
	
	/*---------------------------------------------------------------------*/
	//PRIVATE FUNCTIONS:
	/*---------------------------------------------------------------------*/
	/*----------------------------------------------------------------------------------------------------------------*/
	//Funkcja sprawdza parametr , jesli jest null-em zwraca pusta tablice
	function check_result_if_not_null($result)
	{
		if(!is_null($result))
			return $result;
		else
		{
			$result = array();
			return $result; 	
		}	
	}

	/*----------------------------------------------------------------------------------------------------------------*/
	function send_email($ticket_id,$ticket_status,$ticket_kategoria,$do,$user_type)
	{
		//$do 			- tablica maili do których zostanie wyslana wiadomosc 
		//$user_type	- nazwa okreslajaca nadawce [user | afiliant | admin]
	
		require_once 'files/swift-4.0.5/lib/swift_required.php';
		require_once('files/lib/SMTP.config.php');
		
		$ticketModel = new TicketModel();
		
		//filtr .. jesli admin wyslij na alias 
		if($user_type == 'admin')
		{
			$email_alias 	= $ticketModel->get_email_alias($ticket_kategoria);
			if($email_alias)
				$do        		= $email_alias['alias_email'];
			else
				return FALSE;
					 
		}
		
		 $transport = Swift_SmtpTransport::newInstance(SMTP_SERVER,SMTP_PORT)
		  ->setUsername(SMTP_USER)
		  ->setPassword(SMTP_PASSWORD);
		
		$mailer = Swift_Mailer::newInstance($transport);
		
		
		$user_controller = null;
		switch($user_type)
		{
			case 'user'  		: $user_controller = 'admin'; 		break;
			case 'afiliant'		: $user_controller = 'afiliant'; 	break;
			case 'admin'		: $user_controller = 'superadmin';	break;		
		}
		
			//kodowanie parametrow
			$user_controller_encoded = $ticketModel->encode($user_controller);
			$ticket_id_encoded 		 = $ticketModel->encode($ticket_id);
		
		
		//Create a message
		$body =  'Wiadomość w systemie networds została '.substr($ticket_status,0,strlen($ticket_status)-1).'a.'.'<br/>'; 
		//$body .= 'Nadawca: '.'<br/>';
		
		if($user_controller != null)
			$body .= 'Wiadomość jest dostępna pod adresem: <br/><a href="'.BASE_URL.'tickets/show/'.$ticket_id_encoded.'/'.$user_controller_encoded.'">'.BASE_URL.'tickets/show/'.$ticket_id_encoded.'/'.$user_controller_encoded.'</a><br/><br/>';
			 
		$body .= 'Email został automatycznie wygenerowany przez system Networds.';
		
	
		$message = Swift_Message::newInstance('Wiadomość Networds: '.$ticket_id)
		  ->setFrom(array(SMTP_USER => 'Networds System'))
		  ->setTo($do)
		  ->setBody($body, 'text/html', 'utf-8');
		  ;
		
		$headers = $message->getHeaders();
		$headers->addTextHeader('Reply-To',SMTP_USER);
		     
		//Send the message
		$result = $mailer->send($message);
		return $result; 		
	}	
?>