<?php
  class Tickets extends Controller
  {
  	private  $user_login;
	private  $user_account; 
	private  $user_data_index;
	private  $user_data; 
	
  	function Tickets()
	{
		parent::Controller();	
		$this->load->library('session');	
		$this->load->helper(array('form', 'url','html'));
		$this->load->model('baza','',TRUE);
		$this->load->model('ticket','',TRUE);	
		
		/*
		if(!(isset($this->session->userdata['user_zalogowany']) or isset($this->session->userdata['user_sa_zalogowany'])) and !(isset($this->session->userdata['di']) or isset($this->session->userdata['di_sa'])))
		{
			redirect('/admin/','location');		
		}*/
		
	
		//klient
		if(isset($this->session->userdata['di']))
		{
			$this->user_data 		= $this->baza->get_user_login($this->session->userdata['user_zalogowany'], $this->session->userdata['di']);
			$this->user_account 	= $this->baza->get_user_account($this->session->userdata['di']);
			$this->user_data_index	= 'di';
		}
		//admin - pracownik
		if(isset($this->session->userdata['di_sa']))
		{
			$this->user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$this->user_account 	= $this->baza->get_super_admin_account($this->session->userdata['di_sa']);
			$this->user_data_index	= 'di_sa';				
		}		
		
		//afiliant
		if(isset($this->session->userdata['id']))
		{
			$this->user_data 			= $this->baza->get_affiliant_name($this->session->userdata['id']);
			$this->user_account 		= $this->baza->get_afiliant_account($this->session->userdata['id']);
			$this->user_data_index		= 'id';
		}
		
		
		
				
		//if($this->user_data_index == null)
		//{
			
			
			$user_controller = $this->uri->segment(4);
			$ticket_id 		 = $this->uri->segment(3);
			if($this->uri->segment(2) == 'show' && !empty($user_controller) && !empty($ticket_id))
			{
				//dekodowanie
				$user_controller = $this->ticket->decode($this->uri->segment(4));
				$ticket_id 		 = $this->ticket->decode($this->uri->segment(3));
				
				if($this->user_data_index == null)
				{
					switch($user_controller)
					{
						case 'admin'		: redirect('/admin/index/'.$ticket_id,'location'); 			break;
						case 'superadmin'	: redirect('/superadmin/index/'.$ticket_id,'location'); 	break;
						case 'afiliant' 	: redirect('/afiliant/index/'.$ticket_id,'location');		break;
						
						default: redirect('','location');
					}
				}
				//else
					//redirect('/tickets/show/'.$ticket_id,'location');
				
			}

			if($this->user_data_index == null)
				redirect('','location');
		//}
	}

	//------------------------------------------------------------------------------------------------
	function index()
	{
		redirect('/tickets/list_items/', 'location');
	}
	//------------------------------------------------------------------------------------------------
	function getUserType()
	{
		//[klient  | admin | afiliant]
		if(isset($this->session->userdata['id']))
		{
			return 'afiliant';
		}
		if(isset($this->session->userdata['di_sa']))
		{
			return 'admin';
		}	
		if(isset($this->session->userdata['di']))
		{
			return 'klient';
		}			
	}
	//------------------------------------------------------------------------------------------------
	function add($parent_id=0)
	{
		
		$data['user']  			= $this->user_data[0]['name'];
		$data['user_account'] 	= $this->user_account;
		$data['user_type'] 		= $this->getUserType(); 
		
		if(isset($this->session->userdata['di_sa']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['di_sa']);
			$data['odbiorcy'] 		= $this->ticket->get_client_list();
		}
		else if(isset($this->session->userdata['di']))	
		{
			$data['user_data'] 		= $this->baza->get_user_data($this->session->userdata['di']);
			$data['odbiorcy']		= $this->ticket->get_employee_list();
		}
		else if(isset($this->session->userdata['id']))
		{
			$data['user_data'] 		= $this->baza->get_affiliant_data($this->session->userdata['id']);
			$data['odbiorcy']		= $this->ticket->get_employee_list();			
		}
		
		$data['statusy']		= $this->ticket->get_status_list();
		$data['kategorie']		= $this->ticket->get_category_list();
		$data['priorytety']		= $this->ticket->get_priority_list();
		
		//jesli odpowiedz
		if($parent_id != 0)
		{
			$data['parent_ticket']		= $this->ticket->get($parent_id);
			$data['parent_zalaczniki']  = $this->ticket->get_attachment_list($parent_id);
			
		}

		$errros 		= null;
		$form_data		= null;
		
		if(isset($_POST['add_ticket']))
		{
			$nadawca  				= (int)$_POST['user_id']; 
			$form_data['odbiorca'] 	= (int)$_POST['odbiorca']; 
			$form_data['kategoria']	= (int)$_POST['kategoria'];
			$form_data['status']	= (int)$_POST['status'];
			$form_data['priorytet']	= (int)$_POST['priorytet'];
			$form_data['temat'] 	= trim($_POST['temat']);
			$form_data['wiadomosc']	= trim($_POST['wiadomosc']);
			@$files					= $_POST['files'];
			
			//walidacja
			if(strlen($form_data['temat']) == 0)	
				$errros['temat'] 	= 'Pusta wartość pola tytuł';
			if(strlen($form_data['wiadomosc']) == 0)	 
				$errros['wiadomosc'] 	= 'Pusta wartość pola wiadomość';
				
			if($errros == null)
			{
				$ticket_id = 0;
				if(($ticket_id = $this->ticket->add($nadawca,
									$form_data['odbiorca'],
									$form_data['kategoria'],
				                    $form_data['status'],
									$form_data['priorytet'],
									$form_data['temat'] ,
									$form_data['wiadomosc'],
									$files,$parent_id)))
				{					
					$data['form_success'] = true;
					//function send_email($ticket_id,$ticket_status,$ticket_kategoria,$do,$user_type)
					
					//nadawca
					  $status_name 	= $this->ticket->get_status_name_by_id($form_data['status']);
					  $nadawca_email	= $this->ticket->get_user_email_by_account_id($nadawca);
					  $nadawca_type   = $this->ticket->get_user_type_by_account_id($nadawca);
					  $this->send_email($ticket_id,$status_name,$form_data['kategoria'],$nadawca_email,$nadawca_type); //do nadawcy
					
					//odbiorca					
					$odbiorca_email	= $this->ticket->get_user_email_by_account_id($form_data['odbiorca']);
					$odbiorca_type   = $this->ticket->get_user_type_by_account_id($form_data['odbiorca']);
					$this->send_email($ticket_id,$status_name,$form_data['kategoria'],$odbiorca_email,$odbiorca_type);
				}
				else
					$data['form_success'] = false;
			}
						
		}
		if($errros != null)
		{
			$data['errros'] 	  = $errros;
			$data['form_data']	  = $form_data;	
			$data['form_success'] = false;					
		}
			
		if($this->getUserType() == 'admin')	
			$data['mainContent']	= $this->load->view('tickets/superadmin_add',$data,true);
		else
			$data['mainContent']	= $this->load->view('tickets/add',$data,true);	
					
		$this->load->view('/layout/tickets',$data);
			
	}
	//------------------------------------------------------------------------------------------------
	function response($parent_id)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['user_account'] 	= $this->user_account;
		$data['user_type'] 		= $this->getUserType();
		
		if(isset($this->session->userdata['di_sa']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['di_sa']);
			$data['odbiorcy'] 		= $this->ticket->get_client_list();
		}
		else if(isset($this->session->userdata['di']))	
		{
			$data['user_data'] 		= $this->baza->get_user_data($this->session->userdata['di']);
			$data['odbiorcy']		= $this->ticket->get_employee_list();
		}
		else if(isset($this->session->userdata['id']))
		{
			$data['user_data'] 		= $this->baza->get_affiliant_data($this->session->userdata['id']);
			$data['odbiorcy']		= $this->ticket->get_employee_list();			
		}
		
		$data['statusy']		= $this->ticket->get_status_list();
		$data['kategorie']		= $this->ticket->get_category_list();
		$data['priorytety']		= $this->ticket->get_priority_list();
		
		$data['parent_ticket']				= $this->ticket->get($parent_id);
		$data['parent_ticket_zalaczniki']   = $this->ticket->get_attachment_list($parent_id);
		
		$data['child_tickets'] 		= $this->ticket->get_child_tickets_by($parent_id);
		
		foreach($data['child_tickets'] as $key=>$value)
			{
				$data['child_tickets_zalaczniki'][$value->id] = $this->ticket->get_child_tickets_by($value->id);				
			}
			
		//$data['response_tickets']	= $this->ticket->get_list_by_parent_id($parent_id);

		$errros 				= null;
		$form_data				= null;
		$data['can_response'] 	= true;		//user ma mozliwosc odpowiedzenia
					
		if(isset($_POST['add_ticket']))
		{

			
			$nadawca  				= (int)$_POST['user_id']; 
			$form_data['odbiorca'] 	= (int)$_POST['odbiorca']; 
			$form_data['kategoria']	= (int)$_POST['kategoria'];
			$form_data['status']	= (int)$_POST['status'];
			$form_data['priorytet']	= (int)$_POST['priorytet'];
			$form_data['temat'] 	= trim($_POST['temat']);
			$form_data['wiadomosc']	= trim($_POST['wiadomosc']);
			@$files			= $_POST['files'];
			
			//walidacja
			if(strlen($form_data['temat']) == 0)	
				$errros['temat'] 	= 'Pusta wartość pola tytuł';
			if(strlen($form_data['wiadomosc']) == 0)	 
				$errros['wiadomosc'] 	= 'Pusta wartość pola wiadomość';
				
			if($errros == null)
			{
				if($this->ticket->add($nadawca,
									$form_data['odbiorca'],
									$form_data['kategoria'],
				                    $form_data['status'],
									$form_data['priorytet'],
									$form_data['temat'] ,
									$form_data['wiadomosc'],
									$files,$parent_id))
				{					
					$data['form_success'] = true;
					
					//usuniecie sesji ticket ownera
					$this->ticket->delete_ticket_owner_session($parent_id);
					
					//wysylanie wiadomosci email
					//nadawca
					 $status_name 	= $this->ticket->get_status_name_by_id($form_data['status']);
					 $nadawca_email	= $this->ticket->get_user_email_by_account_id($nadawca);
					 $nadawca_type   = $this->ticket->get_user_type_by_account_id($nadawca);
					 $this->send_email($parent_id,$status_name,$form_data['kategoria'],$nadawca_email,$nadawca_type); //do nadawcy
					
					//odbiorca					
					$odbiorca_email	= $this->ticket->get_user_email_by_account_id($form_data['odbiorca']);
					$odbiorca_type   = $this->ticket->get_user_type_by_account_id($form_data['odbiorca']);
					$this->send_email($parent_id,$status_name,$form_data['kategoria'],$odbiorca_email,$odbiorca_type);					
				}
				else
					$data['form_success'] = false;
			}
		}
		else
		{
			//ustawienie ownera - gdy admin
			if($data['user_type'] == 'admin')
			{
				$owner_id = $this->ticket->get_ticket_owner($parent_id);
				if(empty($owner_id))
				{
					$this->ticket->set_owner($data['user_account']['id'],$parent_id);
					$data['can_response'] = true;
				}
				else
				{
					if($data['user_account']['id'] == $owner_id)
					{
						$data['can_response'] = true;
						//update session
						$this->ticket->update_ticket_owner($parent_id);
					}
					else
					{
						$data['can_response'] = false;						
					}
				}
			}
		}
		
		if($errros != null)
		{
			$data['errros'] 	  = $errros;
			$data['form_data']	  = $form_data;	
			$data['form_success'] = false;					
		}
			
		$data['mainContent']	= $this->load->view('tickets/response',$data,true);		
		$this->load->view('/layout/tickets',$data);		
		
	}
	//------------------------------------------------------------------------------------------------
	function list_items($type=0,$pageId=0,$condition=null)
	{
		// type : [0 - odebrane | 1 - wyslane ]		
		$type 	= (int)$type;
		$pageId = (int)$pageId;
		$tickestPerPage	 = 4;
		
		$this->load->library('pagination');
		
		$data['user']  			= $this->user_data[0]['name'];
		$data['user_account'] 	= $this->user_account;
		$data['user_type'] 		= $this->getUserType();
	
			$config['base_url']    = base_url().'/tickets/list_items/'.$type.'/';
			
			if ($type == 0)
				$config['total_rows']  = $this->ticket->get_amount_of_received_tickets($this->user_account['id'],$condition);
			else
				$config['total_rows']  = $this->ticket->get_amount_of_sended_tickets($this->user_account['id'],$condition);
					
			$config['per_page']    = $tickestPerPage; 
			$config['uri_segment'] = 4; 
			
		$this->pagination->initialize($config);
		
		
		if($type == 0)
			$data['list_type'] = 'odebrane';
		else
			 $data['list_type'] = 'wyslane';
			 
			 
		if($type == 0)
			$data['tickets']    = $this->ticket->get_received_ticket_list($this->user_account['id'],$pageId,$tickestPerPage,$condition);
		else
			$data['tickets']	= $this->ticket->get_sended_ticket_list($this->user_account['id'],$pageId,$tickestPerPage,$condition);
			

			
		$data['paginacja'] 		= $this->pagination->create_links();
		$data['mainContent']	= $this->load->view('tickets/list',$data,true);		
		$this->load->view('/layout/tickets',$data);
		
	}
	//------------------------------------------------------------------------------------------------
	function show($ticketId,$user_controller=null)
	{
		if($user_controller == null)
			$ticketId  = (int)$ticketId;
		else
			$ticketId  = (int)$this->ticket->decode($ticketId);	
		
		$data['user']  			= $this->user_data[0]['name'];
		$data['user_account'] 	= $this->user_account;
		$data['user_type'] 		= $this->getUserType();
		
		//jesli pracownik lub dowolny user z mozliwościa ogladania ticketa
		if($data['user_type'] == 'admin' || $this->ticket->does_user_have_permision_to_ticket($ticketId,$data['user_account']['id']))
		{
			$data['ticket']			= $this->ticket->get($ticketId);
			
			if($data['ticket']->data_odebrania == '')
				$this->ticket->set_data_odebrania($ticketId);
			
			$this->ticket->clear_ticket_owners_session();	//czyszczenie starych sesji odpowiedzi do ticketów
			$data['owner_id']		= $this->ticket->get_ticket_owner($ticketId);	
							
			if($data['ticket']->parent_id != '')
				{
					$data['ticket']	= $this->ticket->get($data['ticket']->parent_id);					
					$ticketId       = $data['ticket']->id;
				}
	
			$data['child_tickets'] = $this->ticket->get_child_tickets_by($ticketId);
			$data['zalaczniki']    = $this->ticket->get_attachment_list($ticketId);
		}
		else
			$data['message'] = 'Niestety nie masz uprawnień aby zobaczyć tą wiadomość.';
		
		$data['mainContent']	= $this->load->view('tickets/show',$data,true);		
		$this->load->view('/layout/tickets',$data);		
	}
	//------------------------------------------------------------------------------------------------
	function get_users_list()
	{
		//grupy
		// 0 - afiliant | 1 - klient | 2 - admin
		$group_id = $_POST['group_id'];
		$data = null;
		
		switch($group_id)
		{
			case 0:
					$data['users'] 			= $this->ticket->get_afiliant_list();
					$data['user_type']		= 'afiliant';
					break;	
			case 1:
					$data['users'] 			= $this->ticket->get_client_list();
					$data['user_type']		= 'klient';
					break;
			case 2:
					$data['users'] 			= $this->ticket->get_employee_list();
					$data['user_type']		= 'admin';
					break;
			default:exit;
		}

		$this->load->view('/tickets/users_list',$data);			
	}
	//------------------------------------------------------------------------------------------------
	function get_minutes_to_end_session($ticket_id)
	{
		//zwraca ilosc minut do konca sesji odpowiedzi na ticket
		echo $this->ticket->get_minutes_to_end_session($ticket_id);		
	}
	//------------------------------------------------------------------------------------------------
	function reset_session($ticket_id)
	{
		echo $this->ticket->update_ticket_owner($ticket_id);
	}
	//------------------------------------------------------------------------------------------------
	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';
		
		$this->config->load('global_settings');	
		$global_settings 		=  $this->config->item('global_settings');
				
		//filtr .. jesli admin wyslij na alias 
		if($user_type == 'admin')
			$do = $global_settings['alias_emails'][$ticket_kategoria];
		


		
		
		 $transport = Swift_SmtpTransport::newInstance($global_settings['smtp']['smtp_serwer'],587)
		  ->setUsername($global_settings['smtp']['smtp_user'])
		  ->setPassword($global_settings['smtp']['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 = $this->ticket->encode($user_controller);
			$ticket_id_encoded 		 = $this->ticket->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($global_settings['smtp']['smtp_user'] => 'Networds System'))
		  ->setTo($do)
		  ->setBody($body, 'text/html', 'utf-8');
		  ;
		
		$headers = $message->getHeaders();
		$headers->addTextHeader('Reply-To',$global_settings['smtp']['smtp_user']);
		     
		//Send the message
		$result = $mailer->send($message);
		return $result; 		
	}
  }
?>