<?php

/**
 * Main Class
 * @author franzz
 * @version 0.1
 */
class Pedidor extends Main
{
	//SQL tables
	const USER_TABLE = 'users';
	const MATL_TABLE = 'materials';
	const MA_TY_TABLE = 'mat_types';
	const ORDER_TABLE = 'orders';
	
	//SQL commands
	const INSERT = 'insert';
	const UPDATE = 'update';
	const DELETE = 'delete';
	
	private $oAuth;	
	
	public function __construct($oClassManagement, $sProcessPage)
	{
		//Load classes
		$oClassManagement->incClass('auth', true);
		
		parent::__construct($oClassManagement, $sProcessPage);
		
		//Init objects
		$this->oAuth = new Auth($this->oMySql, Settings::API_KEY);
	}
	
	protected function install()
	{
		$this->oAuth = new Auth($this->oMySql, Settings::API_KEY, false);
		
		//Install DB
		$this->oMySql->install();
		
		//Add user
		$this->addUser('clara');
		$this->addUser('franzz');
		$this->addUser('micro');
		
		//Add products
		$this->uploadProducts();
	}
	
	/* Authorizations handling */
	
	public function isLoggedIn()
	{
		return $this->oAuth->isLoggedIn();
	}
	
	public function logMeIn($sToken)
	{
		return $this->oAuth->logMeIn($sToken);
	}
	
	public function checkApiKey($sApiKey)
	{
		return $this->oAuth->checkApiKey($sApiKey);
	}
	
	/* Building main pages */
	
	public function getPage($bLoggedIn)
	{
		//Constants
		$asPages = array_values($this->asMasks);
		unset($asPages['index']);
		foreach($asPages as $sPage) $asGlobalVars['consts']['pages'][$sPage] = $this->getPageContent($sPage);
		$asGlobalVars['consts']['page_to_hash'] = array('logon'=>'connectarse', 'add_order'=>'crear_pedido', 'orders'=>'pedidos', 'products'=>'productos');
		$asGlobalVars['consts']['hash_to_page'] = array_flip($asGlobalVars['consts']['page_to_hash']);
		$asGlobalVars['consts']['token_sep'] = Auth::TOKEN_SEP;
		$asGlobalVars['consts']['error'] = self::ERROR;
		$asGlobalVars['consts']['success'] = self::SUCCESS;
		$asGlobalVars['consts']['context'] = $this->asContext;
		$asGlobalVars['consts']['process_page'] = $this->asContext['process_page'];
		$asGlobalVars['consts']['rest'] = array('insert'=>self::INSERT, 'update'=>self::UPDATE, 'remove'=>self::DELETE);

		$asGlobalVars['vars']['id'] = $this->oAuth->getUserId();
		$asGlobalVars['vars']['log_in'] = $bLoggedIn;

		//Main Page
		$sPage = $this->getPageContent('index');
		$sPage = str_replace('asGlobalVars', json_encode($asGlobalVars), $sPage);
		return $sPage;
	}
	
	/* DB structure. See MySqlManager::__construct */
	
	protected function getSqlOptions()
	{
		return array
		(
			'tables' 			=>	array
									(
										self::USER_TABLE	=> array(MySqlManager::getText(self::USER_TABLE), 'first_name', 'last_name', 'email', 'pass', 'cookie', 'active', 'clearance'),
										self::MATL_TABLE	=> array('z_code', MySqlManager::getText(self::MATL_TABLE), MySqlManager::getId(self::MA_TY_TABLE), 'price', 'format', 'active'),
										self::MA_TY_TABLE	=> array(MySqlManager::getText(self::MA_TY_TABLE), 'active')
									),
			'types' 			=>	array
									(
										MySqlManager::getText(self::USER_TABLE)		=> "varchar(30) NOT NULL",
										'first_name'								=> "varchar(20) NOT NULL",
										'last_name'									=> "varchar(20) NOT NULL",
										'email'										=> "varchar(100) NOT NULL",
										'pass'										=> "varchar(255) NOT NULL",
										'cookie'								=> "varchar(255) NOT NULL",
										'active'									=> "tinyint(1) DEFAULT ".Auth::MEMBER_ACTIVE,
										'clearance'									=> "int(1) DEFAULT ".Auth::CLEARANCE_MEMBER,
										'z_code'									=> "varchar(20)",
										MySqlManager::getText(self::MATL_TABLE)		=> "varchar(200) NOT NULL",
										MySqlManager::getText(self::MA_TY_TABLE)	=> "varchar(200) NOT NULL",
										'price'										=> "DECIMAL(10, 2)",
										'active'									=> "BOOLEAN",
										'format'									=> "tinyint(10)"
									),
			'constraints'		=>	array
									(
										self::USER_TABLE => "UNIQUE KEY `user_user` (`".MySqlManager::getText(self::USER_TABLE)."`, `last_name`)"
										//self::MATL_TABLE => "UNIQUE KEY `uni_zeta` (`z_code`)",
									)/*,
			'cascading_delete'	=>	array
									(
										self::USER_TABLE=>array(self::SETTINGS_TABLE)
									)*/
		);
	}
	
	/* Pedidor public functions */

	public function getProducts($iMatId=0, $bInternal=false, $bActiveFilter=true)
	{
		$sMatIdCol = MySqlManager::getId(self::MATL_TABLE);
		$sMatTypeIdCol = MySqlManager::getId(self::MA_TY_TABLE);
		$sMatTypeTextCol = MySqlManager::getText(self::MA_TY_TABLE);
		
		$asContraints = array();
		if($bActiveFilter) $asContraints['active'] = self::ACTIVE;
		$bValidMat = ($iMatId > 0);
		if($bValidMat) $asContraints[$sMatIdCol] = $iMatId;
		
		$asInfo = array('from'		=> self::MATL_TABLE,
						'constraint'=> $asContraints);
		$asProducts = $this->oMySql->selectRows($asInfo);
		$asMatTypes = $this->oMySql->selectRows(array('select'=>array($sMatTypeIdCol.' AS id', $sMatTypeTextCol.' AS text'), 'from'=>self::MA_TY_TABLE, 'constraint'=> array('active'=>self::ACTIVE)));
		foreach($asMatTypes as $asMatType) $asDirectMatTypes[$asMatType['id']] = $asMatType['text'];
		
		$asResult = array();
		foreach($asProducts as $asProduct)
		{
			$asResult[] = array('id'			=> $asProduct[$sMatIdCol],
								'Categoria'		=> $asProduct[$sMatTypeIdCol],
								'Codigo Zeta'	=> $asProduct['z_code'],
								$sMatTypeTextCol=> $asDirectMatTypes[$asProduct[$sMatTypeIdCol]],
								'Producto'		=> self::getTitle($asProduct[MySqlManager::getText(self::MATL_TABLE)]),
								//'safe'			=> self::getSafe($asProduct[MySqlManager::getText(self::MATL_TABLE)]),
								'Precio'		=> $asProduct['price']
			);
		}
		
		return $bInternal?($bValidMat?$asResult[0]:$asResult):self::getJsonResult(true, 'products', array('products'=>$asResult, 'mat_types'=>$asMatTypes));
	}
	
	public function modifyProduct($sActionType, $asProduct)
	{
		$iMatId = $asProduct['id'];
		$iMatTypeId = $asProduct['Categoria'];
		$sZeta = $asProduct['Codigo Zeta'];
		$sMatDesc = $asProduct['Producto'];
		$dPrice = $asProduct['Precio'];
		
		$asResult = array();
		switch($sActionType)
		{
			case self::INSERT:
				$iMatId = $this->insertProduct($sZeta, $sMatDesc, $iMatTypeId, $dPrice);
				break;
			case self::UPDATE:
				$iMatId = $this->oMySql->updateRow(self::MATL_TABLE, $iMatId, array('z_code'=>$sZeta,
																					MySqlManager::getText(self::MATL_TABLE)=>$sMatDesc,
																					MySqlManager::getId(self::MA_TY_TABLE)=>$iMatTypeId,
																					'price'=>$dPrice));
				break;
			case self::DELETE:
				$iMatId = $this->oMySql->updateRow(self::MATL_TABLE, $iMatId, array('active'=>self::INACTIVE));
				break;
		}
		$asResult = $this->getProducts($iMatId, true, false);
		return self::getJsonResult(true, $sActionType.' product', $asResult);
	}
	
	public function downloadProducts()
	{
		$this->oClassManagement->incClass('phpexcel', true);
		$asProducts = $this->getProducts(0, true);
		
		//Filter columns
		foreach($asProducts as $iRow=>$asProduct)
		{
			foreach($asProduct as $sFieldName=>$sFieldValue)
			{
				$sFirstChar = mb_substr($sFieldName, 0, 1);
				if(mb_strtoupper($sFirstChar) == $sFirstChar) //Capital Letter = Interface column
				{
					if($iRow == 0) $asTitles[] = $sFieldName;
					if($sFieldName == 'Categoria') $sFieldValue = $asProduct['mat_type']; //replacing MD
					if($sFieldName == 'Precio') $sFieldValue = str_replace('.', ',', $sFieldValue);
					$asFilteredProducts[$iRow][] = $sFieldValue;
				}
			}
		}
		
		//Add titles
		array_unshift($asFilteredProducts, $asTitles);
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
	
		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Pedidor")
									->setLastModifiedBy("Pedidor")
									->setTitle("Productos")
									->setSubject("Productos")
									->setDescription("Lista de productos (micro)")
									->setKeywords("micro lista productos")
									->setCategory("productos");
	
		$objPHPExcel->setActiveSheetIndex(0);
		foreach($asFilteredProducts as $iRow=>$asProduct)
		{
			foreach($asProduct as $iCol=>$sValue)
			{
				$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($iCol, $iRow+1, $sValue);
				$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn($iCol)->setAutoSize(true);
			}
		}
		
		// Rename worksheet
		$objPHPExcel->getActiveSheet()->setTitle('Productos');
	
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
	
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="productos.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
	
		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
	
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit;
	}
	
	/* Pedidor private functions */
	
	private function addUser($sNickName, $bLogMeIn=false)
	{
		return $this->oAuth->addUser($sNickName, $sNickName);
	}
	
	private  function uploadProducts()
	{
		$sZetasFileName = 'files/zetas.csv';
		
		$asZetas = explode("\n", Toolbox::fixEOL(file_get_contents($sZetasFileName)));
		foreach($asZetas as $sLine)
		{
			$asZeta = explode(';', $sLine);
			$sZeta = $asZeta[0];
			$sTypeDesc = $asZeta[1];
			$sDesc = $asZeta[2];
			
			$asMatType = array(	MySqlManager::getText(self::MA_TY_TABLE)=>$sTypeDesc,
								'active'=>self::ACTIVE);
			$iMatTypeId = $this->oMySql->insertUpdateRow(self::MA_TY_TABLE, $asMatType, array(MySqlManager::getText(self::MA_TY_TABLE)), false);
				
			$this->insertProduct($sZeta, $sDesc, $iMatTypeId);
		}
		
	}
	
	private function insertProduct($sZeta, $sMatDesc, $iMatTypeId, $dPrice=0.01)
	{
		$asMaterial = array('z_code'=>$sZeta,
							MySqlManager::getText(self::MATL_TABLE)=>$sMatDesc,
							MySqlManager::getId(self::MA_TY_TABLE)=>$iMatTypeId,
							'price'=>$dPrice,
							'active'=>self::ACTIVE);
		return $this->oMySql->insertRow(Pedidor::MATL_TABLE, $asMaterial);
	}
	
	/* Static toolbox functions */

	public static function getSafe($sText)
	{
		return mb_strtolower(Toolbox::remove_accents($sText));
	}
	
	public Static function getTitle($sTitle)
	{
		return Toolbox::mb_ucfirst($sTitle);
	}
	
	
	
	
	
	
	
	
	
	
}

?>