<?php
session_start();
include("../include/config.php");
include("../include/functions.php"); 
include("../include/simpleimage.php");
 validate_admin();
  $cat_id=mysqli_real_escape_string($GLOBALS['conn'],$_POST['cat_id']);
  $url=SITE_URL;
  //$csvMimes = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
  
  $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
    
    // Validate whether selected file is a CSV file
	
 if($_REQUEST['submitForm']=='yes'){
	//echo $_FILES['csv_file']['type'];
	//echo "<pre>";print_r($csvMimes);die;
    if(!empty($_FILES['csv_file']['name']) && in_array($_FILES['csv_file']['type'], $csvMimes)){
		

		$curTime =  date('Y-m-d_H:i:s');
	    $destination_file = $_FILES["csv_file"]["name"]."_".$curTime.".csv";

	   
	   $target_file = $_FILES['csv_file']['tmp_name'];
	   $store_code = $_REQUEST['store_code'];
	   $csvArr = parse_csv_file($target_file);
	   $cntCsvArr = count($csvArr);


	   
	   //if(is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
		$obj->query("DELETE FROM `cainsta_ff_inventory_sync_v1` WHERE `store_identifier` LIKE '$store_code'");

	   //}
	   
	   foreach($csvArr as $csvArrs) {
		   
	   $tax = $csvArrs['tax'];
       $bottle_deposit = rtrim(ltrim($csvArrs['bottle_deposit']));		   
		   
	   $lookup_code=$csvArrs['lookup_code'];
	   $store_identifier=$csvArrs['store_identifier'];
	   $price=$csvArrs['price'];
	   $brand_name=$csvArrs['brand_name'];
	   $item_name=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['item_name']);
	   $cost_unit=$csvArrs['cost_unit'];
	   $size=$csvArrs['size'];
	   $size_uom=$csvArrs['size_uom'];
	   $balance_on_hand=$csvArrs['balance_on_hand'];
	   $available=$csvArrs['available'];
	   $par_weight=$csvArrs['par_weight'];
	   $department=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['department']);
	   $aisle=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['aisle']);
	   $item_details=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['item_details']);
	   $remote_image_URL=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['remote_image_URL']);
	   $additional_images_url=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['additional_images_url']);
	   $createdAT =  date('Y-m-d_H:i:s');
	   $updatedAT =  date('Y-m-d_H:i:s');
	   
	   	$catIdSql = $obj->query("SELECT id,parent_id,maincategory FROM `tbl_maincategory` WHERE `maincategory` LIKE '$department'");
		$catIdArr=$obj->fetchNextObject($catIdSql);
		$mainCategory =$catIdArr->id; 
		
	    $subcatIdSql = $obj->query("SELECT id,parent_id,maincategory FROM `tbl_maincategory` WHERE `maincategory` LIKE '$aisle'");
		$subcatIdArr=$obj->fetchNextObject($subcatIdSql);
		$subCategory =$subcatIdArr->id; 
		$storeIdStr = explode('-',$store_code);
		$storeId = $storeIdStr[2];
		
	           //echo "<pre>==ff=";
			    //print_r($catIdArr);
        //print_r($subcatIdArr);
	  //die;
	   
		      //echo "<pre>==ff=";
        //print_r($csvArr);
        if($cntCsvArr > 0 && $storeId !="" ) {
		$insSql = "INSERT INTO cainsta_ff_inventory_sync_v1 set lookup_code='$lookup_code', store_identifier='$store_identifier',price='$price',brand_name='$brand_name' ,item_name='$item_name'
		           ,cost_unit='$cost_unit',size='$size',size_uom='$size_uom',balance_on_hand='$balance_on_hand',available='$available',par_weight='$par_weight',department='$department'
				   ,aisle='$aisle',item_details='$item_details',remote_image_URL='$remote_image_URL',additional_images_url='$additional_images_url',store_id='$storeId',create_at='$createdAT',updtaed_at='$updatedAT'
				   ,status=1,insta_store_id='$store_code',cat_id='$mainCategory',subcat_id='$subCategory',tax='$tax',bottle_deposit='$bottle_deposit'";	
		}
	    $obj->query($insSql);
		//die;
	   }

		
		 $_SESSION['sess_msg'] =  "File processed successfully!".'<br>';
		 header("location:upload_ff_to_insta_vv.php");
		 exit;
        //echo "<pre>==ff=";
        //print_r($csvArr);
	  //die;
	} else {
		 $_SESSION['sess_msg'] =  "Invalid csv file.Please upload valid csv file!".'<br>';
		 header("location:upload_ff_to_insta_vv.php");
		 exit;
	}
 }	
function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 100000;
        $header = fgetcsv($handle, $max_line_length);
        $header = str_replace(' ', '_', $header);
        $header = str_replace('/', '_', $header);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo SITE_TITLE; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/admin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" language="javascript">
function validate(obj)
{
if(obj.cat_id.value==''){
alert("Please select category");
obj.cat_id.focus();
return false;
}



}
</script>

</head>
<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<?php include("header.php") ?>

<tr>
	<td align="right" class="paddRtLt70" valign="top">
		<table width="99%" border="0" cellspacing="0" cellpadding="0">
			<tr>

				<td align="right" valign="top">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td align="left" valign="middle" class="headingbg bodr text14">
					<em><img src="images/arrow2.gif" width="21" height="21" hspace="10" align="absmiddle" /></em>Admin: Instacart Canada
					</td>
						</tr>
						
						<tr>
							<td height="100" align="left" valign="top" bgcolor="#f3f4f6" class="bodr">
                            <form name="frm" method="POST" enctype="multipart/form-data" action="" onsubmit="return validate(this)">
						<input type="hidden" name="submitForm" value="yes" />
						<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
							<table width="100%" cellpadding="0" cellspacing="0">
									<tr>
										<td align="center" colspan="2" class="paddRt14 paddBot11">
										<font color="#FF0000"><strong><?php echo $_SESSION['sess_msg']; $_SESSION['sess_msg']='';?></strong></font></td>
									</tr>									

<tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Store identifier (For ex INCA-BFISCCON-4001) :</strong></td>
									  <td align="left" class="paddBot11">
									 <input type="text" name="store_code" id="store_code" size="50" >
                                      </td>
							       </tr>
                               <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Upload Feed File Csv:</strong></td>
									  <td align="left" class="paddBot11"><input name="csv_file" type="file"  /><br/>
                                      <?php if(is_file("../upload_images/category/".$result->photo)) {?>
                                      <img src="../upload_images/category/<?php echo  $result->photo; ?>" width="100" height="100" />
                                      <?php } ?>
                                      </td>
							       </tr>
 
                              
									<tr>
									  <td align="right" class="paddRt14 paddBot11">&nbsp;</td>
									  <td align="left" class="paddBot11">&nbsp;</td>
							  </tr>
									<tr>
										<td width="18%" align="right" class="paddRt14 paddBot11">&nbsp;</td>
										<td width="82%" align="left" class="paddBot11">
											<input type="submit" name="submit" value="Submit"  class="submit" border="0"/> 	                  		 &nbsp;&nbsp;
																		  </td>
									</tr>
								</table></form>
							</td>
						</tr>
						
					</table>
				</td>
			</tr>
		</table>
	</td>
</tr>
<?php include('footer.php'); ?>
</table>
</body>
</html>