<?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');
	    $destination_file = $_FILES["csv_file"]["name"]."_".$curTime.".csv";
	    //$destination_file = "/ubr_inventory/in_files/".$storagename; 
	  //move_uploaded_file($target_file,$destination_file);  
	   
	   $target_file = $_FILES['csv_file']['tmp_name'];
	   $store_code = $_REQUEST['store_code'];
	   $csvArr = parse_csv_file($target_file);
	   $cntCsvArr = count($csvArr);
echo "<pre>==ff=";
//print_r($csvArr);die;


	   move_uploaded_file($_FILES["csv_file"]["tmp_name"], "ubr_inventory/in_files/" . $destination_file);
	   
	   //if(is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
		$obj->query("DELETE FROM `dordsh_inv_automnup` WHERE `store_id` LIKE '$store_code'");

	   //}
	   
	   foreach($csvArr as $csvArrs) {
		   			   
	   $lookup_code=$csvArrs['sku_id'];
	   
	   $storeIdStr = explode('-',$store_code);
	   $storeId = $storeIdStr[0];
	   
	   $store_identifier=$storeId;
	   $price=$csvArrs['price'];

	   $item_name=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['name']);
	   
	   $cost_unit=$csvArrs['cost_unit'];
	   $size=$csvArrs['size'];

	   $available=$csvArrs['is_active'];
	   
	   $par_weight=$csvArrs['is_weighted_item'];
	   
	   $is_alcohol=$csvArrs['is_alcohol'];
	   
	   $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['description']);
	   
	   $remote_image_URL=mysqli_real_escape_string($GLOBALS['conn'],$csvArrs['image_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; 

		
	           //echo "<pre>==ff=";
			    //print_r($catIdArr);
        //print_r($subcatIdArr);
	  //die;
	   
		      //echo "<pre>==ff=";
        //print_r($csvArr);
        if($cntCsvArr > 0 && $storeId !="" ) {
		echo $insSql = "INSERT INTO dordsh_inv_automnup set sku_id='$lookup_code', store_id='$store_code',price='$price',name='$item_name'
		           ,cost_unit='$cost_unit',size='$size',is_active='$available',is_weighted_item='$par_weight',department='$department'
				   ,aisle='$aisle',description='$item_details',image_URL='$remote_image_URL',store_identifier='$storeId',create_at='$createdAT',updtaed_at='$updatedAT'
				   ,cat_id='$mainCategory',subcat_id='$subCategory' ";	
		}
	    $obj->query($insSql);
		//die;
	   }

/*$sql = "INSERT INTO `caubff_inventory_sync_20250106` (`id`, `lookup_code`, `store_identifier`, `price`, `brand_name`, `
item_name`, `cost_unit`, `size`, `size_uom`, `balance_on_hand`, `available`, `
par_weight`, `department`, `aisle`, `item_details`, `remote_image_URL`,
 `additional_images_url`, `store_id`, `create_at`, `updtaed_at`, `status`, `ubr_store_id`)";*/
		
		 $_SESSION['sess_msg'] =  "File processed successfully!".'<br>';
		 header("location:ddautom_ffupldprs.php");
		 exit;
        //echo "<pre>==ff=";
        //print_r($csvArr);
	  //die;
	} else {
		 $_SESSION['sess_msg'] =  "Invalid csv file.Please upload valid csv file!".'<br>';
		 header("location:ddautom_ffupldprs.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: DoDash
					</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 Id (For ex DD56880CSTX) :</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 FF 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>