<?php
class Master extends Controller {
	private $user_data;
	private $login	= false;
	private $global_settings;
	
	function Master()
	{
		parent::Controller();
		$this->load->library('session');
		$this->load->library('walidacja');
			
		//$this->load->helper(array('form', 'url','html'));
		$this->load->helper(array('form', 'url','html'));
		$this->load->model('baza','',TRUE);
		
		$this->config->load('global_settings');	
		$this->global_settings 		=  $this->config->item('global_settings');
		
		$this->checkLogin();
	}
	//------------------------------------------------------------------------------------------------------------------
	/* sprawdza uzytkownika czy jest zalogowany */	
	function checkLogin()
	{
	
		if(isset($this->session->userdata['user_master_zalogowany']) and isset($this->session->userdata['master_id']))
		{
			$this->login 		= true;
			$this->user_data 	= $this->baza->master_get_user_login($this->session->userdata['user_master_zalogowany'], $this->session->userdata['master_id']);
			if(empty($this->user_data))
				$this->login 	= false;
		}
		
		if($this->uri->segment(2))
		{
			$metoda = $this->uri->segment(2);
			if($metoda != 'login' && !$this->login)
				redirect('/master/login', 'location');						
		}
	}
	//------------------------------------------------------------------------------------------------------------------
	function index()
	{
		redirect('/master/start/','location');
	}
	//------------------------------------------------------------------------------------------------------------------	
	function start()
	{
		$this->load->model('ticket','',TRUE);
		
		$data['user']  			= $this->user_data[0]['name'];
		$data['mainContent']	= $this->load->view('master/start',$data,true);
	
        $data['messages']           =   array();//dashboard items
        $users_withouts_manager_id  = $this->baza->get_users_without_manager_id();

        if(!empty($users_withouts_manager_id))
        {
            $data['messages'][]     = "Uwaga w systemie występują użytkownicy nie przypisani do pracowników !!!";
        }
		
		//liczba niedobranych wiadomości
		$user_account       = $this->baza->get_super_admin_account($this->session->userdata['master_id']);
		$unreaded_tickets_msg   =   $this->ticket->get_info_about_unreaded_tickets($user_account['id']); //niedebrane tickety
		if(!empty($unreaded_tickets_msg))
			$data['messages'][] = $unreaded_tickets_msg;		

        $data['mainContent']	= $this->load->view('master/start',$data,true);			
		$this->load->view('/layout/master',$data);
	}
	//------------------------------------------------------------------------------------------------------------------
	function masters($info_id = null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		//wykluczenie zalogowanego uzytkownika
		$excluded_ids = array($data['master_id']);
		if(!empty($info_id))
		{
			if($info_id == 1)
				$data['message']	= 'Operacja została wykonana pomyślnie !';
			elseif($info_id == 0)
				$data['message']	= 'Wystapił błąd !';
		}
		
		$data['masters']		= $this->baza->get_all_masters($excluded_ids);
		$data['mainContent']	= $this->load->view('master/masters',$data,true);
		$this->load->view('/layout/master',$data);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function employees($info_id = null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		//wykluczenie zalogowanego uzytkownika
		$excluded_ids = array($data['master_id']);
		if(!empty($info_id))
		{
			if($info_id == 1)
				$data['message']	= 'Operacja została wykonana pomyślnie !';
			elseif($info_id == 0)
				$data['message']	= 'Wystapił błąd !';
		}
        $data['employees']          = $this->baza->get_employees_by_type(array(2,3));

		$data['mainContent']	= $this->load->view('master/employees',$data,true);
		$this->load->view('/layout/master',$data);				
	}
	//------------------------------------------------------------------------------------------------------------------
	function employee($id,$tickets_type=0,$tickets_pageId=0,$tickets_condition=null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		//tabs content
		$data['employee_profile']	= $this->employee_profile($id);
		$data['employee_tickets']	= $this->employee_tickets($id,$tickets_type,$tickets_pageId,$tickets_condition);
		
		$data['mainContent']	= $this->load->view('master/employee',$data,true);
		$this->load->view('/layout/master',$data);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function clients($info_id = null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		if(!empty($info_id))
		{
			if($info_id == 1)
				$data['message']	= 'Operacja została wykonana pomyślnie !';
			elseif($info_id == 0)
				$data['message']	= 'Wystapił błąd !';
		}
		$data['clients']	=	$this->baza->get_all_users();
		$data['mainContent']	= $this->load->view('master/clients',$data,true);
		$this->load->view('/layout/master',$data);		
				
	}
	//------------------------------------------------------------------------------------------------------------------
	function domains()
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		if(!empty($_POST))
		{
			$this->config->load('alerts');
			$alerts		=  $this->config->item('alerts');
					
					
			//google region
			if(!empty($_POST['google_region']))			
			{
				if($this->baza->superadmin_set_region($_POST['domain_id'], $_POST['google_region']))
					$data['info']	=	$alerts['operation_success'];
				else
					$data['info']	=	$alerts['operation_fail'];
			}//aktywnosc
			elseif(isset($_POST['active']))	
			{
				if($this->baza->set_domain_activity($_POST['domain_id'], $_POST['active']))
					$data['info']	=	$alerts['operation_success'];
				else
					$data['info']	=	$alerts['operation_fail'];								
			}	
		}
		$data['domains'] = $this->baza->superadmin_get_domains('admin');
		$this->config->load('google_regions');
		$data['regions'] = $this->config->item('google_regions');
		
		$data['mainContent']	= $this->load->view('master/domains',$data,true);
		$this->load->view('/layout/master',$data);
	}
	//------------------------------------------------------------------------------------------------------------------
	function domain_positions($domain_id)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];		
		
		$data['colors']	  		= $this->global_settings['chart_line_colors'];
		$data['keywords'] 		= $this->baza->get_domain($domain_id);
		$data['pozycja'] 		= $this->baza->get_domain_key_position($domain_id);		
		$data['domains']		= $this->baza->superadmin_get_domains('admin');	
		$data['google_region']	= $this->baza->google_region($domain_id);
        
		$data['mainContent']	= $this->load->view('master/domain_positions',$data,true);
		$this->load->view('/layout/master',$data);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function domain_positions_charts($domain_id)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];

		$data['domain_id']		= $domain_id;		
		$data['keywords'] 		= $this->baza->get_keyword_position($domain_id);
		$data['colors']	  		= $this->global_settings['chart_line_colors'];
		$data['domains']		= $this->baza->superadmin_get_domains('admin');
		$data['google_region']	= $this->baza->google_region($domain_id);
		
		$data['mainContent']	= $this->load->view('master/domain_positions_charts',$data,true);
		$this->load->view('/layout/master',$data);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function domain_visits($domain_id,$elem_start = 0)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];

		
		$this->load->model('bazapg','','pg');
		$data['stats'] 	= $this->bazapg->get_stats_pagination($domain_id,$elem_start,50);
		$this->load->library('pagination');
		$number_of_rows = $this->bazapg->count_stats($domain_id);
		if(empty($number_of_rows[0]['ile'])) $number_of_rows[0]['ile']=0;
		
		$config['base_url'] = "/master/domain_visits/$domain_id/";
		$config['url_extention']= '';
		$config['total_rows'] 	= $number_of_rows[0]['ile'];
		$config['per_page'] 	= '50';
		$config['num_links'] 	= '9';
		$config['uri_segment'] 	= 4;
		$config['first_link'] 	= '<<';
		$config['last_link'] 	= '>>';
		
		$this->pagination->initialize($config);
		$data['paginacja'] 	= 	$this->pagination->create_links();					
		$data['domain_id']	=	$domain_id;						
		$data['domains']	= $this->baza->superadmin_get_domains('admin');		
		
		
		$data['mainContent']	= $this->load->view('master/domain_visits',$data,true);
		$this->load->view('/layout/master',$data);							
	}
	//------------------------------------------------------------------------------------------------------------------
	function domain_visits_charts($domain_id, $type = 1, $elem_start = 0)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
				
		$this->load->library('pagination');

			switch($type)
			{
			    case 1: {
			    			// "Dzienne"; 
							$data['name_of_type'] = "Dzienne"; 
							$prefs = array (
   					    					'show_next_prev'  => TRUE,
       										'next_prev_url'   => '/master/domain_visits_charts/'.$domain_id.'/'.$type.'',
					    					'month_type'   => 'long',
					    					'day_type'     => 'short'
     										);
						
						   $prefs['template'] = $this->global_settings['calendar_template'];
						   $this->load->library('calendar', $prefs);
							
							break;
						}
			    case 2: {
			    			// "Tygodniowe"; 
							$data['name_of_type'] = "Tygodniowe";
							//include_once('files/dateclass.php');
							break;
						}
			    case 3: {
			    			// "Miesieczne";
							$data['name_of_type'] = "Miesieczne";
							break;
						}
			    case 4: {
			    			// "Roczne";
							$data['name_of_type'] = "Roczne";
							break;
						}
			}
			$data['domain_id']	= $domain_id;
			$data['domains']	= $this->baza->superadmin_get_domains('admin');	
			$data['type'] 		= $type;		
			
		$data['mainContent']	= $this->load->view('master/domain_visits_charts',$data,true);
		$this->load->view('/layout/master',$data);
	}
	//------------------------------------------------------------------------------------------------------------------			
	function afiliants($info_id = null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		if(!empty($info_id))
		{
			if($info_id == 1)
				$data['message']	= 'Operacja została wykonana pomyślnie !';
			elseif($info_id == 0)
				$data['message']	= 'Wystapił błąd !';
		}
		$data['afiliants']		= $this->baza->get_all_afiliants();
		$data['mainContent']	= $this->load->view('master/afiliants',$data,true);
		$this->load->view('/layout/master',$data);	
	}
	//------------------------------------------------------------------------------------------------------------------
	function afiliant($afiliant_id,$tickets_type=0,$tickets_pageId=0,$tickets_condition=null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		//tabs content
		$data['afiliant_profile']	= $this->afiliant_profile($afiliant_id);
		$data['afiliant_tickets']	= $this->afiliant_tickets($afiliant_id,$tickets_type,$tickets_pageId,$tickets_condition);
						
		$data['afiliants']		= $this->baza->get_all_afiliants();
		$data['mainContent']	= $this->load->view('master/afiliant',$data,true);
		$this->load->view('/layout/master',$data);						
	}
	//------------------------------------------------------------------------------------------------------------------
	function afiliant_profile($afiliant_id)
	{

		$afiliant				=	$this->baza->get_affiliant_data($afiliant_id);
		$afiliant_users			=	$this->baza->get_affiliant_users($afiliant_id);
		$free_users				=	$this->baza->get_free_users_for_aff();
		$clients				=   $this->baza->get_all_users();
		$afiliants				= 	$this->baza->get_all_afiliants();
		$data['afiliant']		=	$afiliant[0];
		$data['users']			=	$this->baza->get_all_users();
	
		
		$this->load->library('walidacja');
		$this->config->load('alerts');
		$alerts					=  $this->config->item('alerts');
		$values					=	null;
		$errors					= 	null;
						
				
		
		if(!empty($_POST))
		{
			$values['id']						=	(int)$_POST['id'];
			$values['nazwa']					=	isset($_POST['nazwa'])	? trim(strip_tags($_POST['nazwa'])) : '';
			$values['typ']						=	trim(strip_tags($_POST['typ']));
			$values['imie']						=	isset($_POST['imie']) 		? trim(strip_tags($_POST['imie'])) 		: '';
			$values['nazwisko']					=	isset($_POST['nazwisko']) 	? trim(strip_tags($_POST['nazwisko']))	: '';
			
			$values['pesel']					=	isset($_POST['pesel']) ? trim(strip_tags($_POST['pesel'])) : '';
			
			$values['nip']						=	trim(strip_tags($_POST['nip']));
			
			$values['regon']					=	isset($_POST['regon']) ? trim(strip_tags($_POST['regon'])) : '';
			
			$values['miasto']					=	trim(strip_tags($_POST['miasto']));
			$values['ulica']					=	trim(strip_tags($_POST['ulica']));
			$values['kod_pocztowy']				=	trim(strip_tags($_POST['kod_pocztowy']));
			$values['numer_domu']				=	trim(strip_tags($_POST['numer_domu']));
			$values['nr_mieszkania']			=	trim(strip_tags($_POST['nr_mieszkania']));
			$values['dk_miasto']				=	trim(strip_tags($_POST['dk_miasto']));
			$values['dk_ulica']					=	trim(strip_tags($_POST['dk_ulica']));
			$values['dk_kod_pocztowy']			=	trim(strip_tags($_POST['dk_kod_pocztowy']));
			$values['dk_nr_domu']				=	trim(strip_tags($_POST['dk_nr_domu']));
			$values['dk_nr_mieszkania']			=	trim(strip_tags($_POST['dk_nr_mieszkania']));
			$values['dk_telefon']				=	trim(strip_tags($_POST['dk_telefon']));
			$values['nr_konta']					=	trim(strip_tags($_POST['nr_konta']));
			$values['telefon']					=	trim(strip_tags($_POST['telefon']));
			$values['email']					=	trim(strip_tags($_POST['email']));
			
			$values['pass']						=	trim(strip_tags($_POST['pass']));
			$values['pass2']					=	trim(strip_tags($_POST['pass2']));
			
			$values['uwagi']					=	trim(strip_tags($_POST['uwagi']));
			$values['active']					=	trim(strip_tags($_POST['active']));
			$values['umowa']					=	trim(strip_tags($_POST['umowa']));
			$values['dokumenty_firma']			=	isset($_POST['dokumenty_firma']) 			? trim(strip_tags($_POST['dokumenty_firma']))		:	'';
			$values['dokumenty_osoba_prywatna']	=	isset($_POST['dokumenty_osoba_prywatna'])   ? trim(strip_tags($_POST['dokumenty_osoba_prywatna'])) :	'';
			
			$values['afiliant_users']			=   isset($_POST['afiliant_users'])   			? $_POST['afiliant_users'] : null;
			$values['danekorespondecyjne']		=	$_POST['danekorespondecyjne'];
			
	
			if($values['danekorespondecyjne'] == 0)
			{
				$values['dk_miasto']			=	null;
				$values['dk_ulica']				=	null;
				$values['dk_kod_pocztowy']		=	null;
				$values['dk_nr_domu']			=	null;
				$values['dk_nr_mieszkania']		=	null;
				$values['dk_telefon']			=	null;
			}

			
			//walidacja
			//id
			if(empty($values['id']))
				$errors['id']					=	$alerts['field_required'];
				
			//typ	
			if(empty($values['typ']))
				$errors['typ']					=	$alerts['field_required'];
				
			//pesel		
			if(strtolower($values['typ']) == 'osoba prywatna')
			{
				//imie	
				if(empty($values['imie']))
					$errors['imie']					=	$alerts['field_required'];
					
				//nazwisko													
				if(empty($values['nazwisko']))
					$errors['nazwisko']				=	$alerts['field_required'];
									
				if(empty($values['pesel']))
					$errors['pesel']				=	$alerts['field_required'];
				elseif(!$this->walidacja->CheckPESEL($values['pesel']))		
					$errors['pesel']				=	$alerts['field_invalid'];
					
										
			}
			//nip
			if(empty($values['nip']))
				$errors['nip']				=	$alerts['field_required'];
			elseif(!$this->walidacja->CheckNIP($values['nip']))
				$errors['nip']				=	$alerts['field_invalid'];
				
			//regon
			if(strtolower($values['typ']) == 'firma')
			{
				//nazwa	
				if(empty($values['nazwa']))
					$errors['nazwa']				=	$alerts['field_required'];
							
				if(empty($values['regon']))
					$errors['regon']				=	$alerts['field_required'];
				elseif(!$this->walidacja->CheckREGON($values['regon']))
					$errors['regon']				=	$alerts['field_invalid'];					
			}
			
			//miasto
			if(empty($values['miasto']))
				$errors['miasto']				=	$alerts['field_required'];
			
			//ulica
			if(empty($values['ulica']))
				$errors['ulica']				=	$alerts['field_required'];
						
			//kod_pocztowy
			if(empty($values['kod_pocztowy']))
				$errors['kod_pocztowy']			=	$alerts['field_required'];
			elseif(!$this->walidacja->CheckKodPocztowy($values['kod_pocztowy']))
				$errors['kod_pocztowy']			=	$alerts['field_invalid'];				
			
			//numer_domu
			if(empty($values['numer_domu']))
				$errors['numer_domu']			=	$alerts['field_required'];
							
			//nr_mieszkania
			//if(empty($values['nr_mieszkania']))
			//	$errors['nr_mieszkania']			=	$alerts['field_required'];
				
						
			//DANE KORESPONDENCYJNE
			if(isset($_POST['danekorespondecyjne']) && ($_POST['danekorespondecyjne'] == 1))
			{				
					//dk_miasto
					if(empty($values['dk_miasto']))
						$errors['dk_miasto']			=	$alerts['field_required'];
									
					//dk_ulica
					if(empty($values['dk_ulica']))
						$errors['dk_ulica']				=	$alerts['field_required'];
									
					//dk_kod_pocztowy
					if(empty($values['dk_kod_pocztowy']))
						$errors['dk_kod_pocztowy']		=	$alerts['field_required'];
					elseif(!$this->walidacja->CheckKodPocztowy($values['dk_kod_pocztowy']))
						$errors['dk_kod_pocztowy']			=	$alerts['field_invalid'];						
									
					//dk_nr_domu
					if(empty($values['dk_nr_domu']))
						$errors['dk_nr_domu']		=	$alerts['field_required'];
									
					//dk_nr_mieszkania
					//if(empty($values['dk_nr_mieszkania']))
					//	$errors['dk_nr_mieszkania']		=	$alerts['field_required'];
									
					//dk_telefon
					if(empty($values['dk_telefon']))
						$errors['dk_telefon']		=	$alerts['field_required'];
			}

				
			//nr_konta
            /*
			if(!empty($values['nr_konta']))
				if(!$this->walidacja->CheckNRB($values['nr_konta']))
					$errors['nr_konta']		=	$alerts['field_invalid'];
			*/
			//telefon
			if(empty($values['telefon']))
				$errors['telefon']		=	$alerts['field_required'];
		
			//email
			if(empty($values['email']))
				$errors['email']		=	$alerts['field_required'];
			elseif(!$this->walidacja->CheckEmail($values['email']))
				$errors['email']		=	$alerts['field_invalid'];
				
			//pass
			//pass2
			if(!empty($values['pass']) || !empty($values['pass2']))
			{
				if($values['pass'] != $values['pass2'])
					$errors['pass2']		=	$alerts['field_invalid'];					
			}
			
			//uwagi
			//active
			//umowa
			//dokumenty_firma
			//dokumenty_osoba_prywatna	
			//klienci
			
					if(is_null($errors))
					{
						$result = $this->baza->edit_afiliant_and_his_clients($values['id'],$values['nazwa'],$values['typ'],$values['imie'],$values['nazwisko'],$values['pesel'],$values['nip'],$values['regon'],
                                                                            $values['miasto'],$values['ulica'],$values['kod_pocztowy'],$values['numer_domu'],$values['nr_mieszkania'],$values['dk_miasto'],$values['dk_ulica'],
                                                                            $values['dk_kod_pocztowy'],$values['dk_nr_domu'],$values['dk_nr_mieszkania'],$values['dk_telefon'],$values['nr_konta'],$values['telefon'],
                                                                            $values['email'],$values['pass'],$values['uwagi'],$values['active'],$values['umowa'],$values['dokumenty_firma'],$values['dokumenty_osoba_prywatna'],
                                                                            $values['afiliant_users']);
				
						if($result)
						{
							$data['info'] 		= $alerts['operation_success'];
							$data['afiliant']	= $afiliant[0];
							$afiliant_users		=	$this->baza->get_affiliant_users($afiliant_id);
						}
						else
							$data['info'] = $alerts['operation_fail'];
							
					}
					else
					{
						$data['info'] = $alerts['operation_fail'];
					}
													
		}
		else
		{
			foreach ($data['afiliant'] as $key => $val)
			{
				$values[$key] = $val;
			}
			
	
			if(!empty($values['dk_miasto']) || !empty($values['dk_ulica']) || !empty($values['dk_kod_pocztowy']) || !empty($values['dk_nr_domu']) || !empty($values['dk_nr_mieszkania']) || !empty($values['dk_telefon']))
				$values['danekorespondecyjne'] = 1;
			else
				$values['danekorespondecyjne'] = 0;
		}

		
		//modyfikacja wyswietlanych nazw klientów
		//jesli klient nalezał pod afilianta ma przypis - [przypisany]
		foreach($data['users'] as $k=>$v)
		{
			foreach($afiliants as $k2=>$v2)
			{
				if($v['afiliant_id'] == $v2['id'])
				{
					$data['users'][$k]['name'] .= ' ['.((!empty($v2['nazwa'])) ? $v2['nazwa'] : $v2['imie'].' '.$v2['nazwisko']).']';
				}
			}
		}



			
		$data['afiliant_users']		= 	array();
		//wyciagniecie id-kow
		foreach($afiliant_users as $elem)
			$data['afiliant_users'][]	=	$elem['id'];
			
			
		$values['afiliant_users'] = $data['afiliant_users'];
		$data['values']	=	$values;
		$data['errors']	=	$errors;					
		
		return $this->load->view('master/afiliant_profile',$data,true);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function afiliant_tickets($afiliant_id,$type=0,$pageId=0,$condition=null)
	{
		$this->load->model('ticket','',TRUE);	
		$this->load->library('pagination');
		
		$list_types  				= array("odebrane","wysłane");
		$data['list_types']			= $list_types;
		$data['list_type']	   		= $list_types[$type];
		$data['link_postfiks']		= '#tabs-2';
				
		$data['afiliant_id']	= $afiliant_id;
		$afiliant_account 		= $this->baza->get_afiliant_account($afiliant_id);
		
		$type 					= (int)$type;
		$pageId 				= (int)$pageId;
		$tickestPerPage			 = 4;
		
		$config['base_url']    = base_url().'/master/afiliant/'.$afiliant_id.'/'.$type.'/';
		
			
		if ($type == 0)
			$config['total_rows']  = $this->ticket->get_amount_of_received_tickets($afiliant_account['id'],$condition);
		else
			$config['total_rows']  = $this->ticket->get_amount_of_sended_tickets($afiliant_account['id'],$condition);
		
		$config['per_page']    		= $tickestPerPage; 
		$config['uri_segment'] 		= 5;
		$config['link_postfiks']	= $data['link_postfiks'];
		
		$this->pagination->initialize($config);
		
		 
		if($type == 0)
			$data['tickets']    = $this->ticket->get_received_ticket_list($afiliant_account['id'],$pageId,$tickestPerPage,$condition);
		else
			$data['tickets']	= $this->ticket->get_sended_ticket_list($afiliant_account['id'],$pageId,$tickestPerPage,$condition);		 			
		
		$data['paginacja'] 		= $this->pagination->create_links();
		return $this->load->view('master/afiliant_tickets',$data,true);			
	}
	//------------------------------------------------------------------------------------------------------------------
	function add_master()
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		$form_data				= null;
		$errors					= null;
		
		if(!empty($_POST))
		{
			$form_data['imie']   = trim($_POST['imie']);
			$form_data['email']  = trim($_POST['email']);
			$form_data['haslo']  = trim($_POST['haslo']);
			$form_data['haslo2'] = trim($_POST['haslo2']);
			
			if(!$this->walidacja->CheckEmail($form_data['email']))
				$errors['email'] = 'Niepoprawny adres email.';
						
			if(empty($form_data['imie']))
				$errors['imie'] = 'Wartośc pola nie może być pusta';

			if(empty($form_data['haslo']))
				$errors['haslo'] = 'Wartośc pola nie może być pusta';
				
			if(empty($form_data['email']))
				$errors['email'] = 'Wartośc pola nie może być pusta';				
								
			if(!$this->baza->is_unique_master_name($_POST['imie']))
				$errors['imie'] = 'Uzytkownik o podanym imieniu już istnieje w bazie.';
				
			if($form_data['haslo'] != $form_data['haslo2'])	
				$errors['haslo2'] = 'Nieprawidłowe potwierdzenie hasła';
				
				if($form_data != null && $errors != null)
				{
					$data['form_data']	    = $form_data;	
					$data['errors']	  		= $errors;
				}
				else
				{
					$this->baza->add_master($form_data['imie'],$form_data['haslo'],$form_data['email']);
					redirect('/master/masters/1','location');					
				}
				
		}
		//wykluczenie zalogowanego uzytkownika
		$excluded_ids = array($data['master_id']);
		
		$data['masters']		= $this->baza->get_all_masters($excluded_ids);
		$data['mainContent']	= $this->load->view('master/add_master_form',$data,true);
		$this->load->view('/layout/master',$data);		
		
	}
	//------------------------------------------------------------------------------------------------------------------
	function add_employee()
	{

		$data['user']  				= $this->user_data[0]['name'];
		$data['master_id']			= $this->session->userdata['master_id'];
		$data['employee_types']		= $this->global_settings['employee_types'];
		
	
		$form_data					= null;
		$errors						= null;
		
		if(!empty($_POST))
		{
			$this->load->library('walidacja');
			$this->config->load('alerts');
			$alerts							=  $this->config->item('alerts');
			
			$form_data['imie']   		= trim($_POST['imie']);
			$form_data['email']  		= trim($_POST['email']);
			$form_data['haslo']  		= trim($_POST['haslo']);
			$form_data['haslo2'] 		= trim($_POST['haslo2']);
			$form_data['utrzymanie'] 	= isset($_POST['utrzymanie']) 	? (int)$_POST['utrzymanie'] : 0;
			$form_data['rabat'] 		= isset($_POST['rabat']) 		? (int)$_POST['rabat'] 		: 0;
			$form_data['active'] 		= (int)$_POST['active'];
			$form_data['type']			= (int)$_POST['type'];
			
			$form_data['customers']		= null;
			if(isset($_POST['customers']) && ($form_data['active']==1))
				$form_data['customers']		= $_POST['customers'];
			
					
			if(empty($form_data['email']))
				$errors['email']  = $alerts['field_required'];			
			if(!$this->walidacja->CheckEmail($form_data['email']))
				$errors['email'] = $alerts['field_invalid'];
						
			if(empty($form_data['imie']))
				$errors['imie'] = $alerts['field_required'];	

			if(empty($form_data['haslo']))
				$errors['haslo'] = $alerts['field_required'];	
				
						
								
			if(!$this->baza->is_unique_employee_name($_POST['imie']))
				$errors['imie'] = 'Uzytkownik o podanym imieniu już istnieje w bazie.';
				
			if($form_data['haslo'] != $form_data['haslo2'])	
				$errors['haslo2'] 	= 'Nieprawidłowe potwierdzenie hasła';
				
			//jesli pracownik - sprawdz pola utrzymanie i rabat
			if($form_data['type'] == 2)
			{	
				if($form_data['utrzymanie'] < 10 || $form_data['utrzymanie'] > 40)
					$errors['utrzymanie'] = $alerts['field_invalid'];
					
				if($form_data['rabat'] < 0 || $form_data['rabat'] > ($form_data['utrzymanie']-5))
					$errors['rabat'] 	= $alerts['field_invalid'];	
			}
			
				if($form_data != null && $errors != null)
				{
					$data['form_data']	    = $form_data;	
					$data['errors']	  		= $errors;
				}
				else
				{
					$result = $this->baza->add_employee($form_data['imie'],$form_data['haslo'],$form_data['email'],$form_data['type'],$form_data['utrzymanie'],$form_data['rabat'],$form_data['active'],$form_data['customers']);
					if($result)
					{
						redirect('/master/employees/1','location');			
					}
					else
					{		
						$data['form_data']	    = $form_data;	
						$data['errors']	  		= $errors;						
						$data['info']			= 'Wystapił bład, pracownik nie został dodany.';		
					}						
				}
		}
		//wykluczenie zalogowanego uzytkownika
		$excluded_ids = array($data['master_id']);
		
		$data['employees']		= $this->baza->get_all_employees();
		$data['free_customers'] = $this->baza->get_users_without_manager_id();
	
		$data['mainContent']	= $this->load->view('master/add_employee_form',$data,true);
		$this->load->view('/layout/master',$data);			
		
	}
	//------------------------------------------------------------------------------------------------------------------
	function employee_profile($id)
	{
		
		$data['user']  						= $this->user_data[0]['name'];
		$data['master_id']					= $this->session->userdata['master_id'];
		$data['employee_types']				= $this->global_settings['employee_types'];
		
		$data['employee_id']				= $id;
		$superadmin							=  $this->baza->get_superadmin_data($id);	//edytowany pracownik
		$data['superadmin']					= $superadmin[0];
		$data['employees']					= $this->baza->get_active_employees();		//wszyscy pracownicy
		$data['employee_customers']			= $this->baza->get_superadmin_users($id);	//klienci pracownika
		$data['customers'] 					= $this->baza->get_users();					//wszyscy klienci
				
		$form_data				= null;
		$errors					= null;
		
		if(!empty($_POST))
		{
			$this->load->library('walidacja');
			$this->config->load('alerts');
			$alerts							=  $this->config->item('alerts');
					
			
			$form_data['imie']   			= trim($_POST['imie']);
			$form_data['email']  			= trim($_POST['email']);
			$form_data['haslo']  			= trim($_POST['haslo']);
			$form_data['haslo2'] 			= trim($_POST['haslo2']);
			$form_data['utrzymanie'] 		= isset($_POST['utrzymanie']) ? (int)$_POST['utrzymanie'] 	: null;
			$form_data['rabat'] 			= isset($_POST['rabat']) 	  ? (int)$_POST['rabat'] 		: null;
			$form_data['active'] 			= (int)$_POST['active'];
			$form_data['zwolniony'] 		= (int)$_POST['zwolniony'];
			$form_data['new_manager'] 		= isset($_POST['new_manager']) ? $_POST['new_manager'] : null;
			$form_data['type']				= (int)$_POST['type'];
			
			$form_data['customers']			= isset($_POST['customers']) ? $_POST['customers'] : null;;
				
			
			
			if(!$this->walidacja->CheckEmail($form_data['email']))
				$errors['email'] 	= $alerts['field_invalid'];
					
			if(empty($form_data['imie']))
				$errors['imie'] 	= $alerts['field_required'];

			if(empty($form_data['email']))
				$errors['email'] 		= $alerts['field_required'];				
								
			if(isset($form_data['haslo']) && ($form_data['haslo'] != $form_data['haslo2']))	
				$errors['haslo2'] 		= $alerts['field_invalid'];
			
			if($form_data['type'] == 2)	
			{
				if($form_data['utrzymanie'] < 10 || $form_data['utrzymanie'] > 40)
					$errors['utrzymanie'] 	= $alerts['field_invalid'];
					
				if($form_data['rabat'] < 0 || $form_data['rabat'] > ($form_data['utrzymanie']-5))
					$errors['rabat'] 		= $alerts['field_invalid'];	
			}
			
			//ksiegowa nie moze byc zwolniona
			if($form_data['type'] == 3)
			{
				if(!empty($form_data['zwolniony']) && ($form_data['zwolniony'] == 1))	
						$errors['zwolniony'] 	= "Księgowa nie może być zwolniona";			
			}
					
				if($form_data != null && $errors != null)
				{
					$data['form_data']	    = $form_data;	
					$data['errors']	  		= $errors;
				}
				else
				{
					//jesli pracownik jest zwolniony to od razu jest nie aktywny
					if($form_data['zwolniony'])
						$form_data['active'] = 0;
					
					// edit_employee($id,$name,$password,$email,$type,$utrzymanie,$rabat,$active=0,$clients=null,$new_manager_id=null)	
					if($this->baza->edit_employee($id,$form_data['imie'],$form_data['haslo'],$form_data['email'],$form_data['type'],$form_data['utrzymanie'],$form_data['rabat'],$form_data['active'],$form_data['zwolniony'],$form_data['customers'],$form_data['new_manager']))
					{
							redirect('/master/employees/1','location');
							//$data['info']			= $alerts['operation_success'];
							//$data['form_data']	    = $form_data;
							
					}else
					{
						$data['form_data']	    = $form_data;	
						$data['errors']	  		= $errors;						
						$data['info']			= $alerts['operation_fail'];		
					}						
				}
				
		}		 
		elseif(empty($_POST))
		{
			$form_data['imie']   		= $data['superadmin']['name'];
			$form_data['email']  		= $data['superadmin']['email'];
			$form_data['utrzymanie'] 	= $data['superadmin']['utrzymanie'];
			$form_data['rabat'] 		= $data['superadmin']['rabat'];
			$form_data['type'] 			= $data['superadmin']['type'];
			$form_data['zwolniony'] 	= $data['superadmin']['zwolniony'];
			$form_data['active'] 		= (int)$data['superadmin']['active'];

					
			if($form_data['active'] == 1)
			{
				//wyciagniecie samych wartosci ID
				foreach($data['employee_customers'] as $k=>$v)	
					$form_data['customers'][]= $v['id'];
			}
			else
			{
				$form_data['customers']    = unserialize($data['superadmin']['history_users']);	
			}
			
			$data['form_data']	    	= $form_data;
		}
		
		if(isset($form_data['customers']) && count($form_data['customers']) > 0 && is_null($data['superadmin']['history_users']))
				$data['przepisz_klientow']  = 1;
						
		return $this->load->view('master/employee_profile',$data,true);
				
	}
	//------------------------------------------------------------------------------------------------------------------
	function employee_tickets($employee_id,$type=0,$pageId=0,$condition=null)
	{
		$this->load->model('ticket','',TRUE);	
		$this->load->library('pagination');
		
		$list_types  				= array("odebrane","wysłane");
		$data['list_types']			= $list_types;
		$data['list_type']	   		= $list_types[$type];
		$data['link_postfiks']		= '#tabs-2';
				
		$data['employee_id']	= $employee_id;
		$employee_account 		= $this->baza->get_super_admin_account($employee_id);
		
		$type 					= (int)$type;
		$pageId 				= (int)$pageId;
		$tickestPerPage			 = 4;
		
		$config['base_url']    = base_url().'/master/employee/'.$employee_id.'/'.$type.'/';
		
			
		if ($type == 0)
			$config['total_rows']  = $this->ticket->get_amount_of_received_tickets($employee_account['id'],$condition);
		else
			$config['total_rows']  = $this->ticket->get_amount_of_sended_tickets($employee_account['id'],$condition);
		
		$config['per_page']    		= $tickestPerPage; 
		$config['uri_segment'] 		= 5;
		$config['link_postfiks']	= $data['link_postfiks'];
		
		$this->pagination->initialize($config);
		
		

			 
			 
		if($type == 0)
			$data['tickets']    = $this->ticket->get_received_ticket_list($employee_account['id'],$pageId,$tickestPerPage,$condition);
		else
			$data['tickets']	= $this->ticket->get_sended_ticket_list($employee_account['id'],$pageId,$tickestPerPage,$condition);		 			
		
		$data['paginacja'] 		= $this->pagination->create_links();		
		return $this->load->view('master/client_tickets',$data,true);
	}
	//------------------------------------------------------------------------------------------------------------------
	function delete_master($id)
	{
		$id = (int)$id;
		if($this->baza->delete_master($id))
			redirect('/master/masters/1', 'refresh');
		else
			redirect('/master/masters/0', 'refresh');		
	}	
	//------------------------------------------------------------------------------------------------------------------
	function delete_employee($id)
	{
		$id = (int)$id;
		if($this->baza->delete_employee($id))
			redirect('/master/employees/1', 'refresh');
		else
			redirect('/master/employees/0', 'refresh');		
	}
	//------------------------------------------------------------------------------------------------------------------
	function change_master_pass()
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		$this->load->library('walidacja');
		$this->config->load('alerts');
		$alerts					= $this->config->item('alerts');
		$form_data				= null;
		$errors					= null;
		
		if(!empty($_POST))
		{
			$form_data['haslo']   		= trim($_POST['haslo']);
			$form_data['nowe_haslo']    = trim($_POST['nowe_haslo']);
			$form_data['nowe_haslo2']   = trim($_POST['nowe_haslo2']);

			if($form_data['nowe_haslo2'] != $form_data['nowe_haslo'])
				$errors['nowe_haslo2'] = 'Potwierdzenie hasła jest niepoprawne.';
							
			if(empty($form_data['haslo']))
				$errors['haslo'] = 'Wartośc pola nie może być pusta';

			if(empty($form_data['nowe_haslo']))
				$errors['nowe_haslo'] = 'Wartośc pola nie może być pusta';
				
			if(empty($form_data['nowe_haslo2']))
				$errors['nowe_haslo2'] = 'Wartośc pola nie może być pusta';
			
			if(!$this->baza->is_valid_master_password($form_data['haslo'],$data['master_id']))
				$errors['haslo'] = 'Podane hasło jest niepoprawne.';				
				
				if($form_data != null && $errors != null)
				{
					$data['form_data']	    = $form_data;	
					$data['errors']	  		= $errors;
				}
				else
				{
					if($this->baza->change_master_pass($form_data['nowe_haslo'],$data['master_id']))
					{
						$data['info']	=	$alerts['operation_success'];
						$haslo_md5 		= 	md5($form_data['nowe_haslo']);
						$this->session->set_userdata('user_master_zalogowany',$haslo_md5);
						//redirect('/master','location');							
					}
					else
						$data['info']	=	$alerts['operation_fail'];	
				}
		}		
		
		$data['mainContent']	= $this->load->view('master/change_master_pass_form',$data,true);
		$this->load->view('/layout/master',$data);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function login()
	{
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span style="color:red;">', '<br /></span>');
		
		$fields['login_form'] 	= 'login_form';
		$fields['pass'] 		= 'pass';
		$this->validation->set_fields($fields);
					
		$login_form 			= $this->validation->login_form;
		$pass_form			 	= $this->validation->pass;
		$rules['login_form'] 	= "callback_login_form_check|required";
		$rules['pass'] 			= "callback_pass_check[$login_form]|required";
		$this->validation->set_rules($rules);
		
		if($this->validation->run() == FALSE)
		{
			$this->load->view('/layout/home');		
		}
		else
		{
			$haslo_md5 		= md5($pass_form);
			$uzyt 			= $this->baza->master($login_form);
			$master_id 		= $uzyt[0]['id'];
			$this->session->set_userdata('user_master_zalogowany',$haslo_md5);
			$this->session->set_userdata('master_id',$master_id);
			
			redirect('/master/start','location');
		}		
	}	
	//------------------------------------------------------------------------------------------------------------------
	function logout()
	{
		$this->session->sess_destroy();
		redirect('/master','refresh');
	}	
	//------------------------------------------------------------------------------------------------------------------
	function login_form_check($str)
	{
		$user=$this->baza->master($str); 
		
		if ($user==null or $str==null)
		{
				$this->validation->set_message('login_form_check', 'Błędny login');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	//------------------------------------------------------------------------------------------------------------------
	function pass_check($pass,$login)
	{
		if($pass==null or $login==null)
		{
			$password = null; 	
		}
		else	
		{
			$haslo 		= md5($pass);
			$password 	= $this->baza->master_check_user_pass($haslo, $login); 	
		}
		
		if ($password == null)
		{
			$this->validation->set_message('pass_check', 'Błędne hasło');
			return FALSE;
		}
		else
		{	
			return TRUE;
		}
	}	
	//------------------------------------------------------------------------------------------------------------------
	function client($client_id,$tickets_type=0,$tickets_pageId=0,$tickets_condition=null)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		$data['client_id']		= $client_id;
		
		//tabs content
		$data['client_account']		= $this->client_account($client_id);
		$data['client_profile']		= $this->client_profile($client_id);
		$data['client_domains']		= $this->client_domains($client_id);
		$data['client_tickets']		= $this->client_tickets($client_id,$tickets_type,$tickets_pageId,$tickets_condition);
		$data['client_contracts']	= $this->client_contracts($client_id);
		
		$data['mainContent']	= $this->load->view('master/client',$data,true);
		$this->load->view('/layout/master',$data);				
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_account($client_id)
	{
		$data['client_id']		= $client_id;
		
		if(!empty($_POST['client_account']))
		{
			$this->load->library('walidacja');
			$this->config->load('alerts');
			$alerts		=  $this->config->item('alerts');
			
			$errors 		=	null;
			$values			=	null;
			
			$values['id']				=	(int)$_POST['id'];
			$values['name']				=	trim($_POST['name']);
			$values['password']			=	trim($_POST['password']);
			$values['password2']		=	trim($_POST['password']);
			$values['active']			=	trim($_POST['active']);
			
			if(empty($values['name']))
				$errors['name']			=	$alerts['field_required'];
			elseif(!$this->baza->is_unique_client_name($values['name'],$values['id']))
				$errors['name']			=	$alerts['field_not_unique'];

			if(!empty($values['password']) && !empty($values['password2']))
			{
				if($values['password'] != $values['password2'])
					$errors['password2']	=	$alerts['field_invalid'];				
			}
			
			if (is_null($errors))							
			{				
			
				$result = null;
				if(!empty($values['password']))
					$result = $this->baza->update_user($values['id'],$values['name'],$values['password'],$values['active']); 						
				else
					$result = $this->baza->update_user($values['id'],$values['name'],null,$values['active']);	
					
				if($result)
				{
					$data['info'] = $alerts['operation_success'];
					$errors 	  = null;
					$values       = null;
				}
				else
				{
					$data['info'] = $alerts['operation_fail'];
				}
			}
			else
			{
				$data['info'] = $alerts['operation_fail'];
			}
			
			$data['values']			=	$values;
			$data['errors']			=	$errors;						
		}
	
		$data['user'] 			= $this->baza->get_user($client_id);		
		return $this->load->view('master/client_account',$data,true);
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_profile($client_id)
	{
		$data['client_id']		= $client_id;
		
		
		$this->load->library('walidacja');
		$this->config->load('alerts');
		$alerts		=  $this->config->item('alerts');
		
		if(!empty($_POST['client_profile']))
		{
		
			$errors 	=	null;
			$values		=	null;
			
			$values['id']				=	(int)$_POST['id'];
			$values['user_id']			=	(int)$_POST['user_id'];
			$values['company_name']		=	trim(strip_tags($_POST['company_name']));
			$values['contact_name']		=	trim(strip_tags($_POST['contact_name']));
			$values['tax_id']			=	trim(strip_tags($_POST['tax_id']));
			$values['website']			=   trim(strip_tags($_POST['website']));
			$values['email']			=   trim(strip_tags($_POST['email']));
			$values['city']				=	trim(strip_tags($_POST['city']));
			$values['post_code']		=	trim(strip_tags($_POST['post_code']));
			$values['street']			=	trim(strip_tags($_POST['street']));
			$values['b_no']				=	trim(strip_tags($_POST['b_no']));
			$values['a_no']				=	trim(strip_tags($_POST['a_no']));				//nullable
			$values['dk_miasto']		=	trim(strip_tags($_POST['dk_miasto']));			//nullable
			$values['dk_ulica']			=	trim(strip_tags($_POST['dk_ulica']));			//nullable
			$values['dk_kod_pocztowy']	=	trim(strip_tags($_POST['dk_kod_pocztowy']));	//nullable
			$values['dk_nr_domu']		=	trim(strip_tags($_POST['dk_nr_domu']));			//nullable
			$values['dk_nr_mieszkania']	=	trim(strip_tags($_POST['dk_nr_mieszkania']));	//nullable
			$values['dk_telefon']		=	trim(strip_tags($_POST['dk_telefon']));			//nullable
			
			
			//walidacja
			if(empty($values['id']))
				$errors['id']					=	$alerts['field_required'];
			if(empty($values['user_id']))
				$errors['user_id']				=	$alerts['field_required'];
				

			if(empty($values['contact_name']))
				$errors['contact_name']			=	$alerts['field_required'];
				
			if(empty($values['tax_id']))
				$errors['tax_id']				=	$alerts['field_required'];
			elseif(!$this->walidacja->CheckNIP($values['tax_id']))		
				$errors['tax_id']				=	$alerts['field_invalid'];	
			
			//website	
			$website = str_replace(array("http",":","/"),"",$values['website']);
			if(!empty($values['website']) && !$this->walidacja->CheckURL("http://".$website."/"))
				$errors['website']				=	$alerts['field_invalid'];
			
			//email
			if(empty($values['email']))
				$errros['email']				=	$alerts['field_required'];
			elseif(!$this->walidacja->CheckEmail($values['email']))
				$errors['email']				=	$alerts['field_invalid'];
			
			//city						
			if(empty($values['city']))
				$errors['city']					=	$alerts['field_required'];
			//kod pocztowy
			if(empty($values['post_code']))
				$errors['post_code']			=	$alerts['field_required'];
			//ulica
			if(empty($values['street']))
				$errors['street']				=	$alerts['field_required'];
			//nr budynku
			if(empty($values['b_no']))
				$errors['b_no']					=	$alerts['field_required'];
				
			//dane korespondencyjne	- jeśli ktoś podał chociaż jedno pole to walidacja
			if(!empty($values['dk_miasto']) || !empty($values['dk_ulica']) || !empty($values['dk_kod_pocztowy']) || !empty($values['dk_nr_domu']) || !empty($values['dk_nr_mieszkania']) || !empty($values['dk_telefon']))
			{
				if(empty($values['dk_miasto']))
					$errors['dk_miasto']			=	$alerts['field_required'];
				
				if(empty($values['dk_ulica']))
					$errors['dk_ulica']				=	$alerts['field_required'];
					
				if(empty($values['dk_kod_pocztowy']))
					$errors['dk_kod_pocztowy']		=	$alerts['field_required'];
					
				if(empty($values['dk_nr_domu']))
					$errors['dk_nr_domu']		=	$alerts['field_required'];																											
			}	
			
			if (is_null($errors))							
			{						
				if($this->baza->update_user_data($values['id'],$values['user_id'],$values['company_name'],$values['contact_name'],$values['tax_id'],$values['website'],$values['email'],$values['city'],$values['post_code'],$values['street'],$values['b_no'],$values['a_no'],$values['dk_miasto'],$values['dk_ulica'],$values['dk_kod_pocztowy'],$values['dk_nr_domu'],$values['dk_nr_mieszkania'],$values['dk_telefon']))
				{
					$data['info'] = $alerts['operation_success'];
					$errors 	  = null;
					$values       = null;
				}
				else
				{
					$data['info'] = $alerts['operation_fail'];
				}
			}
			else
			{
				$data['info'] = $alerts['operation_fail'];
			}
			
			$data['values']			=	$values;
			$data['errors']			=	$errors;			
		}
		$data['user_data'] = $this->baza->get_user_data($client_id);	
		
		return $this->load->view('master/client_profile',$data,true);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_domains($client_id)
	{
		$data['client_id']		= $client_id;
		$data['domains'] 		= $this->baza->get_domains($client_id);
		return $this->load->view('master/client_domains',$data,true);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_tickets($client_id,$type=0,$pageId=0,$condition=null)
	{
		$this->load->model('ticket','',TRUE);	
		$this->load->library('pagination');
		
		$list_types  				= array("odebrane","wysłane");
		$data['list_types']			= $list_types;
		$data['list_type']	   		= $list_types[$type];
		$data['link_postfiks']		= '#tabs-4';
				
		$data['client_id']		= $client_id;
		$client_account 		= $this->baza->get_user_account($client_id);
		
		$type 					= (int)$type;
		$pageId 				= (int)$pageId;
		$tickestPerPage			 = 4;
		
		$config['base_url']    = base_url().'/master/client/'.$client_id.'/'.$type.'/';
		
			
		if ($type == 0)
			$config['total_rows']  = $this->ticket->get_amount_of_received_tickets($client_account['id'],$condition);
		else
			$config['total_rows']  = $this->ticket->get_amount_of_sended_tickets($client_account['id'],$condition);
		
		$config['per_page']    		= $tickestPerPage; 
		$config['uri_segment'] 		= 5;
		$config['link_postfiks']	= $data['link_postfiks'];
		
		$this->pagination->initialize($config);
		
		
					 
			 
		if($type == 0)
			$data['tickets']    = $this->ticket->get_received_ticket_list($client_account['id'],$pageId,$tickestPerPage,$condition);
		else
			$data['tickets']	= $this->ticket->get_sended_ticket_list($client_account['id'],$pageId,$tickestPerPage,$condition);		 			
		
		$data['paginacja'] 		= $this->pagination->create_links();		
		return $this->load->view('master/client_tickets',$data,true);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_contracts($client_id)
	{
		$data = array();
		$data['contracts']	=  $this->baza->get_client_contracts($client_id);
		return $this->load->view('master/client_contracts',$data,true);
	}
	//------------------------------------------------------------------------------------------------------------------
	function networds()
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		$this->load->library('walidacja');
		$this->config->load('alerts');
		$alerts	=  $this->config->item('alerts');		
		$values = null;
		$errors = null;
		
		if(!empty($_POST))
		{
			$values['id']				= $_POST['id'];	
			$values['nazwa']			= $_POST['nazwa'];
			$values['nip']				= $_POST['nip'];
			$values['regon']			= $_POST['regon'];
			$values['bank']				= $_POST['bank'];
			$values['nr_konta']			= $_POST['nr_konta'];
			$values['miasto']			= $_POST['miasto'];
			$values['ulica']			= $_POST['ulica'];
			$values['nr_budynku']		= $_POST['nr_budynku'];
			$values['nr_lokalu']		= $_POST['nr_lokalu'];
			$values['kod_pocztowy']		= $_POST['kod_pocztowy'];
			$values['kraj']				= $_POST['kraj'];
			$values['telefon']			= $_POST['telefon'];
			$values['telefon_kom']		= $_POST['telefon_kom'];
			$values['fax']				= $_POST['fax'];
			$values['skype']			= $_POST['skype'];
			$values['www']				= $_POST['www'];
			$values['email']			= $_POST['email'];
			
			if(is_null($errors))
			{
				$result = $this->baza->edit_networds($values);
				if($result)
				{
					$data['info'] = $alerts['operation_success'];
					//$values 	  = null;
					$errors 	  = null;					
				}
				else
					$data['info'] = $alerts['operation_fail'];	
								
			}
		}
		else
		{
				$networds		= $this->baza->get_networds();
				foreach($networds as $k=>$v)
					$values[$k] = $v; 	
		}		
		
		$data['values'] = $values;
		$data['errors'] = $errors;
		
		$data['mainContent']	= $this->load->view('master/networds',$data,true);
		$this->load->view('/layout/master',$data);				
	}
	//------------------------------------------------------------------------------------------------------------------
	function email_aliases()
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		$data['email_aliases']  = $this->baza->get_email_aliases();
		$data['mainContent']	= $this->load->view('master/email_aliases',$data,true);
		$this->load->view('/layout/master',$data);			
	}
	//------------------------------------------------------------------------------------------------------------------
	function email_alias($id)
	{
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		$data['email_alias']	= $this->baza->get_email_alias($id);
		
		$this->load->library('walidacja');
		$this->config->load('alerts');
		$alerts	=  $this->config->item('alerts');	
				
		$values = null;
		$errors = null;
		
			
		if(!empty($_POST))
		{
			$values['id']  			= (int)($_POST['id']);
			$values['nazwa']  		= strip_tags(trim($_POST['nazwa']));
			$values['alias_email']  = strip_tags(trim($_POST['alias_email']));
			
			if(empty($values['nazwa']))
				$errors['alias_email'] = $alerts['field_required'];
											
			if(empty($values['alias_email']))
				$errors['alias_email'] = $alerts['field_required'];
			elseif(!$this->walidacja->CheckEmail($values['alias_email']))	
				$errors['alias_email'] = $alerts['field_invalid'];	
				
				
			if(is_null($errors))
			{
				$result = $this->baza->edit_email_alias($values['id'],$values['alias_email']);
				if($result)
				{
					$data['info'] = $alerts['operation_success'];
					$errors 	  = null;					
				}
				else
					$data['info'] = $alerts['operation_fail'];
			}
			else
			{
				$data['info'] = $alerts['operation_fail'];
			}			
		}
		else
		{
			foreach($data['email_alias'] as $k=>$v)
				$values[$k] = $v;			
		}
		
		$data['values'] = $values;
		$data['errors'] = $errors;
		
		$data['mainContent']	= $this->load->view('master/email_alias',$data,true);
		$this->load->view('/layout/master',$data);			
	}	
	//------------------------------------------------------------------------------------------------------------------
	function mailing()
	{
		echo 'coming soon';		
	}
	//------------------------------------------------------------------------------------------------------------------
    function settings($type=null,$id=null)
    {
		$data['user']  			= $this->user_data[0]['name'];
		$data['master_id']		= $this->session->userdata['master_id'];
		
		//tabs content
		$data['settings_commission']       = (!empty($id) && ($type == 'commission')) ? $this->settings_commission($id) : $this->settings_commission();
		$data['settings_sem_commission']   = (!empty($id) && ($type == 'sem_commission')) ? $this->settings_sem_commission($id) : $this->settings_sem_commission();
		
		$data['mainContent']	= $this->load->view('master/settings',$data,true);
		$this->load->view('/layout/master',$data);		        
    }
    //------------------------------------------------------------------------------------------------------------------
    function settings_commission($id=null)
    {
        $data       = null;
        $data['commissions'] = $this->baza->get_prowizje_settings();

        $values = null;
        $errors = null;
        
        if(!empty($data['commissions']))
        {
            $id = (empty($id) ? $data['commissions'][0]['id']:$id);
            $values = $this->baza->get_prowizje_settings($id);
        }
        if(!empty($_POST['commission']))
        {
            $values['id']       =   $_POST['id'];
            $values['od']       =   $_POST['od'];
            $values['do']       =   $_POST['do'];
            $values['procent']  =   $_POST['procent'];

            //walidacja
			$this->config->load('alerts');
			$alerts		=  $this->config->item('alerts');

            if(!isset($values['od']))
                $errors['od'] = $alerts['field_required'];
            elseif(!is_numeric($values['od']))
                $errors['od'] = $alerts['field_invalid'];

            if(!isset($values['do']))
                $errors['do'] = $alerts['field_required'];
            elseif(!is_numeric($values['do']))
                $errors['do'] = $alerts['field_invalid'];

            if(!isset($values['procent']))
                $errors['procent'] = $alerts['field_required'];
            elseif(!is_numeric($values['procent']))
                $errors['procent'] = $alerts['field_invalid'];

            if(empty($errors))
            {
                $result = $this->baza->edit_prowizje_settings($values['id'],$values['od'],$values['do'],$values['procent']);
                if($result)
					$data['info']['settings_commission']	=	$alerts['operation_success'];
				else
					$data['info']['settings_commission']	=	$alerts['operation_fail'];
            }

        }

        $data['values'] = $values;
        $data['errors'] = $errors;

        return $this->load->view('master/settings_commission',$data,true);
    }
    //------------------------------------------------------------------------------------------------------------------
    function settings_sem_commission($id=null)
    {
        $data       = null;
        $data['sem_comissions'] = $this->baza->get_prowizje_sem();

        $values = null;
        $errors = null;

        if(!empty($data['sem_comissions']))
        {
            $id     = (empty($id) ? $data['sem_comissions'][0]['id'] : $id);
            $values = $this->baza->get_prowizje_sem_settings($id);
        }
        if(!empty($_POST['sem_commission']))
        {
            $values['id']       =   $_POST['id'];
            $values['procent']  =   $_POST['procent'];

            //walidacja
			$this->config->load('alerts');
			$alerts		=  $this->config->item('alerts');
            
            if(!isset($values['procent']))
                $errors['procent'] = $alerts['field_required'];
            elseif(!is_numeric($values['procent']))
                $errors['procent'] = $alerts['field_invalid'];

            if(empty($errors))
            {
                $result = $this->baza->edit_prowizje_sem_settings($values['id'],$values['procent']);
                if($result)
					$data['info']['settings_sem_commission']	=	$alerts['operation_success'];
				else
					$data['info']['settings_sem_commission']	=	$alerts['operation_fail'];
            }
        }

        $data['values'] = $values;
        $data['errors']  = $errors;

        return $this->load->view('master/settings_sem_commission',$data,true);
    }
    //------------------------------------------------------------------------------------------------------------------
	function show_contract($contract_id)
	{
		$contract = $this->baza->get_user_contract($contract_id);
		if($contract)
		{
			$file_handle 	= fopen($contract['sciezka'],"r");
			$file_name      = basename($contract['sciezka']);
			 
			header('Content-Type: application/pdf');
			header('Content-Disposition: inline; filename="'.$file_name.'"');
			//header('Cache-Control: private, max-age=0, must-revalidate');
			echo file_get_contents($contract['sciezka']);
		}
		else
			echo 'error';
	}
	//------------------------------------------------------------------------------------------------------------------
}
?>