<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

include("config.inc.php");
include("function.inc.php");
include("functions_Items.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$mode 		= $_GET['mode']; 
$itemcol 	= $_GET['itemcol'];
$itemRemove	= $_GET['itemRemove'];
$chk_seq	= $_POST['chk_seq']; if($chk_seq == '') $chk_seq = $_GET['chk_seq'];
$vproject	= $_GET['vproject'];

if($chk_seq == '') $chk_seq = 0;
//Add item field into excel table
if($mode == 'addColumn'){
	
	echo "[BRK]";
	showColumns($itemcol, $removedCol);
	echo "[BRK]";
	addColumns($chk_seq);
	
	exit;
}

else if($mode == 'removeCol'){
	
	echo "[BRK]";
	showColumns($itemcol, $itemRemove);
	echo "[BRK]";
	addColumns($chk_seq);
	
	exit;
}
else if($mode == 'clearPage'){
	$_SESSION['Cols'] = '';
	echo "[BRK]";
	showColumns('', '');
	echo "[BRK]";
	addColumns('');
	
	exit;
}else if($mode == 'ImportExcel'){
	
	
	if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

		$image_name = addslashes($_FILES['image']['name']);
		$image_size = getimagesize($_FILES['image']['tmp_name']);
		$image_type =$_FILES['image']['type'];
		//	echo$_FILES['image']['size'];
			
		if ($image_size == FALSE) {
			$error['image'] = "That's not an image.";
		
		}
		else 
			if ($_FILES['image']['size'] > 204800) {
				$error['image'] = "Image is too large.";
			}
			else {
				$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
			}
	}
	
	$foldername='uploads';
	if (!file_exists($foldername)) {
		mkdir("./uploads", 0700);
	}

	$fileName = $_FILES["image"]["name"]; 
	$fileTmpLoc = $_FILES["image"]["tmp_name"];
	// Path and file name
	$pathAndName = "uploads/".$fileName;
	$pathAndName1 = "./uploads/".$fileName;
	// Run the move_uploaded_file() function here
	$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);

	require_once('Spreadsheet/Excel/Reader.php');
    $excel = new Spreadsheet_Excel_Reader();
    $excel->read($pathAndName1); 
	
	$x=2;
	$message = '';
	$ColVal = array();
	while($x<=$excel->sheets[0]['numRows']) {
		$editmode = 0;
		
		$Colss = array();
		$Colss = explode(',', $_SESSION['Cols']);
		$Colss = array_filter($Colss);
			$i = 1;
			foreach($Colss as $col){
				
				$ColVal[$col] = $excel->sheets[0]['cells'][$x][$i];	
				//group code 
				if($col == 'Group_code' && $ColVal[$col] !=''){
					$q = "select Group_discountPer from grouping where group_code = '".$ColVal[$col]."' ";
					$resultdt= mysql_query($q,$connection) or die( mysql_error());
					$rowdt1=mysql_fetch_array($resultdt);
					$discper=$rowdt1[0];
					if($discper>0)
						$item_discountper = $discper;
				}
				//item discount
				if( $col == 'item_discountpercent' && $item_discountper > 0)
					$ColVal[$col] = $item_discountper;
				//check item_code
				if($col == 'Item_Code' && $ColVal[$col] !=''){
					$itemcode = $ColVal[$col];
					$query = "select 1 from items where item_code = '".$ColVal[$col]."' ;";
					$res = mysql_query($query,$connection);
					$numr = mysql_num_rows($res);
					if($numr > 0)
						$editmode = 1;
					
				} else $item_code='';
				if($col == 'item_vattype' && $ColVal[$col] ==''){ 
					$ColVal[$col] = 1;
				}
				/* if($col == 'Item_SubSequence' && $ColVal[$col] ==''){ 
					$queryseq = "select default_itemSubSequence from setup;";
					$res = mysql_query($queryseq,$connection);
					$rwseq = mysql_fetch_array($res);
					$ColVal[$col] = $rwseq[0];
				} */
				$i++;
			} 
			
	 	if ($ColVal['Item_Code'] != ''){	
		if($editmode == 0)	{
			fbegin();
			$item_id = get_nextsequence('Item_Increment','',$connection);
			fcommit();
			
			//insert into items	
			$queryins = " insert into items (item_id "; 
			foreach($Colss as $col){
				$queryins .= ",".$col;
			}
			$queryins .= " , Item_SysDateTime, item_createdBy ) values ( $item_id ";
			
			foreach($Colss as $col){
				if(empty($ColVal[$col]))  $ColVal[$col]= "null";
				else $ColVal[$col]="'".$ColVal[$col]."'"; 
				 
				$queryins .= ",".$ColVal[$col];
			}
			$queryins .= ", now(), '".$_SESSION['useraccount']."'); ";
			
			
			$resins = mysql_query($queryins,$connection);
			if(!$resins)
				$message=$message.",".mysql_error();
			else {
				if($chk_seq == 1){
					$updateseq = "update setup set item_sequence = item_sequence+1;";	
					$resseq = mysql_query($updateseq, $connection);
				} 
				if($vproject == 1){
					
					$maxproj = "select ifnull(max(project_id),0)+1 from project";
					$resmax = mysql_query($maxproj,$connection);
					$rwmax = mysql_fetch_row($resmax);
					$project_id = $rwmax[0];
					foreach($Colss as $col){
						if($col == 'Item_Code' && $ColVal[$col] !='')
							$item_code = $ColVal[$col];
						if($col == 'Item_Description' && $ColVal[$col] !='')
							$item_description = $ColVal[$col];
						else $item_description = $item_code;
					}
					$query_project = "insert into project (Project_Code, Project_Name, Project_Deactivate, Project_date, Project_BelongsToGroup, Synchronized,Project_posted, project_id)
									values (".$item_code.",".$item_description.",0,now(),0,0,0,$project_id)";  //echo $query_project;
					$resproj = mysql_query($query_project, $connection);
				}
			}
		} 
		 else {
			$c=0;
			$queryup = " update items set "; 
			foreach($Colss as $col){
				
				if($ColVal[$col] == '')  $ColVal[$col]="null";
				else $ColVal[$col] = "'".$ColVal[$col]."'"; 
				
				if($col != 'Item_Code'){
					if($c == 0) $queryup .= " $col = $ColVal[$col] ";
					else $queryup .= ", $col = $ColVal[$col] ";
					$c++;
				}
			} 
			$queryup .= " where item_code= '$itemcode';";//echo $queryup ;echo "<br>";
			$resup = mysql_query($queryup,$connection);
			if(!$resup)
				$message=$message.",".mysql_error();
		} 
		}
		
 
		$x++;	
	}  
	
	//exit;
	if($message != '')
		header ("Location: ./Form_LoadFromExcel.php?message=".$message);
	else 
		header ("Location: ./Form_LoadFromExcel.php");
}


function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

?>