<?php

class security_functions
{	
	var $conn;
	var $lang;
	var $auth_path_pages_array = array (
		array("customers","manage_customers","customers_barcode","manage_type","cat_cust"),
		array("items","manage_items","items_barcode","categories/manage_categories"),
		array("reports","escoge_fecha_maestro"),
		array("buys","po_ui","manage_po","buy_ui","manage_buys","escoge_fecha_buyr","traspaso_almacen","suppliers/manage_suppliers"),
		array("sales","sale_ui","manage_cot","manage_fact","manage_salidas","manage_traspasos","liquidaciones","cancelar_doctos","resella"),
		array("settings","manage_branches","../users/manage_users","index_or"));
	var $auth_label_pages_array = array (				//////////////// OBTENER LAS VARIABLES CORRESPONDIENTES DE ESTE PEDO ///////////////////
		array("Clientes","<i class='icon-users'></i> Administar Clientes","<i class='icon-barcode'></i> Hoja de Códigos de Barra de Clientes","<i class='icon-adjust'></i> Administrar giros","<i class='icon-group'></i> Catalogo de Clientes"),
		array("Articulos","<i class='icon-line2-layers'></i> Administrar Artículos","<i class='icon-barcode'></i> Hoja de Códigos de Barra de Artículos","<i class='icon-line-paper'></i> Administar Categorías"),
		array("Reportes","<i class='icon-windows'></i> Reporte Maestro"),
		array("Compras","<i class='icon-display'></i> Generar pedido","<i class='icon-map'></i> Administrar pedidos","<i class='icon-zoom-in2'></i> Agregar compra","<i class='icon-clipboard'></i> Administrar compras","<i class='icon-graph'></i> Historico de compras","<i class='icon-list-alt'></i> Traspaso de almacen","<i class='icon-th-large'></i> Administrar proveedores"),
		array("Ventas","<i class='icon-line-file-add'></i> Crear una Venta Nueva","<i class='icon-bars'></i> Administrar Cotizaciones","<i class='icon-file-settings'></i> Administrar Facturas","<i class='icon-email2'></i> Administrar Salidas","<i class='icon-cube'></i> Administrar Traspasos","<i class='icon-stopwatch'></i> Liquidaciones","<i class='icon-line-square-cross'></i> Cancelar documentos","<i class='icon-line-repeat'></i> Resellar factura"),
		array("Configuración","<i class='icon-truck2'></i> Administrar sucursales","<i class='icon-users'></i> Administrar usuarios","<i class='icon-cog'></i> Configuración del Sistema"));
	var $auth_user_array = array ();

	//defalt constructor which first checks if page is accessable.
	function security_functions($dbf,$page_type,$language)
	{
		//pre: $dbf must be a db_functions object and $page_type must be a string
		//post: denies access to page and stops php processing
		
		//$page_type will be either: Public, Admin, Sales Clerk or Report Viewer.
		//$usertype will be either: Admin, Sales Clerk or Report Viewer.
		//Their must be a session present in order to execute authoization.
		
		//sets class variables.
		$this->conn=$dbf->conn;
		$this->lang=$language;
		
		if(isset($_SESSION['session_user_id']))
		{
			$user_id=$_SESSION['session_user_id'];
			
			$tablename='users';
			$result = mysqli_query($this->conn,"SELECT * FROM $tablename WHERE id=\"$user_id\"");
			$row = mysqli_fetch_assoc($result);
			$usertype= $row['type'];
			
			
			//If the page is not public or the user is not an Admin, investigation must continue.
			if($page_type!='Public' or $usertype != 'SuperAdmin')
			{
				if($usertype!='Admin' and $usertype!='Sales Clerk' and $usertype!='SuperAdmin' and $usertype!='Empleado' and $usertype!='Report Viewer')
				{
					//Makes sure $usertype is not anything but Admin, Sales Clerk, Report Viewer
					echo "|1|{$this->lang->attemptedSecurityBreech}";
					exit();
				}
				elseif($page_type!='Public' and $page_type!='Admin' and $page_type!='Sales Clerk' and $page_type!='SuperAdmin')
				{
					//makes sure $page_type is not anything but Public, Admin, Sales Clerk or Report Viewer.
					echo "|2|{$this->lang->attemptedSecurityBreech}";				
					exit();
				}
				elseif($usertype!='SuperAdmin' and $page_type=='SuperAdmin')
				{
					//if page is only intented for Admins but the user is not an admin, access is denied.
					echo "|3|No tiene autorizaci&oacute;n para ver esta p&aacute;gina";
					exit();
				}
				elseif(($usertype=='Sales Clerk') and $page_type =='Report Viewer')
				{
					//Page is only intented for Report Viewers and Admins.
					echo "|4|{$this->lang->mustBeReportOrAdmin}";
					exit();
				}
				elseif(($usertype=='Report Viewer') and $page_type =='Sales Clerk')
				{
					//Page is only intented for Sales Clerks and Admins.
					echo "|5|{$this->lang->mustBeSalesClerkOrAdmin}";
					exit();
				}
				/*
				elseif($page_type=='Public' and $usertype=='Report Viewer')			//	NEW
				{
					echo "|6|{$this->lang->attemptedSecurityBreech}";
					exit();
				}
				*/
			}
		}
	}
	
	function isLoggedIn()
	{
		//returns boolean based on if user is logged in.
		
		if(isset($_SESSION['session_user_id']))
		{
			$user_id=$_SESSION['session_user_id'];
			$tablename='users';
			$result = mysqli_query($this->conn,"SELECT * FROM $tablename WHERE id=\"$user_id\"");
			$num = @mysqli_num_rows($result);
			if($num > 0)
			{
				$row = mysqli_fetch_assoc($result);
				$auth = $row['type'];
				
				if($auth=="Admin" or $auth=="SuperAdmin") 					// Admin | SuperAdmin
				{ 
					$this->auth_user_array = array (
						array(true, true, true, true, true), 							// customers
						array(true, true, true, true),									// items
						array(true, true),												// reports
						array(true, true, true, true, true, true, true, true),			// buys
						array(true, true, true, true, true, true, true, true, true),	// sales
						array(true, true, true, true));									// settings
				} 
				elseif($auth=="Sales Clerk" or $auth=="Empleado") 			// Sales Clerk | Empleado
				{
				 	$this->auth_user_array = array (
						array(true, true, true, true, true),
						array(true, true, true, true),
						array(false,false),
						array(true, true, true, true, true, true, true, true),
						array(true, true, true, true, true, true, true, true, true),
						array(false,false,false,false));
				} 
				elseif($auth=="Report Viewer") 								// Report Viewer
				{
					$this->auth_user_array = array (
						array(false,false,false,false,false),
						array(false,false,false,false),
						array(true, true),
						array(false,false,false,false,false,false,false,false),
						array(false,false,false,false,false,false,false,false,false),
						array(false,false,false,false));
				} 
				
				return true;
			}
			else
			{
				return false;
			}
		}
		return false;
	}
	
	function checkLogin($username,$password)
	{
		//pre: $username and $password must be strings. ($password is encrypted)
		//post: returns boolean based on if their login was succesfull.
		
		$result = mysqli_query($this->conn,"SELECT * FROM users WHERE username=\"$username\" and password=\"$password\" and status=\"Activo\"");	
		$num = @mysqli_num_rows($result);
		$numa = @mysqli_fetch_assoc($result);
		$resultb = mysqli_query($this->conn,"SELECT * FROM branches WHERE statusb=\"".$numa['branch_id']."\"");
		$numb = @mysqli_fetch_assoc($resultb);
		if($num > 0)// && $numb['statusb'] == 1)
		{
			return true;
		}
		
		return false;
	}

	function checkAuthPath($auth, $page_path)
	{
		$home = "home";
		//echo "<script>console.log('$page_path');</script>";
		
		if (isset($page_path)) // or $page_path != $home)
		{
			//$page_path = $_POST['path_id'];
			$sec_path = explode("/", $page_path);
			$sec_path_root = $sec_path[0];
			for($w = 1; $w < count($sec_path); $w++)
			{
				if($w > 1)
				{
					$sec_path_rest .= "/";
				}
				$sec_path_rest .= $sec_path[$w];
			}
			print_r($auth_user_array);
			echo "<script>console.log('$sec_path_rest');</script>";
			for($h = 0; $h < count($this->$auth_user_array); $h++)
			{
				echo "<script>console.log('$h');</script>";
				for($g = 0; $g < count($this->$auth_user_array[$h]); $g++)
				{
					echo "<script>console.log('".$this->$auth_path_pages_array[$h][0]." === ".$sec_path_root."');</script>";
					if($this->$auth_path_pages_array[$h][0] === $sec_path_root)
					{
						echo "<script>console.log('".$g." > 0 and ".$this->$auth_path_pages_array[$h][$g]." === ".$sec_path_rest." and ".$this->$auth_user_array[$h][$g]."');</script>";
						//echo "<br>".$g." > 0 and ".$this->$auth_path_pages_array[$h][$g]." === ".$sec_path_rest." and ".$this->$auth_user_array[$h][$g];
						if($g > 0 and $this->$auth_path_pages_array[$h][$g] === $sec_path_rest and $this->$auth_user_array[$h][$g])
						{

							return $page_path; 
						}
						/*
						else
						{
							return $home;
						}
						*/
					}
					/*
					else
					{
						return $home;
					}
					*/
				}
			}

			return $page_path; // SOLO PRUEBAS !!
		}
		elseif($auth=="Report Viewer")
		{
			$page_path = "reports/escoge_fecha_maestro";
			return $page_path;
		}
		else 
		{
			$page_path = $home;
			return $page_path;
		}
	}

	function closeSale()
	{
		//deletes sessions vars 
		
		unset($_SESSION['current_sale_customer_id']);
		unset($_SESSION['items_in_sale']);
		unset($_SESSION['current_item_search']);
		unset($_SESSION['current_customer_search']);

	}
	function closeBuy()
	{
		//deletes sessions vars 
		unset($_SESSION['current_sale_supplier_id']);
		unset($_SESSION['items_in_buy']);
		unset($_SESSION['items_in_po']);
		unset($_SESSION['current_item_search']);
		unset($_SESSION['current_customer_search']);
		unset($_SESSION['document_number']);
		unset($_SESSION['date']);
		unset($_SESSION['current_sale_supplier_id']);

	}
	function cleanOnlyOne($action,$pos)
	{
		$items_array_temp = array();
		if(isset($action))
		{
			switch($action)
			{
				case $action=='all':
					$this->closeBuy();
					break;
				case $action=='all_po':
					$this->closeBuy();
					break;
				case $action=='all_sale':
					$this->closeSale();
					break;
				case $action=='item':
					for($k=0;$k<count($_SESSION['items_in_buy']);$k++)
					{
						if($k!=$pos)
						{
							array_push($items_array_temp,$_SESSION['items_in_buy'][$k]);
						}
					}
					if(count($_SESSION['items_in_buy'])==0)
					{
						$this->closeSale();
						break;
					}
					else
					{
						unset($_SESSION['items_in_buy']);
						$_SESSION['items_in_buy']=array_values($items_array_temp);
					}
					break;
				case $action=='item_sale':
					for($k=0;$k<count($_SESSION['items_in_sale']);$k++)
					{
						if($k!=$pos)
						{
							array_push($items_array_temp,$_SESSION['items_in_sale'][$k]);
						}
					}
					if(count($_SESSION['items_in_sale'])==0)
					{
						$this->closeSale();
						break;
					}
					else
					{
						unset($_SESSION['items_in_sale']);
						$_SESSION['items_in_sale']=array_values($items_array_temp);
					}
					break;
				case $action=='item_po':
					for($k=0;$k<count($_SESSION['items_in_po']);$k++)
					{
						if($k!=$pos)
						{
							array_push($items_array_temp,$_SESSION['items_in_po'][$k]);
						}
					}
					if(count($_SESSION['items_in_po'])==0)
					{
						$this->closeSale();
						break;
					}
					else
					{
						unset($_SESSION['items_in_po']);
						$_SESSION['items_in_po']=array_values($items_array_temp);
					}
					break;	
				case $action=='item_search':
					unset($_SESSION['current_item_search']);
					break;
				case $action=='item_search_po':
					unset($_SESSION['current_item_search']);
					break;	
				case $action=='supplier_search':
					unset($_SESSION['current_supplier_search']);			
					break;
				case $action=='supplier_search_po':
					unset($_SESSION['current_supplier_search']);			
					break;
				case $action=='customer_search':
					unset($_SESSION['current_customer_search']);			
					break;
				case $action=='customer_search_buy':
					unset($_SESSION['current_customer_search']);			
					break;	
			}
		}
	}
}

?>