<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com (C) 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "../includes/config.php";
include "../includes/session.php";
include "../includes/functions.php";

if(isset( $_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"]!= ""){
	$adminname = $_SESSION["sess_adminname"];
}else{
	header("Location:login.php");
	exit;
}
$csvfilename=$_GET['file'];
$filepath="../csv/$csvfilename";
$sampleFilepath="../csv/sample.csv";

$sellerid=$_GET['sellerid'];

if(file_exists($sampleFilepath))
{ // chechk sample csv file exixts or not 
		
		$fcontents = file($sampleFilepath);
		$headers=str_replace('"',"",$fcontents[0]);
		$sampleArray=explode(",",$headers);
}

if(file_exists($filepath))
{ // check file exists
$fcontents = file($filepath);
$header=str_replace('"',"",$fcontents[0]);
$listArray=explode(",",$header);

} // file check  

$message="";
$flag="true";
if(isset($_POST['btnSave']) && $_POST['btnSave']=='Next')
{
	$csvfiles=$_POST['csvfilename'];
	$csvFile="../csv/$csvfiles";
	$sellerid=$_POST['sellerid'];
	$productNames=trim($_POST['labelsproduct_name']);
	$productCategory=trim($_POST['labelsproduct_category']);
	$productCode=trim($_POST['labelsproduct_code']);
	$labelsproduct_description=trim($_POST['labelsproduct_description']);
	$labelsproduct_price=trim($_POST['labelsproduct_price']);
	$labelsproduct_height=trim($_POST['labelsproduct_height']);
	$labelsproduct_width=trim($_POST['labelsproduct_width']);
	$labelsproduct_length=trim($_POST['labelsproduct_length']);
	$labelsproduct_stock=trim($_POST['labelsproduct_stock']);
	$labelsreorder_level=trim($_POST['labelsreorder_level']);
	$labelsDiscount=trim($_POST['labelsDiscount']);
	$labelsDiscountdescription=trim($_POST['labelsDiscountdescription']);
	$labelsnproduct_shipping_weight=trim($_POST['labelsshipping_weight']);
	
	if($productNames=='')
		{
		$message .= "* Select linked filedname for productname ! <br>";
	}
	
	if($productCategory=='')
		{
		$message .= "* Select linked filedname for productcategory ! <br>";
	}
	if($productCode=='')
	{
	
		//$message .= "* Select linked filedname for productcode ! <br>";
	}
	
	if($labelsproduct_price=='')
	{
	
		$message .= "* Select linked filedname for productprice ! <br>";
	}
	if($labelsproduct_description=='')
	{
	
		$message .= "* Select linked filedname for productdescription ! <br>";
	}
	
	$productDetails=array();
	if($message=='')
	{ // check if messahe is empty 
	
			if(file_exists($csvFile))
	{ // check file exists or not 
		$maxlinelength = 1000;
		$fh = fopen($csvFile, 'r');
		$lines =count(file($csvFile))-1;
		$firstline = fgetcsv($fh, $maxlinelength);
		$cols = count($firstline);
		$row = 0;
		$inventory = array();
				while ( ($nextline = fgetcsv($fh, $maxlinelength)) !== FALSE )
				{
					 for ( $i = 0; $i < $cols; ++$i )
					{
						$inventory[$firstline[$i]][$row] = $nextline[$i];
					}//end forloop
				++$row;
			}//end while loop
		//}//end foreach
	
		if(in_array($productCategory,$firstline))
		{
		  $produtCatArray=RearrangeArray($firstline,$productCategory,$inventory);
			if(!empty($produtCatArray) && is_array($produtCatArray))
			{ // check product category exists
				foreach($produtCatArray as $value)
				{
					$sql="select * from ".$tableprefix."categories where category_name ='".$value."' ";
					$rs=mysql_query($sql) or die(mysql_error());
					$numrows=mysql_num_rows($rs);
					if($numrows==0)
					{
						$sql_insert="insert into ".$tableprefix."categories (category_name) values('".$value."')";
						mysql_query($sql_insert);
					}//end if

					// call looping once agin 
					$sql1="select * from ".$tableprefix."categories where category_name ='".$value."' ";
					$rs11=mysql_query($sql1) or die(mysql_error());
					$totnumRows=mysql_num_rows($rs11);
						
					if($totnumRows>0)
					{
						$rr=mysql_fetch_array($rs11);
						$categoryId[]=$rr['category_id'];
					}//end if	
 		 		}// end for each 
			} // end if arry exists check 
			
		$sellerid=$_POST['sellerid'];
		$recordsper=0;
		$productNameArray=RearrangeArray($firstline,$productNames,$inventory);
		$productCodeArray=RearrangeArray($firstline,$productCode,$inventory);
		$productDescriptionArray=RearrangeArray($firstline,$labelsproduct_description,$inventory);
		$productPriceArray=RearrangeArray($firstline,$labelsproduct_price,$inventory);
		$productHeightArray=RearrangeArray($firstline,$labelsproduct_height,$inventory);
		$productWidthArray=RearrangeArray($firstline,$labelsproduct_width,$inventory);
		$productLengthArray=RearrangeArray($firstline,$labelsproduct_length,$inventory);
		$productStockArray=RearrangeArray($firstline,$labelsproduct_stock,$inventory);
		$productReorderArray=RearrangeArray($firstline,$labelsreorder_level,$inventory);
		$productDiscountArray=RearrangeArray($firstline,$labelsDiscount,$inventory);
		$productDiscountDespArray=RearrangeArray($firstline,$labelsDiscountdescription,$inventory);
		$productShippingWeightArray=RearrangeArray($firstline,$labelsnproduct_shipping_weight,$inventory);
		for($key=0;$key<$lines;$key++)
		{
			
		$sql="select * from ".$tableprefix."products where 	product_name='".$productNameArray[$key]."' and product_artist_id='".$sellerid."' ";
		$rs=mysql_query($sql) or  die (mysql_error());
		 $resultrows=mysql_num_rows($rs);
		
		if($resultrows==0)
		{ // if same product name doesn't exists save products
		
		$sql="INSERT INTO ".$tableprefix."products (product_name,product_category,product_code,product_description,product_price,product_height,product_width,product_length,product_stock,reorder_level,Discount,Discountdescription,nproduct_shipping_weight,product_artist_id,vapproved,date_added)";
		$sql.="values('".addslashes($productNameArray[$key])."','".addslashes($categoryId[$key])."','".addslashes($productCodeArray[$key])."','".addslashes($productDescriptionArray[$key])."',
					'".addslashes($productPriceArray[$key])."','".addslashes($productHeightArray[$key])."','".addslashes($productWidthArray[$key])."','".addslashes($productLengthArray[$key])."',
						'".addslashes($productStockArray[$key])."','".addslashes($productReorderArray[$key])."','".addslashes($productDiscountArray[$key])."',
						'".addslashes($productDiscountDespArray[$key])."','".addslashes($productShippingWeightArray[$key])."','".addslashes($sellerid)."','Y',now())";
		$rs=mysql_query($sql) or die(mysql_error());
		
		
		$productsSavedArray[]=$productNameArray[$key];
		// Update category table 
		if(mysql_affected_rows()>0)
		{
			$recordsper++;
			
			$last_insert_products=mysql_insert_id();
		// Select Inserted Datas Details 
		
	
			$sql_selct="SELECT p.product_id,p.product_name,p.product_code,c.category_name,p.product_price,p.product_stock  from ".$tableprefix."products p 
			INNER JOIN ".$tableprefix."categories c ON c.category_id=p.product_category where p.product_id='".addslashes($last_insert_products)."' ";
			$rs_selct=mysql_query($sql_selct) or die(mysql_error());
			
			if(mysql_num_rows($rs_selct)>0)
			{
				while($row=mysql_fetch_array($rs_selct))
				{
				   $productDetails[] = array("product_code"=>$row["product_code"],
											 	"product_name"=>$row["product_name"],
												"category_name"=>$row["category_name"],
												"product_price"=>$row["product_price"],
												"product_stock"=>$row["product_stock"]);
										    
				} 
			}
			
		
		// End 	
			
		$sql_update="update ".$tableprefix."categories  set count =count +1,route='".$categoryId[$key]."' where  category_id ='".$categoryId[$key]."'  ";
		$rs_update=mysql_query($sql_update) or die(mysql_error());
		
		} // end if affected rows
		
	} // end of saving products	
	
	if($resultrows>0)
		{ //check if save product name exists then 
				$flag="false";
				$parray[]=$productNameArray[$key];
		
		}
		
	}  // end for loop 
	
	
	if(count($productDetails)>0)
	{			
		sendBulkUploadSellerEmail($sellerid,$productDetails);
	}	
		
		

		}//end if array check
 	}// end file checking 	 
	
	} // end message check 
	
} // end button post check 
include "../includes/htmltop.php";
?>
		<body>
		<center>
		<div align="left" id="layout">
				<!--header area start -->
<?php

	include_once("../includes/topheader_admin.php")
?>
				
				<!--header area end -->
				
				
				
				
				<div align="left" class="main_body">
				<!--main body start -->
				
				
				
<?php
		include_once("../includes/admintopmenu.php")
?>		
					<div align="left" class="content_area">
					
					<!--content area start -->
					<div align="left"><?php include("../includes/bulkuploadmenu.php");?></div>
					<div align="left" class="page_title">Bulk Products Upload</div>
					<div align="center" class="text_information grey_tr"><?php echo $message?></div>
            		<br>
					<div align="left">																			
						<form action="" method="post" enctype="multipart/form-data" name="frmProductBulk" >
						
						<?php if($recordsper==0 && $flag=="true")
						{ // display upload if error free
						?>	
						<table width="98%" border="0" cellpadding="8" cellspacing="4" class="manage_table">
						<tr>
						  <td colspan="3">Use the form below to define which import fields should map to which product fields.</td>
						  </tr>
						<tr><td width="34%" height="37"><strong>Link Import Fields</strong></td>
						  <td width="2%">&nbsp;</td>
						  <td width="64%">&nbsp;</td>
						</tr>
						<?php 
						foreach($sampleArray as $bulkvalue)
						{
							$caption = str_replace("_"," ",$bulkvalue);
							$filedArray='labels'.$bulkvalue;
						?>
						<tr>
						  <td><?php if($bulkvalue=="product_name" ||  $bulkvalue=="product_category" || $bulkvalue=="product_price"  || $bulkvalue=="product_code" || $bulkvalue=="product_description") { ?><span class="required">*</span><?php } ?> Match '<?php echo $caption;?> ' with</td>
						  <td>&nbsp;</td>
						  <td><select name="labels<?php echo $bulkvalue;?>">
						  <option value="">Ignore</option>
						  <?php 
						  	foreach($listArray as $bulkkeys)
							{
								$textName = str_replace("_"," ",$bulkkeys);
							?>
							<option value="<?php echo $bulkkeys?>" <?php if(trim($bulkvalue)==trim($bulkkeys)) { echo "selected" ; } ?>><?php echo $textName;?> </option>
							<?
							}
							?>
					      </select>
					      <input type="hidden" name="csvfilename" value="<?php echo $csvfilename;?>">
					      <input type="hidden" name="sellerid" value="<?php echo $sellerid;?>"></td>
						  </tr>
						 <?php } ?>
						<tr>
						  <td>&nbsp;</td>
						  <td>&nbsp;</td>
						  <td><input type="submit" name="btnSave" value="Next" class="button"></td>
						  </tr>
						</table>
					<?php } // end if ?>
						
						<?php if($recordsper>0  && $flag=="false")
						{ // check products uploaded or not 
						?>
						<table width="98%" border="0" cellpadding="8" cellspacing="4" class="manage_table">
						<tr>
						  <td colspan="3" align="left" class="text_information"><?php echo $recordsper?> product(s)
						  saved successfully.</td>
						  </tr>
						<?php if(is_array($parray) && count($parray)>0){ ?>
						  <tr>
						  <td colspan="3" align="left" class="text_information">Following Products Failed To Save. Productname Already Exists!. </td>
						  </tr>
						  <?php 
						  $dd=1;
						  foreach($parray as $pnames)
						  {
						  ?>
						   <tr>
						  <td colspan="3" align="left"><?php echo $dd. ")  ". $pnames;?></td>
						  </tr>
						  <?
						  	$dd++;
						      } // end for each 
						   } // end if error 
					 ?>
						    <tr>
						  <td width="22%" height="50" align="left"><input type="button" name="btnBack" value="Back To Bulkupload" class="button" onClick="window.location.href='bulkupload.php'"></td>
						  <td width="30%" height="50" align="left"><input type="button" name="btnNext" value="Continue" class="button" onClick="window.location.href='bulkimageupload.php?sellerid=<?php echo $sellerid;?>'"></td>
						  <td width="48%" height="50" align="left">&nbsp;</td>
						 </tr>
						   
						  </table>
						  
						<?php }  // end if ?>  
						
						<?php if($recordsper==0 && $flag=="false")
						{ // check products uploaded or not 
						?>
						<table width="98%" border="0" cellpadding="8" cellspacing="4" class="manage_table">
						<tr>
						  <td colspan="3" align="left" class="text_information"><?php echo $recordsper;?>  products saved.</td>
						  </tr>
						  <?php if(is_array($parray) && count($parray)>0){ ?>
						  <tr>
						  <td colspan="3" align="left" class="text_information">Following Products Failed To Save.Same Productname Already Exists!. </td>
						  </tr>
						   <?php 
						   $num=1;
						  	 foreach($parray as $value)
						 		 {
						  ?>
						   <tr>
						  <td colspan="3" align="left"><?php echo $num. ")  ". $value;?> </td>
						  </tr>
						  <?
						  		$num++;
						      } // end for each 
							 } // end if array check 
						?>	  
						
						 <tr>
						  <td width="43%" height="50" align="left"><input type="button" name="btnBack" value="Back To Bulkupload" class="button" onClick="window.location.href='bulkupload.php'"></td>
						  <td width="46%" height="50" align="left">&nbsp;</td>
						  <td width="11%" height="50" align="left">&nbsp;</td>
						 </tr>
						  </table>
						<?php 
						        }  // end if ?>  
						
						<?php if($recordsper>0 && $flag=="true")
						{ // check products uploaded or not 
						?>
						<table width="98%" border="0" cellpadding="8" cellspacing="4" class="manage_table">
						<tr>
						  <td colspan="3" align="left" class="text_information"><?php echo $recordsper;?>  products saved.</td>
						  </tr>
						  <?php if(is_array($productsSavedArray) && count($productsSavedArray)>0){ ?>
						  <tr>
						  <td colspan="3" align="left" class="text_information">Following Products Saved Successfully !. </td>
						  </tr>
						   <?php 
						   $nums=1;
						  	 foreach($productsSavedArray as $products)
						 		 {
						  ?>
						   <tr>
						  <td colspan="3" align="left"><?php echo $nums. ")  ". $products;?> </td>
						  </tr>
						  <?
						  		$nums++;
						      } // end for each 
							 } // end if array check 
						?>	  
						  <tr>
						  <td width="19%" height="50" align="left"><input type="button" name="btnBack" value="Back To Bulkupload" class="button" onClick="window.location.href='bulkupload.php'"></td>
						  <td width="33%" height="50" align="left"><input type="button" name="btnNext" value="Continue" class="button" onClick="window.location.href='bulkimageupload.php?sellerid=<?php echo $sellerid;?>'"></td>
						  <td width="48%" height="50" align="left">&nbsp;</td>
						 </tr>
						  </table>
						  
						<?php }  // end if ?>  
						
					  </form>
																	

					  </div>
						
						
				<!--content area end-->
								
				</div>
				
								
					<div align="left" class="clear_float"><img src="<?php echo $imagefolder;?>/clear.gif" alt="" width="1" height="1" /></div>
				<!--main body end -->
				</div>
				
				
<?
	include "../includes/footer.php";
?>
<script language="javascript">

function Valiadtelinks()
{
	if(document.frmProductBulk.labelsproduct_name.value=="")
	{
	
		alert("please select linked filedname for productname");
		document.frmProductBulk.labelsproduct_name.focus();
		return false;
	}
	
	if(document.frmProductBulk.labelsproduct_category.value=="")
	{
	
		alert("please select linked filedname for productcategory");
		document.frmProductBulk.labelsproduct_category.focus();
		return false;
	}
	if(document.frmProductBulk.labelsproduct_price.value=="")
	{
	
		alert("please select linked filedname for productprice");
		document.frmProductBulk.labelsproduct_price.focus();
		return false;
	}
	if(document.frmProductBulk.labelsproduct_description.value=="")
	{
		alert("please select linked filedname for productdescription");
		document.frmProductBulk.labelsproduct_description.focus();
		return false;
	}
	
	return true;	

}


</script>