<?php
class Afiliant extends Controller {
	
	var $user_logged = false;

	function Afiliant()
	{
		//konstruktor
		parent::Controller();
		$this->load->library('session');	
		$this->load->helper(array('form', 'url','html'));
		$this->load->model('baza','',TRUE);
		$this->load->model('baza_payments','',TRUE);
		$this->load->model('ticket','',TRUE);	
		
		if($this->uri->segment(2) != 'activate' and $this->uri->segment(2) != 'forgotten_pass')
			$this->user_logged = $this->_check_if_logged();
		
	}
	
	function _check_if_logged()
	{
		if($this->uri->segment('2')!='' and $this->uri->segment('2')!='index')
		{
			if(empty($this->session->userdata['id']) and empty($this->session->userdata['pass']))
			{				
				$this->session->sess_destroy();
				redirect('/afiliant', 'location');
			}
			else
			{			
				$data_login = $this->baza->check_id_and_password_afiliant($this->session->userdata['id'],$this->session->userdata['pass']); 
											
				if(!empty($data_login))
				{	
					return true;						
				}
				else 
				{					
					$this->session->sess_destroy();
					redirect('/afiliant', 'location');			
				}
			}
		}		
	}
		
	function index($ticket_id = null)
	{
		$data['user']  = $this->session->userdata('login');
		if(empty($this->session->userdata['id']) and empty($this->session->userdata['pass']))
		{				
			$this->session->sess_destroy();			
		}
		else
		{			
			$data_login = $this->baza->check_id_and_password_afiliant($this->session->userdata['id'],$this->session->userdata['pass']); 
										
			if(!empty($data_login))
			{	
				redirect('/afiliant/start', 'location');						
			}
			else 
			{					
				$this->session->sess_destroy();
				redirect('/afiliant', 'location');			
			}
		}
		
			////////		
		$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
		{	
			$afiliant = $this->baza->afiliant_check_user_pass(md5($pass_form),$login_form);
			//print_r($afiliant); 								
			$this->session->sess_destroy();
			$this->session->set_userdata('id',$afiliant[0]['id']);
			$this->session->set_userdata('login',($afiliant[0]['imie'].' '.$afiliant[0]['nazwisko']));
			$this->session->set_userdata('pass',$afiliant[0]['pass']);
			
			if($ticket_id != null)
				redirect('/tickets/show/'.$ticket_id,'location');
			else	
				redirect('/afiliant/start','location');
		}
	}
	
	function start()
	{
		$data['user']  = $this->session->userdata('login');
		$data['konto']  = $this->baza->afiliant_check_bank_account($this->session->userdata['id']);


        $data['messages']       =   array();//dashboard items
        $user_account           =   $this->baza->get_afiliant_account($this->session->userdata['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['messages'][]     =   "Zarabiaj więcej, znajdź nowego klienta i zgłoś go <a href='/afiliant/newclient'><b>tutaj</b></a>.";

        
        $data['content']    = $this->load->view('afiliant/start',$data,true);
		$this->load->view('/layout/default',$data);
	}
	
	function payments()
	{
		$dane['money'] = $this->baza->affiliant_get_money_from_factures($this->session->userdata['id']);
		$dane['prowizja'] = $this->baza->get_prowizje($this->session->userdata['id']);
		$dane['typ_rozliczenia'] = $this->baza->affiliant_get_typ_rozliczenia($this->session->userdata['id']);
		$afiliant_data = $this->baza->afiliant_get_data($this->session->userdata['id']);
		$dane['afiliant_data'] = $afiliant_data;
		$nr = $this->baza_payments->afiliant_get_document_nr($this->session->userdata['id']); //generowany numer faktury/rachunku na podstawie danych afilianta w bazie
		
		
		$wyplata_ses = array('wyplata'=>array('typ'=>'','krok'=>''));
		
		if(empty($_POST)) 
		{
			//jezeli post pusty wykasowac sesje formularza wyplaty
			$this->session->set_userdata($wyplata_ses);
			$dane['krok'] = $this->session->userdata['wyplata']['krok'];
		}
		else
		{				
			$adres = '';
			
			if(empty($this->session->userdata['wyplata']['typ_rachunku']) and empty($this->session->userdata['wyplata']['krok']))
			{		
				if(!empty($_POST['typ_rachunku']) and !empty($_POST['krok']))
				{
					$wyplata_ses = array('wyplata'=>array('typ'=>$_POST['typ_rachunku'],'krok'=>$_POST['krok']));
					$this->session->set_userdata($wyplata_ses);
															
					$adres .= $afiliant_data[0]['ulica'].' '.$afiliant_data[0]['numer_domu'];						
					if(!empty($afiliant_data[0]['nr_mieszkania'])) $adres .= '/'.$afiliant_data[0]['nr_mieszkania']."\n";
					$adres .= $afiliant_data[0]['kod_pocztowy'].' '.$afiliant_data[0]['miasto'];						
					
					$dane['nr'] = $nr;					
					$dane['adres'] = $adres;
					$dane['nip'] = $afiliant_data[0]['nip'];
					
					if($dane['typ_rozliczenia'][0]['typ']!='Firma'){						
						//rachunek
						$dane['nazwa'] = $afiliant_data[0]['imie'].' '.$afiliant_data[0]['nazwisko'];						
					}else{
						//firma
						$dane['nazwa'] = $afiliant_data[0]['nazwa'];
					}					
				}
				else
				{
					//resetuj formularz
					$wyplata_ses = array('wyplata'=>array('typ'=>'','krok'=>''));
					$this->session->set_userdata($wyplata_ses);
				}
			}
			else
			{
				$adres .= $afiliant_data[0]['ulica'].' '.$afiliant_data[0]['numer_domu'];						
				if(!empty($afiliant_data[0]['nr_mieszkania'])) $adres .= '/'.$afiliant_data[0]['nr_mieszkania']."\n";
				$adres .= $afiliant_data[0]['kod_pocztowy'].' '.$afiliant_data[0]['miasto'];						
				
				$dane['nr'] = $nr;					
				$dane['adres'] = $adres;
				$dane['nip'] = $afiliant_data[0]['nip'];
				
				if($dane['typ_rozliczenia'][0]['typ']!='Firma'){						
					//rachunek
					$dane['nazwa'] = $afiliant_data[0]['imie'].' '.$afiliant_data[0]['nazwisko'];						
				}else{
					//firma
					$dane['nazwa'] = $afiliant_data[0]['nazwa'];
				}
				
				if(!empty($_POST['krok']) and !empty($_POST['nr']) and !empty($_POST['krok']))
				{
					$wyplata_ses = array('wyplata'=>array('typ'=>$this->session->userdata['wyplata']['typ'],'krok'=>$_POST['krok']));
					$this->session->set_userdata($wyplata_ses);
					$dane['post'] = $_POST;
				}								
			}
		}
		
		$data['content'] = $this->load->view('/afiliant/payments',$dane,true);
		$data['user'] = $this->session->userdata('login');
		$this->load->view('/layout/default',$data);	
	}
	
	function rozliczenia()
	{
		$data['user'] 				= $this->session->userdata('login');
		$dane['rozliczenia']		= $this->baza_payments->get_affiliant_rozliczenia($this->session->userdata['id']);		
		$data['content']  			= $this->load->view('/afiliant/rozliczenia',$dane,true);
		
		$this->load->view('/layout/default',$data);	
	}

    function regulamin()
	{
		$data['user'] 				= $this->session->userdata('login');
		$data['content']  			= $this->load->view('/afiliant/regulamin',null,true);
        
		$this->load->view('/layout/default',$data);
	}
	
	function clients()
	{
		$data['user']                                           = $this->session->userdata('login');
		$dane['afiliant_users']		= $this->baza->get_affiliant_users_for_afiliant_list($this->session->userdata['id']);		
		$data['content']                                = $this->load->view('/afiliant/clients',$dane,true);
		
		$this->load->view('/layout/default',$data);	
	}
	
	function profile()
	{
        $afiliant_id         = $this->session->userdata['id'];
		$data['user']        = $this->session->userdata('login');
        $data['afiliant']	 = current($this->baza->get_affiliant_data($afiliant_id));

        $this->load->library('walidacja');
		$this->config->load('alerts');

		$alerts	= $this->config->item('alerts');
        $errors = null;
        $values = null;

        //fetch data
        foreach($data['afiliant'] as $key=>$value)
            if($key != 'pass')
                $values[$key] = $value;

        //process form data
        if(!empty($_POST))
        {
            $values['email']            =   trim(strip_tags($_POST['email']));
            $values['pass']             =   trim(strip_tags($_POST['pass']));
            $values['pass2']            =   trim(strip_tags($_POST['pass2']));

            $values['nazwa']            =   isset($_POST['nazwa']) ? trim(strip_tags($_POST['nazwa'])) : '';      //nazwa firmy
            $values['imie']             =   trim(strip_tags($_POST['imie']));
            $values['nazwisko']         =   trim(strip_tags($_POST['nazwisko']));
            $values['pesel']            =   isset($_POST['pesel']) ? trim($_POST['pesel']) : $values['pesel'];
            $values['nip']              =   trim($_POST['nip']);
            $values['regon']            =   isset($_POST['regon']) ? trim($_POST['regon']) : $values['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['telefon']          =   trim(strip_tags($_POST['telefon']));
            $values['nr_konta']         =   trim(strip_tags($_POST['nr_konta']));

            //dane korespondecyjne
            $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['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;
			}

            //validation
                //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'];


                //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'];
                }


            //UPDATE
            if(is_null($errors))
            {
						$result = $this->baza->edit_afiliant($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']
															);
						if($result)
						{
							$data['info'] 		= $alerts['operation_success'];
                            if(!empty($values['pass']))
                                $this->session->set_userdata('pass',md5($values['pass']));
						}
						else
							$data['info'] = $alerts['operation_fail'];
           }
        }
        else
        {
			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;

        }


		$data['errors'] = $errors;
        $data['values'] = $values;
        $data['content']  = $this->load->view('/afiliant/profile',$data,true);
		$this->load->view('/layout/default',$data);	
	}
	
	function newclient()
	{
		$data['user'] 				= $this->session->userdata('login');
		$dane['afiliant_users']		= $this->baza->get_affiliant_users($this->session->userdata['id']);		
		
			if(isset($_POST['newclient']))
			{

				$errors 			= null;
				$values     		= null;
				
				$client_name						= trim($_POST['client_name']);
				$client_contact_person_name			= trim($_POST['client_contact_person_name']);
				$client_contact_person_telephone	= trim($_POST['client_contact_person_telephone']);	
				$client_contact_person_email		= trim($_POST['client_contact_person_email']);
				$client_contact_person_website		= trim($_POST['client_contact_person_website']); 
				$notes							    = trim($_POST['notes']);
				
				$values['client_name'] 						= strip_tags($client_name);
				$values['client_contact_person_name'] 		= strip_tags($client_contact_person_name);
				$values['client_contact_person_telephone'] 	= strip_tags($client_contact_person_telephone);
				$values['client_contact_person_email'] 		= strip_tags($client_contact_person_email);
				$values['client_contact_person_website'] 	= strip_tags($client_contact_person_website);
				$values['notes'] 							= strip_tags($notes);
				
				//>>walidacja
				
				//nazwa klienta
				if(empty($client_name))
					$errors['client_name']						=	'Pole wymagane';
					
				//osoba kontaktowa	
				if(empty($client_contact_person_name))
					$errors['client_contact_person_name']		=	'Pole wymagane';
					
				//telefon	
				if(empty($client_contact_person_telephone))
					$errors['client_contact_person_telephone']	=	'Pole wymagane';
					
				//email
				if(empty($client_contact_person_email))
					$errors['client_contact_person_email']		=	'Pole wymagane';
					
				elseif(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $client_contact_person_email))
					$errors['client_contact_person_email']		=	'Nieprawidłowy adres email';
					
				//website
				if(empty($client_contact_person_website))
					$errors['client_contact_person_website']	=	'Pole wymagane';		

					$errors 		    = null;
					$values                       = null;
					
					$client_name						= strip_tags(trim($_POST['client_name']));
					$client_contact_person_name			= strip_tags(trim($_POST['client_contact_person_name']));
					$client_contact_person_telephone	= strip_tags(trim($_POST['client_contact_person_telephone']));	
					$client_contact_person_email		= strip_tags(trim($_POST['client_contact_person_email']));
					$client_contact_person_website		= strip_tags(trim($_POST['client_contact_person_website'])); 
					$notes                                                                                      = strip_tags(trim($_POST['notes']));
					
					$values['client_name'] 						= ($client_name);
					$values['client_contact_person_name'] 		= ($client_contact_person_name);
					$values['client_contact_person_telephone'] 	= ($client_contact_person_telephone);
					$values['client_contact_person_email'] 		= ($client_contact_person_email);
					$values['client_contact_person_website'] 	= ($client_contact_person_website);
					$values['notes'] 							= ($notes);
					
					//>>walidacja
					
					//nazwa klienta
					if(empty($client_name))
						$errors['client_name']						=	'Pole wymagane';
						
					//osoba kontaktowa	
					if(empty($client_contact_person_name))
						$errors['client_contact_person_name']		=	'Pole wymagane';
						
					//telefon	
					if(empty($client_contact_person_telephone))
						$errors['client_contact_person_telephone']	=	'Pole wymagane';
						
					//email
					if(empty($client_contact_person_email))
						$errors['client_contact_person_email']		=	'Pole wymagane';
						
					elseif(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $client_contact_person_email))
						$errors['client_contact_person_email']		=	'Nieprawidłowy adres email';
						
					//website
					if(empty($client_contact_person_website))
						$errors['client_contact_person_website']	=	'Pole wymagane';														

							
					if($errors == null)
					{

                        //TICKET JEST WYSYŁANY NA KONTO LOSOWEGO AKTYWNEGO PRACOWNIKA, JESLI BRAK - WYSYŁAJ DO MASTERA

                        $this->load->model('ticket','',TRUE);
						$afiliant_id 		= $this->session->userdata['id'];
						$afiliant_account 	= $this->baza->get_afiliant_account($afiliant_id);

                        $recipient_account  = null; //konto odbiorcy
                        $recipient          = null; //dane obiorcy

                        $active_employees        = $this->baza->get_active_employees();
                        //$active_employee_accounts = $this->baza->get_active_employee_accounts();
                        foreach($active_employees as $k=>$v)
                            $active_employees[$k]['account'] = $this->baza->get_super_admin_account($v['id']);

                        if(is_array($active_employees) && count($active_employees) > 0)
                        {
                            shuffle($active_employees);
                            $recipient_account  = $active_employees[0]['account'];
                            $recipient          = $active_employees[0];
                        }

                        if(empty($recipient_account['id']))
                        {
                            $masters			= $this->baza->get_all_masters();
                            $master 			= $masters[0];
                            $master_account		= $this->baza->get_super_admin_account($master['id']);

                            $recipient_account  = $master_account;
                            $recipient          = $master;
                        }


                        $temat 		= 'Zgłoszenie klienta';
						$wiadomosc 	= 'Klient: '.$client_name;
						$wiadomosc .= '<br/>Osoba kontaktowa: '.$client_contact_person_name;
						$wiadomosc .= '<br/>Telefon: '.$client_contact_person_telephone;
						$wiadomosc .= '<br/>Email: '.$client_contact_person_email;
						$wiadomosc .= '<br/>Strona www: '.$client_contact_person_website;
						$wiadomosc .= '<br/>Uwagi: '.$notes;
						
						if($afiliant_account['id'] && $recipient_account['id'])
						{ 
							$ticket_id 			= $this->ticket->add($afiliant_account['id'],$recipient_account['id'],3,1,2,$temat,$wiadomosc,null,0);
							$ticket_status 	  	= $this->ticket->get_status_name_by_id(1);
							$ticket_kategoria 	= 3;
							$do				  	= $recipient['email'];
							$user_type     	  	= $this->ticket->get_user_type_by_account_id($recipient_account['id']);

							if($ticket_id)
							{
								$this->ticket->send_email($ticket_id,$ticket_status,$ticket_kategoria,$do,$user_type);
								$dane['info']      	= 'Formularz został wysłany.';
								$errors 			= null;
								$values     		= null;														
							}
							else
								$dane['info'] = 'Wystapił błąd. Formularz nie został wysłany.';							
						}
						else
							$dane['info'] = 'Wystapił błąd. Formularz nie został wysłany.';
		
					}
					$dane['values'] = $values;
					$dane['errors']	= $errors;	
			}
			
		$data['content']  = $this->load->view('/afiliant/new_client',$dane,true);
		$this->load->view('/layout/default',$data);			
	}
	function profit_from_clients($type,$okres=1,$rok=2007)
	{
		$data['user']  = $this->session->userdata('login');
		$prowizja = $this->baza->get_prowizje($this->session->userdata['id']);

		$clients['prowizja'] = $prowizja[0]['procent'];
		
		if($type==1)
		{ //tygodniowe
			if($this->uri->segment(4)!=null)
			{				
				$clients['clients'] = $this->baza->get_affiliant_users_tydzien($this->session->userdata['id'],$okres,$rok);	
			}			
		}
		elseif($type==2)
		{//miesieczne
			if($this->uri->segment(4)!=null)
			{				
				$clients['clients'] = $this->baza->get_affiliant_users_miesiac($this->session->userdata['id'],$okres,$rok);	
			}	
		}
		elseif($type==3)
		{//roczne
			$clients['clients'] = $this->baza->get_affiliant_users_rok($this->session->userdata['id'],$rok);
		}
		
		$clients['type'] = $type;
						
		$data['content']  = $this->load->view('/afiliant/clients_table',$clients,true);
		$this->load->view('/layout/default',$data);	
	}
		
	
	function add_user_to_afiliant()
	{
		$data['user']  = $this->session->userdata('login');
		
		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)	
			{
				
				$data_afiliant['afilianci'] = $this->baza->superadmin_all_afiliants();
				$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)
	{
		$data['user']  = $this->session->userdata('login');
		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_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)
	{
		$data['user']  = $this->session->userdata('login');
		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)
	{
		$data['user']  = $this->session->userdata('login');
		
		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=null)
	{	
		$data['user']  = $this->session->userdata('login');	
		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)
	{
		$data['user']  = $this->session->userdata('login');
		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()
	{
		$data['user']  = $this->session->userdata('login');
		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['domains'] = $this->baza->superadmin_get_domains($user_data[0]['name'], $this->session->userdata['di_sa']);				
				$this->config->load('google_regions');
				$data['regions'] = $this->config->item('google_regions');
				$this->load->view('/layout/domain_page',$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['keywords'] = $this->baza->get_domain($id);
					$data['pozycja'] = $this->baza->get_domain_key_position($id);
					$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)
	{
		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['keywords'] = $this->baza->get_keyword_position($id);
					//$domain_name = $this->baza->superadmin_get_doamin_name($id);	
					$data['domain_id']=$id;						
					$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;						
				$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";
									if($this->uri->segment('1')=='superadmin') 
										$link = 'superadmin';
									else		
										$link = 'admin'; 
										
									$data['name_of_type'] = "Dzienne"; 
									$prefs = array (
           					    					'show_next_prev'  => TRUE,
               										'next_prev_url'   => '/'.$link.'/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}';
											
								   $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->afiliant_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->afiliant_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)
				{
					$this->load->view('/layout/change_pass_page',$data);
				}
				else
				{		
					if($new_pass!=null)
					{
						$haslo = md5($new_pass);
	
						if($this->baza->superadmin_user_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('/afiliant', 'location');
	}
	
	function forgotten_pass()
	{
		$this->load->helper(array('form', 'url'));
		$this->load->library('validation');
        $this->load->library('wyslij_email');
		$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)
		{
			$data['content'] = $this->load->view('new_pass',null,true);
		}
		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->afiliant_get_email($email);
				
				if($is_user!=null)
				{
					if($this->baza->afiliant_new_pass($email,$haslo))
					{	
						$tresc = 'Twoje nowe hasło to:<br /><br />
									'.$pass.'<br /><br />
									<a href="http://panel.networds.pl/afiliant" >Zaloguj się</a>
							';	
							
							if($this->wyslij_email->send_mail('Przypomnienie hasła', $tresc, $is_user[0]['email']))
							{
								$data['content'] = $this->load->view('new_pass_created',null,true);
							}	
					}else $data['content'] = $this->load->view('blad');
				}else	$data['content'] = $this->load->view('blad');
			}else $data['content'] = $this->load->view('blad');                    
		}
        $this->load->view('/layout/forgotten_pass_page',$data);
	}
	
	function email_check($str)
	{
		$user=$this->baza->afiliant_user($str);
		
		if ($user==null or $str==null)
		{
				$this->validation->set_message('email_check', 'Błędny e-mail');
				return FALSE;
		}
		else
		{
				return TRUE;
		}
	}
	
	function activate($param)
	{
		try
		{
			if($this->baza->activate_afiliant($param))
			{
                $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);
                
				$data['info']           = 'Twoje konto zostało aktywowane.';
                $data['form_action']    = '/afiliant';
				$this->load->view('/layout/home',$data);
			}
			else
				redirect('/','location');	
		} catch (Exception $e)
		{
			redirect('/','location');
		}
	}
}
?>