<?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);	
		
		//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
		else 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';				
		}		
		//master - pracownik
		else if(isset($this->session->userdata['master_id']))
		{
			$this->user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_master_zalogowany'], $this->session->userdata['master_id']);
			$this->user_account 	= $this->baza->get_super_admin_account($this->session->userdata['master_id']);
			$this->user_data_index	= 'master_id';			
		}
		//pracownik - ksiegowa
		else if(isset($this->session->userdata['ksiegowosc_id']))
		{
			$this->user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_ksiegowosc_zalogowany'], $this->session->userdata['ksiegowosc_id']);
			$this->user_account 	= $this->baza->get_super_admin_account($this->session->userdata['ksiegowosc_id']);
			$this->user_data_index	= 'ksiegowosc_id';			
		}
		//afiliant
		else 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';
		}
		else
            redirect('/','location');
		//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;
						case 'ksiegowosc' 	: redirect('/ksiegowosc/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';
		}
		elseif(isset($this->session->userdata['di_sa']))
		{
			return 'admin';
		}
		elseif(isset($this->session->userdata['ksiegowosc_id']))
		{
			return 'ksiegowa';
		}			
		elseif(isset($this->session->userdata['di']))
		{
			return 'klient';
		}
		elseif(isset($this->session->userdata['master_id']))
		{
			return 'master';
		}					
	}
	//------------------------------------------------------------------------------------------------
	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['ksiegowosc_id']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['ksiegowosc_id']);
			$data['odbiorcy'] 		= $this->ticket->get_client_list();
		}	
		elseif(isset($this->session->userdata['master_id']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['master_id']);
			$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']);
            $user                   = $this->baza->get_user($data['user_data'][0]['id']);
			$data['odbiorcy']		= $this->ticket->get_manager($user['manager_id']);
		}
		else if(isset($this->session->userdata['id']))
		{
             
			$data['user_data'] 		= $this->baza->get_affiliant_data($this->session->userdata['id']);
            $employee_type          = 2;
			$data['odbiorcy']		= $this->ticket->get_employee_list($employee_type);
            //losowy odbiorca

            if(is_array($data['odbiorcy']))
            {
                shuffle($data['odbiorcy']);
                $tmp                  =  $data['odbiorcy'][0];
                $data['odbiorcy']     = null;
                $data['odbiorcy'][]   = $tmp;
            }
		}
		 
		$data['statusy']		= $this->ticket->get_status_list();
		$data['kategorie']		= $this->ticket->get_category_list();
		$data['priorytety']		= $this->ticket->get_priority_list();
		$data['grupy']			= array("afilianci","klienci","pracownicy");
		
		//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'] 	= empty($_POST['odbiorca']) ? null:((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(empty($form_data['odbiorca']))
                $errros['odbiorca'] 		= 'Nieprawidłowy odbiorca';

			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(isset($_POST['group_list']))
			{
				if($_POST['group_list'] < 0 || $_POST['group_list'] >= $data['grupy'])
					$errros['grupy'] 	= 'Nieprawidłowa wartość';
			}				
				
			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;
					
					//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);

					
					//odbiorca
					//$odbiorca_type: user | afiliant | admin
					
					
					$odbiorca_email  = '';
					$odbiorca_type   = '';
					if(isset($_POST['grupa']))
					{
						$odbiorca_type = $data['grupy'][$_POST['grupa']];
					}
					
					//tylko pracownik moze wyslac do kazdego usera w grupie ticketa i wtedy $form_data['odbiorca'] == -1  
					if($odbiorca_type == 'pracownicy' && $form_data['odbiorca'] == -1)	
					{
						$employees = $this->ticket->get_employee_list();
						foreach($employees as $k => $v)
						{
							if($data['user_data'][0]['email'] != $v->email)
								$odbiorca_email[] = $v->email;
						}
					}			
					else
					{		
						$odbiorca_type   = $this->ticket->get_user_type_by_account_id($form_data['odbiorca']);
						$odbiorca_email	= $this->ticket->get_user_email_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' || $this->getUserType() == 'ksiegowa' || $this->getUserType() == 'master')
        {
			$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['ksiegowosc_id']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['ksiegowosc_id']);
			$data['odbiorcy'] 		= $this->ticket->get_client_list();
		}	
		elseif(isset($this->session->userdata['master_id']))
		{
			$data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['master_id']);
			$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($parent_id);
				
		if(is_array($data['child_tickets']))
		{
			foreach($data['child_tickets'] as $key=>$value)
				{
					$data['child_tickets_zalaczniki'][$value->id] = $this->ticket->get_child_tickets($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['odbiorca'] 	= empty($_POST['odbiorca']) ? null:((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(empty($form_data['odbiorca']))
                $errros['odbiorca'] 		= 'Nieprawidłowy odbiorca';
			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);
					
					//redirect('/tickets/show/'.$parent_id,'location');					
					redirect('/tickets/list_items','location');					
				}
				else
					$data['form_success'] = false;
			}
		}
		else
		{
			//ustawienie ownera - gdy admin
			if($data['user_type'] == 'admin' || $data['user_type'] == 'ksiegowa' || $data['user_type'] == 'master')
			{
				$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 forward($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['ticket']->zalaczniki    = $this->ticket->get_attachment_list($ticketId);
			
			$data['child_tickets'] = $this->ticket->get_child_tickets($ticketId);
			if(!empty($data['child_tickets']))
			foreach($data['child_tickets'] as $k=>$v)
				$data['child_tickets'][$k]->zalaczniki	=	$this->ticket->get_attachment_list($v->id);
			
		}
		else
			$data['message'] = 'Niestety nie masz uprawnień aby zobaczyć tą wiadomość.';
			

            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['ksiegowosc_id']))
            {
                $data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['ksiegowosc_id']);
                $data['odbiorcy'] 		= $this->ticket->get_client_list();
            }
            elseif(isset($this->session->userdata['master_id']))
            {
                $data['user_data'] 		= $this->baza->get_superadmin_data($this->session->userdata['master_id']);
                $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['grupy']			= array("afilianci","klienci","pracownicy");

        $errors = null;
        $values = null;

		if(isset($_POST['forward_ticket']))
		{
			$nadawca  				= (int)$_POST['user_id'];
			$values['odbiorca'] 	= (int)$_POST['odbiorca'];
			$values['kategoria']	= (int)$_POST['kategoria'];
			$values['status']       = (int)$_POST['status'];
			$values['priorytet']	= (int)$_POST['priorytet'];
			$values['temat']        = trim($_POST['temat']);
			$values['wiadomosc']	= trim($_POST['wiadomosc']);
			@$files					= $_POST['files'];


			
			//walidacja
			if(strlen($values['temat']) == 0)
				$errros['temat'] 		= 'Pusta wartość pola tytuł';
			if(strlen($values['wiadomosc']) == 0)
				$errros['wiadomosc'] 	= 'Pusta wartość pola wiadomość';

			if(isset($_POST['group_list']))
			{
				if($_POST['group_list'] < 0 || $_POST['group_list'] >= $data['grupy'])
					$errros['grupy'] 	= 'Nieprawidłowa wartość';
			}
			
			if(!empty($data['ticket']->zalaczniki))
				foreach($data['ticket']->zalaczniki as $k=>$v)
					$files[] = $v->sciezka;
			
			if(!empty($data['child_tickets']))
				foreach($data['child_tickets'] as $k=>$v)
					{
                        if(!empty($v->zalaczniki))
                        {
                            foreach($v->zalaczniki as $kk=>$vv)
                                $files[] = $vv->sciezka;
                        }
					}
			
			if($errors == null)
			{
				$ticket_id = 0;
				if(($ticket_id = $this->ticket->add($nadawca,
									$values['odbiorca'],
									$values['kategoria'],
				                    $values['status'],
									$values['priorytet'],
									$values['temat'] ,
									$values['wiadomosc'],
									$files)))
				{
					$data['form_success'] = true;

					//nadawca
				    $status_name 	= $this->ticket->get_status_name_by_id($values['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,$values['kategoria'],$nadawca_email,$nadawca_type);


					//odbiorca
					//$odbiorca_type: user | afiliant | admin


					$odbiorca_email  = '';
					$odbiorca_type   = '';
					if(isset($_POST['grupa']))
					{
						$odbiorca_type = $data['grupy'][$_POST['grupa']];
					}

					//tylko pracownik moze wyslac do kazdego usera w grupie ticketa i wtedy $values['odbiorca'] == -1
					if($odbiorca_type == 'pracownicy' && $values['odbiorca'] == -1)
					{
						$employees = $this->ticket->get_employee_list();
						foreach($employees as $k => $v)
						{
							if($data['user_data'][0]['email'] != $v->email)
								$odbiorca_email[] = $v->email;
						}
					}
					else
					{
						$odbiorca_type   = $this->ticket->get_user_type_by_account_id($values['odbiorca']);
						$odbiorca_email	= $this->ticket->get_user_email_by_account_id($values['odbiorca']);
					}

					$this->send_email($ticket_id,$status_name,$values['kategoria'],$odbiorca_email,$odbiorca_type);
				}
				else
					$data['form_success'] = false;
			}

		}
		else
        {
            $values['temat']      = "Fwd: ".$data['ticket']->temat;
            $values['wiadomosc']  = "Data: ".$data['ticket']->data_wyslania."\r\n";
            $values['wiadomosc'] .= "Od: ".$data['ticket']->nadawca."\r\n";
            $values['wiadomosc'] .= "Do: ".$data['ticket']->odbiorca."\r\n";
            $values['wiadomosc'] .= "Temat: ".$data['ticket']->temat."\r\n";
            $values['wiadomosc'] .= $data['ticket']->wiadomosc;

			if(!empty($data['child_tickets']))
			foreach($data['child_tickets'] as $k=>$v)
                {
                    $values['wiadomosc'] .="\r\n\r\n\r\n";
                    $values['wiadomosc'] .= "Data: ".$v->data_wyslania."\r\n";
                    $values['wiadomosc'] .= "Od: ".$v->nadawca."\r\n";
                    $values['wiadomosc'] .= "Do: ".$v->odbiorca."\r\n";
                    $values['wiadomosc'] .= "Temat: ".$v->temat."\r\n";
                    $values['wiadomosc'] .= $v->wiadomosc;
                }
        }
					
		$data['errors']         = $errors;
        $data['values']         = $values;

		$data['mainContent']	= $this->load->view('tickets/forward',$data,true);		
		$this->load->view('/layout/tickets',$data);					
	}
	//------------------------------------------------------------------------------------------------
	function list_items($type=0,$pageId=0,$condition=null)
	{
		// type : [0 - odebrane | 1 - wyslane ]
		$list_types  = array("odebrane","wysłane");		
		$type 	= (int)$type;
		$pageId = (int)$pageId;
		

		$this->config->load('global_settings');
		$global_settings 		=  $this->config->item('global_settings');
		$this->load->library('pagination');
		$tickestPerPage	 = $global_settings['tickets']['tickets_list_items_per_page'];

		$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);
		
		$data['list_types']		   = $list_types;
		$data['list_type']	   	   = $list_types[$type];

			 
		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);
			
		//określenie odebrania ticketa
		if(!empty($data['tickets']))
		{
			foreach($data['tickets'] as $k=>$v)
				$v->was_ticket_thread_read = $this->ticket->was_ticket_thread_read($v->id,$this->user_account['id']);
		}
		
		$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();
        $data['can_reply']      = true;		//user ma mozliwosc odpowiedzenia
        $data['ticket_status']  = null;


    	//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(empty($data['ticket']->data_odebrania) && ($data['ticket']->odbiorca_id == $data['user_account']['id']))
				$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['ticket_status']      = $data['ticket']->status_id;
				}
			
			$data['ticket']->zalaczniki    = $this->ticket->get_attachment_list($ticketId);
			if($data['ticket']->status_id == 2)
                    $data['can_reply'] = false;
			
			$data['child_tickets'] = $this->ticket->get_child_tickets($ticketId);
			if(!empty($data['child_tickets']))
			{
				foreach($data['child_tickets'] as $k=>$v)
					if($v->odbiorca_id == $data['user_account']['id'])
						$this->ticket->set_data_odebrania($v->id);
			}

            //EDYCJA STATUSU
            if(!empty($_POST['status']))
            {
                $this->config->load('alerts');
                $alerts             =  $this->config->item('alerts');
                $status             =   (int)$_POST['status'];

                $edited_ticket_id          = null;
                if(!empty($data['child_tickets']))
                    $edited_ticket_id = $data['child_tickets'][count($data['child_tickets'])-1]->id;
                else
                    $edited_ticket_id =  $data['ticket']->id;

                if($this->ticket->edit_status($edited_ticket_id,$status))
                {
                        $data['message']        =	$alerts['operation_success'];
                        $data['child_tickets']  = $this->ticket->get_child_tickets($ticketId);
                        $data['ticket_status']  = $status;
                }
                    else
                        $data['message']	=	$alerts['operation_fail'];
            }

			if(!empty($data['child_tickets']))
            {
                foreach($data['child_tickets'] as $k=>$v)
                {
                    $data['child_tickets'][$k]->zalaczniki	=	$this->ticket->get_attachment_list($v->id);
                }

                $data['ticket_status']      =     $data['child_tickets'][count($data['child_tickets'])-1]->status_id;
                

                if($data['child_tickets'][count($data['child_tickets'])-1]->status_id == 2)
                        $data['can_reply'] = false;
            }
			
    	}
		else
			$data['message'] = 'Niestety nie masz uprawnień aby zobaczyć tą wiadomość.';

        $data['statusy']		= $this->ticket->get_status_list();
		$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);
	}
	//------------------------------------------------------------------------------------------------
	//[AjaxMethod]
	function ticket($ticketId)
	{
		$this->load->model('ticket','',TRUE);
		
		$data['ticket']			= $this->ticket->get($ticketId);		
		if($data['ticket']->parent_id != '')
			{
				$data['ticket']	= $this->ticket->get($data['ticket']->parent_id);					
				$ticketId       = $data['ticket']->id;
			}
		$data['zalaczniki']    = $this->ticket->get_attachment_list($ticketId);			
		$data['child_tickets'] = $this->ticket->get_child_tickets($ticketId);
		
		$this->load->view('/master/client_ticket',$data);				
	}
	//------------------------------------------------------------------------------------------------------------------	
	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 ticket leci do admina to wyslij na alias 
		//         jesli odbiorca sa wszyscy admini to nie wysyłaj na alias
		
		//jak do == -1 to odbiorca sa wszyscy uzytkownicy z wybranej grupy
		
		if($user_type == 'admin' && $do != -1)
		{
			$kategoria				=  $this->baza->get_email_alias($ticket_kategoria); 
			$alias_email			= $kategoria['alias_email'];
			$do 					= $alias_email;
		}
		
		
		 $transport = Swift_SmtpTransport::newInstance($global_settings['smtp']['smtp_serwer'],$global_settings['smtp']['smtp_port'])
		  ->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 [no reply]'))
		  ->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; 		
	}
	//------------------------------------------------------------------------------------------------------------------		
  }
?>