<?php

//set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib1');
//include_once('phpseclib1/Net/SFTP.php');

	include("../include/config.php");
	
//include("../include/functions.php"); 
	//die('here25');
//validate_admin();
//error_reporting(E_ALL);
//ini_set('display_errors', '1');

//$isCLI = is_cli();
ini_set('memory_limit','2048M');
$_POST['dnld_ic_ff']=1;



if($_POST['dnld_ic_ff']!=''){
	
	//$icsid = $_POST['dnld_ic_ff'];
	//$icsid = $ubStrid->ubr_store_id;

$isCLI =true;
if( !$isCLI ) {
       die("Sorry! Cannot run in a browser!");
} else { 


        $imgPath = 'https://www.quicklly.com/upload_images/product/';
        //Get data for FULL INVENTORY FEED FILE
        $section =1;
		$addCod="";
        
		$sIdArr = "SELECT  ubr_store_id, store_identifier FROM uber_inventory_process WHERE  ubr_store_id not in ('AAPAFSSCA-114','APIGPAZ-113') group by ubr_store_id ";
        $sqlUarr=$obj->query($sIdArr);

		
		 while($sidResult=$obj->fetchNextObject($sqlUarr)) { 
		 echo "<br>".$sidResult->ubr_store_id;
		 $icsid = $sidResult->ubr_store_id;
		 //}
        //echo "<pre>===";print_r($sidResult);die;

        $sqlPrduct= "SELECT  `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`,ubr_store_id 
		FROM uber_inventory_process WHERE `ubr_store_id` LIKE '$icsid' AND ubr_store_id not in ('AAPAFSSCA-114','APIGPAZ-113')  ";

        $sql=$obj->query($sqlPrduct . $addCod );
       $numRows=$obj->numRows($sql);
		//$prdResult=$obj->fetchNextObject($sql);
        //echo "<pre>===";print_r($prdResult);die;
        //Predefined column for inventroy feed file`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`
        $fullInventoryColumn = array("lookup_code","store_identifier","price",
            "brand_name","item_name","cost_unit",
            "size","size_uom","balance_on_hand",
            "available", "par_weight","department",
            "additional_images_url"
            );


        //$dateTime = date("Ymd").'_'.date("hi");
        $dateTime = date("Ymd");
		$dateTime2 = date("Ymd");
        $dateTime = $dateTime.'_'.date('his');
        $filePath = '';
        $sftpRemoteDir = 'public_html/upload_insta_flat_file/opt/';
        //$sftpRemoteDir = 'inventory-files/';// For Live insta path
        $filePthCpy = 'upload_insta_flat_file/opt/';
       
        if($numRows > 0 ) {
            $fullInventoryData = array();
            while($prdResult=$obj->fetchNextObject($sql)) { 
            //store_id-Product_id ==lookupcode
                //$lookup_code = 'QC-'.$prdResult->barcode.'-D';
				$lookup_code =$prdResult->lookup_code;
                $item_name = ucwords(removeLineBreakSpaces($prdResult->item_name));
                $size = $prdResult->size;
                $size_uom = ucfirst($prdResult->size_uom);
                $available = $prdResult->available;
                $cost_unit = ucfirst($prdResult->cost_unit);
                $price = $prdResult->price;
                $department = ucwords(strtolower($prdResult->department));
                $aisle = ucwords($prdResult->aisle);

                $storeName = $prdResult->storename;
                //$storePrefix = storePrefix($storeName);
                $cityPrefix = '';
                
                
                //$cityPrefix = '-JSQ';
                //echo "<pre>";print_r($storePrefix);die;
                //This unique combination of storename first letter-store id
				//$storePrefix='ICC';
                $store_indentifier = $prdResult->ubr_store_id;
				//$store_indentifier = $storePrefix.'-'.$prdResult->storeid;
				//$//store_indentifier = "FF-100";
                $brand_name ='';
                $balance_on_hand = '';
                $par_weight = '';
                $item_details = $prdResult->item_details;
                $remote_image_URL= $prdResult->remote_image_URL;
                $additional_images_url='';
                $storeZipcode='';
                //$taxValue =$prdResult->tax_value;                
                //$price = number_format(($price+$hikePrice),2);
                                
                //echo "<pre>===";print_r($storeHikeArr);die;
				//$store_indentifier= 'IG-103-ED-NJ';
                $fullInventoryData[] =  array($lookup_code,$store_indentifier,$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
                                            );
				//sleep(1);							
            }

                //Use store id for store name which is setup on instacart as file name 

                //$fileName = 'quicklly_store_'."_".$dateTime.'.csv'; 
                //$fileName = $dateTime.'_quicklly_full'.'.csv';
                //$fileName = $dateTime.'_quicklly_grocery_full_sipce_box'.'.csv';
                //for dtc
                //$fileName = $dateTime.'_dtc_quicklly_full'.'.csv';
				$fileName = $dateTime2."_".$store_indentifier.'_inventory'.'.csv';
                $fileNamePath = $filePath.$fileName;
                //echo "<pre>";print_r($fullInventoryData);die;
                $generateCsv = genrateUbrFlatFile($fileNamePath,$fullInventoryColumn,$fullInventoryData);

                if($generateCsv) {
                    //$sftp = new Net_SFTP(INSTA_SFTP_HOST);
                    //if (!$sftp->login(INSTA_SFTP_USER, INSTA_SFTP_PWD)) {
                        //exit('Login Failed');
                    //}
                    //For Upload transaction log file on quicklly sftp
                //$sftpFile = $sftp->put($sftpRemoteDir.$fileName, $fileNamePath, NET_SFTP_LOCAL_FILE);
                    //if($sftpFile) {
                        //rename($fileNamePath, $filePthCpy.$fileName);
                    //}
                    $msg =  "Product feed file downloaded successfully".'<br>';
					//header("location:ic-ff-dnld.php?success=Product feed file downloaded successfully!");
					//exit;
                }
        }else {
			 echo $msg =  "Error in store id pls enter valid store id!".'<br>';
			 header("location:generate-uber-feed-file.php?error=Error in store id pls enter valid store id!!");
			 exit;
		}



}
} 
}



function genrateUbrFlatFile($fileName,$columnArr,$dataArr ) {
	
	//echo "<pre>";print_r($columnArr);
   //echo "<pre>";print_r($dataArr);die;
    //$file = fopen($fileName, 'wb');
    // save the column headers
    //fputcsv($file, $columnArr); 

// Set the content type to CSV
//header('Content-Type: text/csv; charset=utf-8');

// Set the response header to specify that the file should be downloaded as an attachment
//header('Content-Disposition: attachment; filename='.$fileName);

//$dataArr .= $columnArr;

// Open a file handle for writing
$file = fopen('php://output', 'w');

/*$cuuDate=date('Y-m-d');
$csv_filename = $cuuDate."/".$fileName;
$file = fopen ($csv_filename, "w");*/

$dataArr_header[] = ["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"
            ];
			
$dataArr1 = array_merge($dataArr_header,$dataArr);
//echo "<pre>";print_r($dataArr1);die;

    // save each row of the data
    foreach ($dataArr1 as $row)
    {
        $rowD1 =rmCommaStr($row[0]);
		$rowD2 =rmCommaStr($row[1]);
		$rowD3 =rmCommaStr($row[2]);
		$rowD4 =rmCommaStr($row[3]);
		$rowD5 =rmCommaStr($row[4]);
		$rowD6 =rmCommaStr($row[5]);
		$rowD7 =rmCommaStr($row[6]);
		$rowD8 =rmCommaStr($row[7]);
		$rowD9 =rmCommaStr($row[8]);
		$rowD10 =rmCommaStr($row[9]);
		$rowD11 =rmCommaStr($row[10]);
		$rowD12 =rmCommaStr($row[11]);
		$rowD13 =rmCommaStr($row[12]);
		$rowD14 =rmCommaStr($row[13]);
		$rowD15 =rmCommaStr($row[14]);
		$rowD16 =rmCommaStr($row[15]);
		$csv.= $rowD1.','.$rowD2.','.$rowD3.','.$rowD4.','.$rowD5.','.$rowD6.','.$rowD7.','.$rowD8.','.$rowD9.','.$rowD10.','.$rowD11.','.$rowD12.','.$rowD13.','.$rowD14.','.$rowD15.','.$rowD16."\n"; //Append data to csv
		//fputcsv($file, $row);
		//$csv.= nl2br($row[0]).",".nl2br($row[1]).",".nl2br($row[2]).",".nl2br($row[3]).",".nl2br($row[4]).",".nl2br($row[5]).",".nl2br($row[6]).",".nl2br($row[7]).",".nl2br($row[8]).",".nl2br($row[9]).",".nl2br($row[10]).",".nl2br($row[11]).",".nl2br($row[12]).",".nl2br($row[13]).",".nl2br($row[14]).",".nl2br($row[15])."\n";
			//$csv.= $row[0]."',"'.$row[1]."',"'.$row[2]."',"'.$row[3]."',"'.$row[4]."',"'.$row[5]."',"'.$row[6]."',"'.$row[7]."',"'.$row[8]."',"'.$row[9]."',"'.$row[10]."',"'.$row[11]."',"'.$row[12]."',"'.$row[13]."',"'.$row[14]."',"'.$row[15]."'\n"'; //Append data to csv


		//$csv.= $row[0].','.$row[1].','.$row[2].','.$row[3].','.$row[4].','.$row[5].','.$row[6].','.$row[7].','.$row[8].','.$row[9].','.$row[10].','.$row[11].','.$row[12].','.$row[13].','.$row[14].','.$row[15]."\n"; //Append data to csv
    }
    // Close the file
	//fseek($file, 0);
	$currentDateDir = "ubr_inventory/".date("Y-m-d");
	if (!file_exists($currentDateDir)) {
    mkdir($currentDateDir, 0777, true);
    }
	$csv_handler = fopen ($currentDateDir."/".$fileName,'w');
    //fwrite ($csv_handler,$csv);
	fputs($csv_handler, $csv);
    fclose($file);
    return true;
}
//Method to get percentage of number

function getPercentOfNumber($number, $percent){
    return ($percent / 100) * $number;
}
//Get hike price
function getProductHikePrice($zipcode='',$storeId) {

    $cond = '';
    if($zipcode !='') {
       $cond = " and zip='$zipcode'";
    }
   // echo "select hike,commission,minimum_fee from insta_store_zip where 1=1 $cond and storeid='$storeId'";die;
    $sql = mysqli_query($GLOBALS['conn'], "select hike,commission,minimum_fee from insta_store_zip where 1=1 $cond and storeid='$storeId'");
    $result = mysqli_fetch_assoc($sql);
    return ($result);
}

function is_cli()
{
	if( defined('STDIN') )
	{
		return true;
	}
	
	if( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) 
	{
		return true;
	} 
	
	return false;
}

//Method to remove space and line break from product name
function removeLineBreakSpaces($str) {
    $string = trim(preg_replace('/\s\s+/', ' ', $str));
    return $string;
}

function rmCommaStr($name) {
    $string = str_replace(',', '', $name);
    return $string;
}
function getParentname($p_id) {



    $sql = mysqli_query($GLOBALS['conn'], "select maincategory from  tbl_maincategory where id='$p_id'");



    $result = mysqli_fetch_assoc($sql);



    return ($result['maincategory']);
}

function hikerounder($price, $hike) {
//$num=$num),2);
//$price=number_format($price,2);
    $hikes = number_format(($price * $hike / 100), 2);
    $price = rounder(number_format($price + $hikes, 2));
    return $price;
}

//Get the first letter of each word from store name
function storePrefix($storeName) {
    $words = preg_split("/\s+/", $storeName);
    $acronym = '';
    foreach ($words as $w) {
        $acronym .= ucfirst($w[0]);
    }
    return $acronym;
}

function rounder($num) {

    $fln = $num - floor($num);

    if ($fln > 0.00 and $fln < 0.1) {
        $fln = 0.09;
    }

    if ($fln > 0.10 and $fln < 0.2) {
        $fln = 0.19;
    }

    if ($fln > 0.20 and $fln < 0.3) {
        $fln = 0.29;
    }

    if ($fln > 0.30 and $fln < 0.4) {
        $fln = 0.39;
    }

    if ($fln > 0.40 and $fln < 0.5) {
        $fln = 0.49;
    }

    if ($fln > 0.50 and $fln < 0.6) {
        $fln = 0.59;
    }

    if ($fln > 0.60 and $fln < 0.7) {
        $fln = 0.69;
    }

    if ($fln > 0.70 and $fln < 0.8) {
        $fln = 0.79;
    }

    if ($fln > 0.80 and $fln < 0.9) {
        $fln = 0.89;
    }

    if ($fln > 0.90 and $fln < 0.99) {
        $fln = 0.99;
    }



    return floor($num) + $fln;
}
