<?php

class AccountController extends Zend_Controller_Action {

	public function init() {			
	}
	
	
	public function loginAction() {		
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');	
		$v = $this->_request->getParams();	
		$basket = new Zend_Session_Namespace('basket');
		$order = new Zend_Session_Namespace('order');
		
		if( $client->client_auth == true ){
			$this->_helper->redirector('index','index');
		}
		
		if( $information->errorLogin ){
			$this->view->errorLogin = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->activation ){
			$this->view->activation = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		
		if( isset($v['client_login']) && isset($v['client_pass']) ){

			$Client = new Client();
			$select = $Client->select();		
			$select->where('client_login = ?', $v['client_login']);	
			$select->where('client_pass = ?', hash('sha256',$v['client_pass']));		
		/*	$select->where('client_activ = ?', 1);	*/
			
			$row = $Client->fetchRow($select);		
						
			if( isset($row) ){
				// zalogowany
				$client->time = time();	
				$client->client_auth = true;
				$client->client_login = $v['client_login'];
				$client->client_id = $row['client_id'];	
				$client->client_firstname = $row['client_firstname'];
				$client->client_secondname = $row['client_secondname'];		
				
				$Client = new Client();

				$data = array(					
					'client_lastlog' => Lib_Date::datetime()
				);
				$Client->update( $data , 'client_id='.$client->client_id);

				
				
				
				if( count($order->product) > 0 ){
				
					$data = array(					
						'client_basket' => json_encode($basket->product),
						'client_order' => json_encode($order->product)
					);
					$Client->update( $data , 'client_id='.$client->client_id);
			
				}else{
				
					Zend_Session::namespaceUnset('basket');
					Zend_Session::namespaceUnset('order');
					$basket = new Zend_Session_Namespace('basket');
					$order = new Zend_Session_Namespace('order');
					$basket->product = json_decode($row['client_basket'],true);
					$order->product = json_decode($row['client_order'],true);
				
				}
				
				
				
				/*
				var_dump($order->product);
				echo'<hr />';
				var_dump(json_decode($row['client_basket'],true));
				*/
				$HistoryClientLog = new HistoryClientLog();
				$data = array(
					'client_id'      => $client->client_id,
					'history_client_log_date' => date("Y-m-d H:i:s"),
					'history_client_log_ip'      => Zend_Registry::get('users_ip'),
					'history_client_log_host'      => Zend_Registry::get('users_host')
				);
				$HistoryClientLog->insert($data);	
				
				$this->_helper->redirector('index','index');
			}else{
				// blad logowania
				$information->errorLogin = true; 
				$this->_helper->redirector('login','account');	
			}
			
		}
		
		
		
		
	}
	
	
	public function forgotAction() {
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');	
		$v = $this->_request->getParams();	
		if( $client->client_auth == true ){
			$this->_helper->redirector('index','index');
		}	
		
		if( $information->forgot ){
			$this->view->forgot = true;
			Zend_Session::namespaceUnset('information');			
		}
	
		if( isset($v['client_login']) ){	
			$Client = new Client();
			$select = $Client->select();		
			$select->where('client_login = ?', $v['client_login']);					
			$row = $Client->fetchRow($select);
			
			if( isset($row) ){
			    $tabelka = '1234567890qwertyuiopasdfghjkklzxcvbnm';
				$id = '';
				for ($i=0; $i<7; $i++) // 7 to długość ciągu
				{
					$id .= $tabelka[rand()%(strlen($tabelka))];
				}
				$pass = $id;				
				$body = Lib_Lang::translate(mail_forgot_body);						
				$body = str_replace('%PASS%',$pass,$body);
				$s= "=?utf-8?b?".base64_encode(Lib_Lang::translate(mail_forgot_subject))."?=";
				$headers = "MIME-Version: 1.0\r\n";
				$headers.= "From: =?utf-8?b?".base64_encode(MAIL_LOGIN)."?= <".MAIL_LOGIN.">\r\n";
				$headers.= "Content-Type: text/html;charset=utf-8\r\n";
				$headers.= "Reply-To: ".MAIL_LOGIN."\r\n";  
				$headers.= "X-Mailer: PHP/" . phpversion();
				mail($v['client_login'], $s, $body, $headers);
				
				$data = array(
					'client_pass' => hash('sha256',$pass)
				);
				$Client->update( $data , 'client_id='.$row->client_id);
			}
		
			$information->forgot = true; 	
			$this->_helper->redirector('forgot','account');	
		}	
	}
	
	public function registrationAction() {	
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');		
		$v = $this->_request->getParams();
		if( $client->client_auth == true ){
			$this->_helper->redirector('index','index');
		}		

		
		if( $information->errorNo ){
			$this->view->errorNo = true;
			Zend_Session::namespaceUnset('information');			
		}

	
		
		if( isset($v['client_registration']) ){		
				
			$Client = new Client();

			$err = 0;
			
			/* sprawdzanie czy login istnieje w bazie danych */		
			$select = $Client->select();		
			$select->where('client_login = ?', $v['client_login']);					
			$row = $Client->fetchRow($select);
			if( isset($row) ){
				$err++;
				$this->view->errorLogin = true;
			}
			/* sprawdzanie czy login istnieje w bazie danych - koniec */	

			/* sprawdzanie czy hasla sa identyczne */	
			if( $v['client_pass'] != $v['client_pass_rep'] ){
				$err++;
				$this->view->errorPassword = true;
			}
			/* sprawdzanie czy hasla sa identyczne - koniec */
			
				
			/* sprawdzanie czy podano prawidlowe adresy email */	
			$emailValid = new Zend_Validate();
			$emailValid->addValidator( new Zend_Validate_EmailAddress() );

			if( !$emailValid->isValid( $v['client_login'] ) ){ 
				$err++;
				$this->view->errorEmailLogin = true; 
			}	
			/* sprawdzanie czy podano prawidlowe adresy email - koniec */
		
			if( $err == 0 ){
				$hashgen = hash('sha256',time().rand(10000,99999).$v['client_login']);
				$data = array(
					'client_login' => $v['client_login'],
					'client_pass' => hash('sha256',$v['client_pass']),
					'client_company' => isset($v['client_company'])?$v['client_company']:'',
					'client_nip' => isset($v['client_nip'])?$v['client_nip']:'',
					'client_type' => isset($v['client_type'])?$v['client_type']:0,
					'client_firstname' => $v['client_firstname'],
					'client_secondname' => $v['client_secondname'],
					'client_address' => $v['client_address'],
					'client_zipcode' => $v['client_zipcode'],
					'client_city' => $v['client_city'],
					'client_country' => $v['client_country'],
					'client_phone' => $v['client_phone'],
					
					'client_shipment' => isset($v['client_shipment'])?$v['client_shipment']:0,
					'client_shipment_name' => isset($v['client_shipment_name'])?$v['client_shipment_name']:'',
					'client_shipment_address' => isset($v['client_shipment_address'])?$v['client_shipment_address']:'',
					'client_shipment_zipcode' => isset($v['client_shipment_zipcode'])?$v['client_shipment_zipcode']:'',
					'client_shipment_city' => isset($v['client_shipment_city'])?$v['client_shipment_city']:'',
					'client_shipment_country' => isset($v['client_shipment_country'])?$v['client_shipment_country']:'',
					
					'client_ins' => Lib_Date::datetime(),
					'client_edit' => Lib_Date::datetime(),
					'client_code' => $hashgen
				);
				$Client->insert($data);
				
				
			
			
			/*
				$mail = new PHPMailer();
				$mail->SMTPSecure = 'tls';
				$mail->CharSet = 'UTF-8';
				$mail->IsHTML(true);				
				
				$mail->From = MAIL_EMAIL;
				$mail->FromName = MAIL_EMAILNAME;
				$mail->AddReplyTo(MAIL_EMAIL, MAIL_EMAILNAME); 				
				$mail->Host = MAIL_HOST; 
				$mail->Mailer = "smtp";  
				$mail->IsSMTP();
				$mail->SMTPAuth = true; 
				$mail->SMTPKeepAlive = true;
				$mail->Username = MAIL_LOGIN; 
				$mail->Password = MAIL_PASS;
				$mail->Port = 587;
				
				$mail->Subject = Lib_Lang::translate(mail_registration_subject);
				$body = Lib_Lang::translate(mail_registration_body);				
				$link = WWW_PATH."/account/activation/code/".$hashgen;
				
				$mail->Body = str_replace('%LINK%',$link,$body);   
				$mail->AddAddress ($v['client_login'], $v['client_login']);
								
				if($mail->Send())
				{                      
					die('E-mail został wysłany');
				}            
				else{           
					die('E-mail nie mógł zostać wysłany '. $mail->ErrorInfo);   
				}
			*/
			
			$body = Lib_Lang::translate(mail_registration_body);				
			$link = WWW_PATH."/account/activation/code/".$hashgen;				
			$body = str_replace('%LINK%',$link,$body);
			$s= "=?utf-8?b?".base64_encode(Lib_Lang::translate(mail_registration_subject))."?=";
			$headers = "MIME-Version: 1.0\r\n";
			$headers.= "From: =?utf-8?b?".base64_encode(MAIL_LOGIN)."?= <".MAIL_LOGIN.">\r\n";
			$headers.= "Content-Type: text/html;charset=utf-8\r\n";
			$headers.= "Reply-To: ".MAIL_LOGIN."\r\n";  
			$headers.= "X-Mailer: PHP/" . phpversion();
			mail($v['client_login'], $s, $body, $headers);

	
				$information->errorNo = true; 
				$this->_helper->redirector('registration','account');	
			}
		
		}

		
	}
	
	
	public function infoAction() {	
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');		
		$v = $this->_request->getParams();
		if( $client->client_auth != true ){
			$this->_helper->redirector('login','account');
		}		

		
		if( $information->client_registration ){
			$this->view->client_registration = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->client_registration_cp ){
			$this->view->client_registration_cp = true;
			Zend_Session::namespaceUnset('information');			
		}
		
		if( $information->add_opinion ){
			$this->view->add_opinion = true;
			Zend_Session::namespaceUnset('information');			
		}
	
		
		if( isset($v['client_registration']) ){		
				
			$Client = new Client();

				$data = array(
					'client_company' => isset($v['client_company'])?$v['client_company']:'',
					'client_nip' => isset($v['client_nip'])?$v['client_nip']:'',
					'client_firstname' => $v['client_firstname'],
					'client_secondname' => $v['client_secondname'],
					'client_address' => $v['client_address'],
					'client_zipcode' => $v['client_zipcode'],
					'client_city' => $v['client_city'],
					'client_country' => $v['client_country'],
					'client_phone' => $v['client_phone'],					
					
					'client_shipment' => isset($v['client_shipment'])?$v['client_shipment']:0,
					'client_shipment_name' => isset($v['client_shipment_name'])?$v['client_shipment_name']:'',
					'client_shipment_address' => isset($v['client_shipment_address'])?$v['client_shipment_address']:'',
					'client_shipment_zipcode' => isset($v['client_shipment_zipcode'])?$v['client_shipment_zipcode']:'',
					'client_shipment_city' => isset($v['client_shipment_city'])?$v['client_shipment_city']:'',
					'client_shipment_country' => isset($v['client_shipment_country'])?$v['client_shipment_country']:'',
					
					'client_edit' => Lib_Date::datetime()
				);
				$Client->update( $data , 'client_id='.$client->client_id);
				
				$information->client_registration = true; 
				$this->_helper->redirector('info','account');	
			
		
		}

	
		
		if( isset($v['client_registration_cp']) ){		
				
			$Client = new Client();

				$data = array(
					'client_pass' => hash('sha256',$v['client_pass']),
					'client_edit' => Lib_Date::datetime()
				);
				$Client->update( $data , 'client_id='.$client->client_id);
				
				$information->client_registration_cp = true; 
				$this->_helper->redirector('info','account');	
			
		
		}

		$Client = new Client();	
		$select = $Client->select();		
		$select->where('client_id = ?', $client->client_id);					
		$row = $Client->fetchRow($select);
		$this->view->rowClient = $row;
	}
	
	
	public function addopinionAction() {	
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');		
		$v = $this->_request->getParams();
		if( $client->client_auth != true ){
			$this->_helper->redirector('login','account');
		}		
	
		
		if( isset($v['add_opinion']) ){		
				
			$Opinion = new Opinion();
			

			$data = array(
				'client_id' => $client->client_id,
				'opinion_type' => $v['opinion_type'],
				'opinion_contents' => $v['opinion_contents'],
				'opinion_signature' => $v['opinion_signature'],								
				'opinion_ins' => Lib_Date::datetime()
			);
			$Opinion->insert( $data );
			
			
			$information->add_opinion = true; 
			$this->_helper->redirector('info','account');	
		
		}


		$Client = new Client();	
		$select = $Client->select();		
		$select->where('client_id = ?', $client->client_id);					
		$row = $Client->fetchRow($select);
		$this->view->rowClient = $row;
		
		$id = 52;		
		$Content = new Content();
		$select = $Content->select();		
		$select->where('content_id = ?', $id);	
		$row = $Content->fetchRow($select);			
		$this->view->rowContent = $row;
	}
	
	
	public function historyorderAction() {	
		$db = Zend_Registry::get('db');
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');		
		$v = $this->_request->getParams();
		if( $client->client_auth != true ){
			$this->_helper->redirector('login','account');
		}		

		$limit = 10;
		$limitpage = 10;

		$page = $this->_request->getParams();
		if( isset($page['page']) ) $page = $page['page'];
		else $page = 1;
			
		$Order = new Order();	
		
		
		
			
		$select = $db->select();
		$select->from('order')->join('client', 'client.client_id = order.client_id');		
		$select->where('client.client_id = ?', $client->client_id);	
		$select->order(array('order_ins DESC'));//->limit($limit,$p);
		$stmt = $db->query($select);
		$dataCount = count($stmt->fetchAll()); 
			
		$p = ($page-1)*$limit;	
			
		$select = $db->select();
		$select->from('order')->join('client', 'client.client_id = order.client_id');		
		$select->where('client.client_id = ?', $client->client_id);		
		$select->order(array('order_ins DESC'))->limit($limit,$p);
		$stmt = $db->query($select);
		$data = $stmt->fetchAll();
		//$data = $Order->fetchAll(null , 'order_ins DESC', $limit,$p); 		
		$this->view->dataTable = $data;		
	
		$Lib_Page = new Lib_Page();
		$Lib_Page->setLimit( $limit );
		$Lib_Page->setLimitPage( $limitpage );
		$Lib_Page->setMax( $dataCount );
		$Lib_Page->setActualId( $page );
		$Lib_Page->setController('account');
		$Lib_Page->setAction('historyorder');
		$Lib_Page->setPrefix('page');
		$this->view->str = $Lib_Page->result();
		$this->view->page = ($page-1)*$limit;
		
		
	}
	
	
        public function payAction()
        {
            $db = Zend_Registry::get('db');
            $information = new Zend_Session_Namespace('information');
            $client = new Zend_Session_Namespace('client');		
            $v = $this->_request->getParams();
            if( $client->client_auth != true ){
                    $this->_helper->redirector('login','account');
            }

            $Order = new Order();
            $select = $Order->select();				
            $select->where('order_id = ?', $v['id']);	
            $select->where('client_id = ?', $client->client_id);
            $row = $Order->fetchRow($select);	

            if(!$row)
            {
                $this->_helper->redirector('login','account');
            }
            
            $amount             = $row->order_price*100;
            $order_id           = $v['id'];
            $ts                 = time();
            $desc               = "Zamowienie numer ".$order_id;
            $los                = rand(1000,10000);			
            $hash               = hash('sha256', $los.'payu'.date('G:i:s.Y-M-d'));
            $this->view->ts     = $ts;
            $this->view->sig    = md5(PAY_pos_id.$hash.PAY_pos_auth_key.$amount.$desc.$order_id.$_SERVER['REMOTE_ADDR'].$ts.PAY_key);
            $this->view->client_ip = $_SERVER['REMOTE_ADDR'];
            $this->view->desc   = $desc;
            $this->view->amount     = $amount;
            $this->view->session_id = $hash;
            $this->view->order_id   = $order_id;
            
            
            $this->view->rowOrder = $row;
        }
        
	public function orderAction() {	
		$db = Zend_Registry::get('db');
		$information = new Zend_Session_Namespace('information');
		$client = new Zend_Session_Namespace('client');	
		
		$v = $this->_request->getParams();
		if( $client->client_auth != true ){
			$this->_helper->redirector('login','account');
		}	
		
		$Order = new Order();
		$Client = new Client();		
		
		$v = $this->_request->getParams();
		
		$select = $Order->select();		
		$select->where('order_id = ?', $v['id']);	
		$select->where('client_id = ?', $client->client_id);	
		$row = $Order->fetchRow($select);
		$this->view->rowOrder = $row;
		
			
		$select = $db->select();
		$select->from('order_product')->join('order', 'order.order_id = order_product.order_id')->join('product', 'product.product_id = order_product.product_id');				
		$select->where('order.client_id = ?', $client->client_id);		
		$select->where('order_product.order_id = '.$v['id']);//->limit($limit,$p);
		$select->order(array('order_product_id DESC'));//->limit($limit,$p);
		$stmt = $db->query($select);
		$data = $stmt->fetchAll(); 
		$this->view->dataProductOrder = $data;	
		
		$select = $db->select();
		$select->from('order_file');		
		$select->where('order_file.order_id = '.$v['id']);//->limit($limit,$p);
		$select->order(array('order_file_id DESC'));//->limit($limit,$p);
		$stmt = $db->query($select);
		$data = $stmt->fetchAll(); 
		$this->view->dataOrderFile = $data;	
		
		$select = $Client->select();		
		$select->where('client_id = ?', $client->client_id);	
		$row1 = $Client->fetchRow($select);
		$this->view->rowClient = $row1;	
	
		if( !$row OR !$row1 ){		
			$this->_helper->redirector('index','index');	
		}
	}
	
	public function orderfileopenAction(){
		$client = new Zend_Session_Namespace('client');	
		$v = $this->_request->getParams();
		$information = new Zend_Session_Namespace('information');
		
		$OrderFile = new OrderFile();
		$select = $OrderFile->select();
		$select->where('order_file_id = ?', $v['id']);	
		$row = $OrderFile->fetchRow($select);
		
		$Order = new Order();
		$select = $Order->select();		
		$select->where('order_id = ?', $row['order_id']);	
		$select->where('client_id = ?', $client->client_id);	
		$rowOrder = $Order->fetchRow($select);
		
		if( !isset($rowOrder) ){
			$this->_helper->redirector('index','index');	
		}
		
		if ( isset($row->order_file_file) ) { 			
		
			$file = 'orderfile/'.$row->order_file_file;
			header('Content-Type: '.$row->order_file_filetype);
			header('Content-Disposition: inline; filename="'.$row->order_file_filename.'"');
			header('Content-Length: '.filesize($file));	
	
			ob_clean();
			flush();
			@readfile($file);
			exit;
		}else{
			$this->_helper->redirector('index','index');			
		}
		
        $this->_helper->viewRenderer->setNoRender();
	}
	
	public function ordereditproductAction() {	
		$db = Zend_Registry::get('db');
		$v = $this->_request->getParams();
		$admin = new Zend_Session_Namespace('admin');
		$information = new Zend_Session_Namespace('information');	
		
		$select = $db->select();
		$select->from('order_product');		
		$select->where('order_product.order_product_id = '.$v['order_product_id']);
		$select->where('order_product.product_id = '.$v['product_id']);
		$stmt = $db->query($select);
		$data = $stmt->fetchAll(); 
		
		$this->view->product = $data[0];	
	
	}
	
	
	public function activationAction() {
		$information = new Zend_Session_Namespace('information');	
		$v = $this->_request->getParams();				
			
		$Client = new Client();
		$data = array(
			'client_activ' => 1
		);
		$Client->update( $data, "client_code LIKE '".$v['code']."'" );
	
		$information->activation = true; 
		$this->_helper->redirector('login','account');	
		$this->_helper->viewRenderer->setNoRender();
	}
	
	
	public function logoutAction() {	
		$client = new Zend_Session_Namespace('client');	
		Zend_Session::namespaceUnset('client');
		$this->_helper->redirector('login','account');		
	}

	
	
	public function checkloginAction() {
		header("Content-Type:text/plain");
		$this->_helper->viewRenderer->setNoRender();
		$v = $this->_request->getParams();
		$valid = 0;
		// $valid = 0 - nie istnieje w bazie
		// $valid = 1 - istnieje w bazie
		
		$Client = new Client();	
		$select = $Client->select();		
		$select->where('client_login = ?', $v['client_login']);					
		$row = $Client->fetchRow($select);
		unset($Client);		

		if( isset($row) ) $valid = 1;
		else $valid = 0;
			
		echo $valid;
	}
	
}
