<?php 
class ControllerMyAffiliate extends Controller { 

	function index() {
		ini_set("display_errors", "On");
error_reporting(1);

		$customer =& $this->locator->get('customer'); 
		$module   =& $this->locator->get('module');
		$response =& $this->locator->get('response');
		$session  =& $this->locator->get('session');
		$template =& $this->locator->get('template');
		$view = $this->locator->create('template');
		$url      =& $this->locator->get('url');
		$database =& $this->locator->get('database');
		$request  =& $this->locator->get('request');
		$language =& $this->locator->get('language');
//		$language->load('controller/my_affiliate.php');
		
		if (!$customer->isLogged()) {
	  		$session->set('redirect', $url->ssl('affiliate'));
	  		$response->redirect($url->ssl('account_login'));
    	}

    	if($request->has('page')){
		   $page=$request->get('page');
		}else{
			$page = 1;
		}    
		
		$email = $customer->getEmail();
		$customer_id = $customer->getId();
	
		$customer_info = $database->getRow("select invitation_code, email from customer where customer_id = $customer_id");
		if(!empty($customer_info['invitation_code']))
		{
			$database->query("update customer set invitation_code = '".md5('invite'.$customer_info['email'])."' where customer_id =$customer_id");
		}
		$token = $database->getRow("select invitation_code from customer where customer_id = $customer_id");
		
		$view->set('token', $token['invitation_code']);
		
		$sql = "select * from affiliate where customer_id = $customer_id";
		$customer_invites = $database->getRows($database->splitQuery($sql, $page, 2));
		$page_data = array();
	    for ($i = 1; $i <= $database->getPages(); $i++) {
				$page_data[] = array(
	  				'text'  => $language->get('text_pages', $i, $database->getPages()),
	  				'value' => $i
				);
	      	}
	    $view->set('pages', $page_data);  	      	        		
  		$view->set('page', $page);	
  		$view->set('text_results', $language->get('text_results',$page, $database->getPages()));		
  		$view->set('action', $url->href('my_affiliate'));
  		
		foreach ($customer_invites as $key=>$invite){
				$invite_customer_info = $database->getRow('select firstname,lastname from customer where customer_id ='.$invite['invite_customer_id']);
				$customer_invites[$key]['name'] = $invite_customer_info['lastname'].' '.$invite_customer_info['firstname'];
			}
		$view->set('customer_invites', $customer_invites);					
  				
		$template->set('content', $view->fetch('content/my_affiliate.tpl'));
		$template->set($module->fetchAccount());	
    	$response->set($template->fetch('layout.tpl')); 
	}
}
?>