<?php

class Superadmin extends Controller {

	function Superadmin()
	{
		parent::Controller();
		$this->load->library('session');	
		$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');

	}
	
	function _check_domain_owner($manager_id, $domain_id)
	{
		$domain = $this->baza->superadmin_check_domain_owner($manager_id, $domain_id);
		if($domain!=null)
		{
			return true;
		}
		else
		{
			return redirect('/superadmin','location');	
		}
	}
	
	function index($ticket_id=null)
	{
        //tablica z userami id do usuniecia
        //$array = array(43,44);

        //foreach($array as $i)
         // $this->baza->del_user($i);
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data==null)	
			{
				redirect('/superadmin/logout','location');
			}
			else
			{
				redirect('/superadmin/start','location');
			}
		}
		else
		{
			$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->superadmin_user($login_form);
				$di = $uzyt[0]['id'];
				$this->session->set_userdata('user_sa_zalogowany',$haslo_md5);
				$this->session->set_userdata('di_sa',$di);
				
				if($ticket_id != null)
					redirect('/tickets/show/'.$ticket_id,'location');
				else
					redirect('/superadmin/start','location');	
				//redirect('/superadmin/start','location');
			}
		}
	}
	
	function start()
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']  = $user_data[0]['name'];
                $this->load->model('ticket','',TRUE);
				//$this->load->view('/layout/start_page',$data);

                $data['messages']       =   array();//dashboard items
                $user_account           =   $this->baza->get_super_admin_account($this->session->userdata['di_sa']);
                $unreaded_tickets_msg   =   $this->ticket->get_info_about_unreaded_tickets($user_account['id']); //nieodebrane tickety
                if(!empty($unreaded_tickets_msg))
                    $data['messages'][] = $unreaded_tickets_msg;


                $data['content']    = $this->load->view('superadmin/start',$data,true);
                $this->load->view('/layout/default',$data);
				
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
		
	function add_afiliant()
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$data['user']   = $user_data[0]['name'];
			$valid_form 	= null;
			
			
			if($user_data!=null)	
			{
				if(empty($_POST))
				{
					
					$data['content']  = $this->load->view('/superadmin/add_afiliant',null,true);	
				}
				else
				{
					foreach($_POST as $k=>$v)
					{
						if($k!='uwagi' and $k!='nr_mieszkania' and $k!='nip' and $k!='regon')
						{
							if($v=='') $valid_form = 'blad';
						}
					}
					
					if($valid_form=='blad')
					{
						$data['blad'] = 'Pola formularza z * są wymagane';
						$data['content']  = $this->load->view('/superadmin/add_afiliant',$data,true);
					}
					else
					{
						$this->baza->superadmin_add_afiliant($_POST);
						$data['info'] = 'Afiliant został dodany';
						$data['content']  = $this->load->view('/superadmin/add_afiliant',$data,true);	
					}
				}
								
				
				$this->load->view('/layout/default',$data);				
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
    //------------------------------------------------------------------------------------------------------------------
	function employees()
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']   		= $user_data[0]['name'];
				$data['employees']		= $this->baza->get_all_employees();
				$data['content']		= $this->load->view('/superadmin/employees',$data,true);
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}		
	}
	//------------------------------------------------------------------------------------------------------------------
	function employee($id,$tickets_type=0,$tickets_pageId=0,$tickets_condition=null)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']   		= $user_data[0]['name'];
				
				$data['employee_tickets']	= $this->employee_tickets($id,$tickets_type,$tickets_pageId,$tickets_condition);
				$data['content']			= $this->load->view('/superadmin/employee',$data,true);
				
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}				
	}
	//------------------------------------------------------------------------------------------------------------------
	function employee_tickets($employee_id,$type=0,$pageId=0,$condition=null)
	{
		$this->load->model('ticket','',TRUE);	
		$this->load->library('pagination');
		
		$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().'/superadmin/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']	= '#tabs-1';
		
		$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($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('superadmin/employee_tickets',$data,true);
	}
	//------------------------------------------------------------------------------------------------------------------
	function clients()
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']   		= $user_data[0]['name'];
				$data['clients']		= $this->baza->get_all_users();
				$data['content']		= $this->load->view('/superadmin/clients',$data,true);
				
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	//------------------------------------------------------------------------------------------------------------------
	function client($client_id,$tickets_type=0,$tickets_pageId=0,$tickets_condition=null)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']   			= $user_data[0]['name'];
                
				$data['client'] 				= $this->baza->get_user($client_id);
                $data['clients']                = $this->baza->get_all_users();
                
				$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['content']		= $this->load->view('/superadmin/client',$data,true);
				
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}	
	//------------------------------------------------------------------------------------------------------------------
	function client_account($client_id)
	{
		$data['user'] 				= $this->baza->get_user($client_id);
		
		if(!empty($data['user']['manager_id']))
		{
			$manager_id                 = (int)$data['user']['manager_id'];
			$manager 					= $this->baza->get_superadmin_data($manager_id);
			if(!empty($manager))
				$data['user']['manager']	= $manager[0]['name'];
		}
		
		return $this->load->view('superadmin/client_account',$data,true);		
	}
	//------------------------------------------------------------------------------------------------------------------
	function client_profile($client_id)
	{
		$data['user_data'] = $this->baza->get_user_data($client_id);
		$data['user_data'] = $data['user_data'][0];
		
		return $this->load->view('superadmin/client_profile',$data,true);		
	}	
	//------------------------------------------------------------------------------------------------------------------
	function client_domains($client_id)
	{
		$data['domains'] 		= $this->baza->get_domains($client_id);	
		return $this->load->view('superadmin/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['list_type']  = 'odebrane';
		else
			 $data['list_type'] = 'wyslane';
			 
			 
		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('superadmin/client_tickets',$data,true);			
	}	
	//------------------------------------------------------------------------------------------------------------------		
	function afiliants()
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']   		= $user_data[0]['name'];
				$data['afiliants']		= $this->baza->get_all_afiliants();
				$data['content']		= $this->load->view('/superadmin/afiliants',$data,true);
				
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}		
	}
	//------------------------------------------------------------------------------------------------------------------
	function edit_afiliant($afiliant_id)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{		
					$data['user']   		= $user_data[0]['name'];
                    $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;



                $data['content']		= $this->load->view('/superadmin/edit_afiliant',$data,true);
				$this->load->view('/layout/default',$data);					
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}					
	}
	
	function add_user_to_afiliant()
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$data['user']   = $user_data[0]['name'];
			$valid_form = null;
			
			if($user_data!=null)	
			{				
				$data_afiliant['afilianci'] = $this->baza->superadmin_all_afiliants();
				//print_r($data_afiliant['afilianci']);
				$data['content']  = $this->load->view('/superadmin/add_user_to_afiliant',$data_afiliant,true);						
				$this->load->view('/layout/default',$data);				
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
		
	function get_affiliant_users($id=null)
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data 		= $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$data['user']   = $user_data[0]['name'];
			$valid_form = null;
			
			if($user_data!=null)	
			{
				if($id!=null)
				{
					$data['afiliant'] = $this->baza->get_affiliant_data($id);
					$data['users'] = $this->baza->get_affiliant_users($id);										
					$this->load->view('superadmin/users_table',$data);	
				}					
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	function get_free_users_for_aff($id=null)
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$valid_form = null;
			
			if($user_data!=null)	
			{
				if($id!=null)
				{
					$data['users'] = $this->baza->get_free_users_for_aff($id);
					$this->load->view('superadmin/add_user_to_aff_table',$data);	
				}					
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	
	function del_affiliant_user($id=null)
	{
		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$valid_form = null;
			
			if($user_data!=null)	
			{
				if($id!=null)
				{
					$this->baza->del_user_from_aff($id);						
				}					
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');
		}
	}
	
	function update_affiliant_user($id=null,$affiliant)
	{		
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			$valid_form = null;
			
			if($user_data!=null)	
			{
				if($id!=null)
				{
					$this->baza->update_user_from_aff($id,$affiliant);						
				}					
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');
		}
	}
			
	function change_region($domain_id)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				if(!empty($_POST['google_region']))
					$this->baza->superadmin_set_region($domain_id, $_POST['google_region']);				
								
				redirect('/superadmin/domain','location');	
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	function domain()
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']  = $user_data[0]['name'];
				
				if(!empty($_POST))	
				{
					$this->config->load('alerts');
					$alerts		=  $this->config->item('alerts');
			
					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['content']    = $this->load->view('superadmin/domain',$data,true);
				$this->load->view('/layout/default',$data);
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	function show_domain_stat($id=null)
	{
        
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);

			if($user_data!=null)	
			{
				$data['user']  = $user_data[0]['name'];
               
				if($id!=null)
				{
                    /*
					if($user_data[0]['name']!='admin')
					{
						$this->_check_domain_owner($this->session->userdata['di_sa'], $id);	
					}
                    */
					$data['colors']         = $this->global_settings['chart_line_colors'];
					$data['keywords']       = $this->baza->get_domain($id);
					$data['pozycja']        = $this->baza->get_domain_key_position($id);
                    $data['google_region']	= $this->baza->google_region($id);

                    $data['mainContent']    = $this->load->view('domains/show_domain_table',$data,true);
                    $this->load->view('/layout/show_chart_domain_page',$data);

					//$this->load->view('/layout/show_domain_page',$data);
				}
				else{
					$this->load->view('blad',$data);
				}
			}
			else
			{
				redirect('/superadmin/logout','refresh');
			}		
		}
		else
		{
			redirect('/admin/','refresh');
		}
	}
	
	function show_domain_chart($id=null,$type = 1,$elem_start = 0)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);

			if($user_data!=null)	
			{
                
				$data['user']  = $user_data[0]['name'];
				
				if($id!=null)
				{	
				
					$data['keywords'] 		= $this->baza->get_keyword_position($id);
					//$domain_name = $this->baza->superadmin_get_doamin_name($id);	
					$data['colors']	  	= $this->global_settings['chart_line_colors'];
					$data['domain_id']		= $id;						
					$data['google_region']	= $this->baza->google_region($id);

                      switch($type)
                        {
                            case 1: {
                                        // "Dzienne";
                                        $data['name_of_type'] = "Dzienne";
                                        $prefs = array (
                                                        'show_next_prev'  => TRUE,
                                                        'next_prev_url'   => '/superadmin/show_domain_chart/'.$id.'/'.$type.'',
                                                        'month_type'   => 'long',
                                                        'day_type'     => 'short'
                                                        );
                                    /*
                                    $prefs['template'] = '

                                                       {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}

                                                       {heading_row_start}<tr>{/heading_row_start}

                                                       {heading_previous_cell}<th><a href="{previous_url}/01">&lt;&lt;</a></th>{/heading_previous_cell}
                                                       {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
                                                       {heading_next_cell}<th><a href="{next_url}/01">&gt;&gt;</a></th>{/heading_next_cell}

                                                       {heading_row_end}</tr>{/heading_row_end}

                                                       {week_row_start}<tr>{/week_row_start}
                                                       {week_day_cell}<td>{week_day}</td>{/week_day_cell}
                                                       {week_row_end}</tr>{/week_row_end}

                                                       {cal_row_start}<tr>{/cal_row_start}
                                                       {cal_cell_start}<td>{/cal_cell_start}

                                                       {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
                                                       {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}

                                                       {cal_cell_no_content}{day}{/cal_cell_no_content}
                                                       {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}

                                                       {cal_cell_blank}&nbsp;{/cal_cell_blank}

                                                       {cal_cell_end}</td>{/cal_cell_end}
                                                       {cal_row_end}</tr>{/cal_row_end}

                                                       {table_close}</table>{/table_close}';
                                       */
                                       $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['mainContent'] = $this->load->view('domains/show_domain_chart',$data,true);
                        $this->load->view('/layout/show_chart_domain_page',$data);
				}
				else{
					$this->load->view('blad',$data);
				}
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	function show_domain_keyword_activity($id = null, $elem_start = 0)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$this->load->model('bazapg','','pg');
				$data['user']  = $user_data[0]['name'];
				$data['stats'] = $this->bazapg->get_stats_pagination($id,$elem_start,50);
				$this->load->library('pagination');
				$number_of_rows = $this->bazapg->count_stats($id);
				if(empty($number_of_rows[0]['ile'])) $number_of_rows[0]['ile']=0;
				
				$config['base_url'] = "/superadmin/show_domain_keyword_activity/$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']=$id;

                $data['mainContent'] = $this->load->view('domains/show_domain_keyword_activity',$data,true);
                $this->load->view('/layout/show_chart_domain_page',$data);    
				//$this->load->view('/layout/show_domain_search_term',$data);
	
			}
			else
			{
				redirect('/admin/logout','location');	
			}
		}		
		else
		{
			redirect('/admin/','location');		
		}
	}
	
	function show_domain_statcounter($id = null, $type = 1)
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']  = $user_data[0]['name'];
				
				if($id!=null)
				{
                    /*
					if($user_data[0]['name']!='admin')
					{
						$this->_check_domain_owner($this->session->userdata['di_sa'], $id);	
					}*/
		
					switch($type)
					{
					    case 1: {
					    			// "Dzienne";
									$data['name_of_type'] = "Dzienne"; 
									$prefs = array (
           					    					'show_next_prev'  => TRUE,
               										'next_prev_url'   => '/superadmin/show_domain_statcounter/'.$id.'/'.$type.'',
							    					'month_type'   => 'long',
							    					'day_type'     => 'short'
             										);
								/*
								$prefs['template'] = '
			
												   {table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
												
												   {heading_row_start}<tr>{/heading_row_start}
												
												   {heading_previous_cell}<th><a href="{previous_url}/01">&lt;&lt;</a></th>{/heading_previous_cell}
												   {heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
												   {heading_next_cell}<th><a href="{next_url}/01">&gt;&gt;</a></th>{/heading_next_cell}
												
												   {heading_row_end}</tr>{/heading_row_end}
												
												   {week_row_start}<tr>{/week_row_start}
												   {week_day_cell}<td>{week_day}</td>{/week_day_cell}
												   {week_row_end}</tr>{/week_row_end}
												
												   {cal_row_start}<tr>{/cal_row_start}
												   {cal_cell_start}<td>{/cal_cell_start}
												
												   {cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
												   {cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_content_today}
												
												   {cal_cell_no_content}{day}{/cal_cell_no_content}
												   {cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
												
												   {cal_cell_blank}&nbsp;{/cal_cell_blank}
												
												   {cal_cell_end}</td>{/cal_cell_end}
												   {cal_row_end}</tr>{/cal_row_end}
												
												   {table_close}</table>{/table_close}';
                                    */
                                   $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;
								}
					}
					
					
					//$this->load->model('bazapg','','pg');
					//$stats = $this->bazapg->get_stats($id);
					
					$data['domain_id']=$id;
					//$data['stats'] = $stats;
					$data['type'] = $type;						
					$this->load->view('/layout/show_stats_chart_domain_page',$data);
				}
				else{
					$this->load->view('blad',$data);
				}
			}
			else
			{
				redirect('/superadmin/logout','location');
			}		
		}
		else
		{
			redirect('/admin/','location');
		}
	}
	
	function profile()
	{
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$data['user']  = $user_data[0]['name'];
		
				if(isset($_POST['id']))
				{
					if($_POST['id']!='')
					{
						$this->baza->superadmin_update_user_data($_POST['id'],$_POST['company_name'],$_POST['contact_name'],$_POST['tax_id'],$_POST['website'],$_POST['email'],$_POST['city'],$_POST['post_code'],$_POST['street'],$_POST['b_no'],$_POST['a_no']);						
						$data['user_data'] = $this->baza->superadmin_get_user_data($this->session->userdata['di_sa']);
						$this->load->view('/layout/profile_page',$data);
					}
					else
					{
						$data['user_data'] = $this->baza->superadmin_get_user_data($this->session->userdata['di_sa']);
						$this->load->view('/layout/profile_page',$data);
					}
				}
				else
				{
					$data['user_data'] = $this->baza->superadmin_get_user_data($this->session->userdata['di_sa']);
					$this->load->view('/layout/profile_page',$data);
				}	
				
			}
			else
			{
				redirect('/superadmin/logout','refresh');	
			}		
		}
		else
		{
			redirect('/admin/','refresh');		
		}
	}
	
	function login_form_check($str)
	{
		$user=$this->baza->superadmin_user($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->superadmin_check_user_pass($haslo, $login); 	
		}
		
		if ($password == null)
		{
			$this->validation->set_message('pass_check', 'Błędne hasło');
			return FALSE;
		}
		else
		{	
			return TRUE;
		}
	}
	
	function change_pass()
	{	
		if(isset($this->session->userdata['user_sa_zalogowany']) and isset($this->session->userdata['di_sa']))
		{	
			$user_data = $this->baza->superadmin_get_user_login($this->session->userdata['user_sa_zalogowany'], $this->session->userdata['di_sa']);
			
			if($user_data!=null)	
			{
				$user  = $user_data[0]['name'];
				$data['user']=	$user_data[0]['name'];
				$this->load->helper(array('form', 'url'));
				$this->load->library('validation');
				$this->validation->set_error_delimiters('<span style="color:red;">', '<br /></span>');
				
				$fields['old_pass'] = 'old_pass';
				$fields['new_pass'] = 'new_pass';
				$fields['new_pass_repeat'] = 'new_pass_repeat';
				$this->validation->set_fields($fields);
				
				$new_pass = $this->validation->new_pass;
				$new_pass_repeat = $this->validation->new_pass_repeat;
				
				$rules['old_pass'] = "callback_old_pass_check[$user]|required";
				$rules['new_pass'] = "callback_new_pass_check[$new_pass_repeat]|required";
				$rules['new_pass_repeat'] = "callback_new_pass_repeat_check[$new_pass]|required";
				$this->validation->set_rules($rules);
				
				if ($this->validation->run() == FALSE)
				{
                    $data['content']    =   $this->load->view('/superadmin/change_pass',$data,true);
					$this->load->view('/layout/default',$data);
				}
				else
				{		
					if($new_pass!=null)
					{
						$haslo = md5($new_pass);
	
						if($this->baza->superadmin_new_pass($user,$haslo))
						{			
							$data['nowe_haslo'] = $new_pass;
							redirect('/superadmin/logout','refresh');
							
							
						}else $this->load->view('blad',$data);
					}else $this->load->view('blad',$data);
				}

			}
			else
			{
				redirect('/superadmin/logout','refresh');
			}	
		}
		else
		{
			redirect('/superadmin/','refresh');
		}
	}
	
	
	function old_pass_check($str,$user)
	{
		$password_baza=$this->baza->superadmin_user($user); 
		$pass =  md5($str);
		
		if($password_baza==null)
		{
			$password_baza[0]['password']='1';
		}
		
		if ($password_baza[0]['password']!=$pass or $pass==null)
		{
				$this->validation->set_message('old_pass_check', 'Błędne hasło');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	
	function new_pass_check($str,$pass_repeat)
	{	
		if ($str!=$pass_repeat or $str==null or $pass_repeat==null )
		{
				$this->validation->set_message('new_pass_check', 'Hasło nowe i hasło nowe powtórzopne muszą być takie same');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	
	function new_pass_repeat_check($str,$new_pass)
	{	
		if ($str!=$new_pass or $new_pass==null or $str=null)
		{
				$this->validation->set_message('new_pass_repeat_check', 'Hasło nowe i hasło nowe powtórzopne muszą być takie same');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	
	function logout()
	{
		$this->session->sess_destroy();
		redirect('/superadmin','refresh');
	}	
	/*
	function forgotten_pass()
	{
		$this->load->helper(array('form', 'url'));
		$this->load->library('validation');
		$this->validation->set_error_delimiters('<span style="color:red;">', '<br /></span>');
		
		$fields['email'] = 'email';
		$this->validation->set_fields($fields);
		
		$rules['email'] = "callback_email_check|required";
		$this->validation->set_rules($rules);
		$email = $this->validation->email;
		
		if ($this->validation->run() == FALSE)
		{
			$this->load->view('layout/forgotten_pass_page');
		}
		else
		{	
			$pass = substr ( md5 ( uniqid ( rand(), true ) ), 0, 5 );
			$haslo = md5($pass);

			if($email!=null)
			{
				//zmienna email zawiera login a nie jak nazwawskazuje email 
				$is_user = $this->baza->user_get_email($email);
				
				if($is_user!=null)
				{
					if($this->baza->superadmin_user_new_pass($email,$haslo))
					{	
						$tresc = 'Twoje nowe hasło to:<br /><br />
									'.$pass.'<br /><br />
									<a href="http://admin.networds.mariusz.jrchosting.com/superadmin" >Zaloguj się</a>
							';	
							
							if($this->send_mail('Przypomnienie hasła', $tresc, $is_user[0]['email'])) 
							{
								$this->load->view('/new_pass_created');
							}	
					}else $this->load->view('/blad');
				}else	$this->load->view('/blad');
			}else $this->load->view('/blad');
		}
	}
	
	function email_check($str)
	{
		$user=$this->baza->superadmin_user($str); 
		
		if ($user==null or $str==null)
		{
				$this->validation->set_message('email_check', 'Błędny login');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	
	function send_mail($title=null, $content_email=null, $email=null)
	{			
		require_once "swift_mailer/Swift.php";
		require_once "swift_mailer/Swift/Connection/SMTP.php";
		require_once "swift_mailer/Swift/Authenticator/LOGIN.php";

		$conn =& new Swift_Connection_SMTP("ubieranki.jrchosting.com");
		$conn->setUsername("mailer@ubieranki.org");
		$conn->setPassword("mailer0987");
		$swift =& new Swift($conn);
		$message =& new Swift_Message($title, $content_email, 'text/html');
		return $swift->send($message, $email, "mailer@ubieranki.org");
		
	}*/
}
?>