<?php
include '../../../../shell/gvs_cf.php';
/**
 * XLS parsing uses php-excel-reader from http://code.google.com/p/php-excel-reader/
 */

require('../../php_plugins/php-excel-reader/excel_reader2.php');
require('../../php_plugins/SpreadsheetReader/SpreadsheetReader.php');
include ('sub_bonanza_hw_download_listings.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../../php_plugins/phpmailer/vendor/autoload.php';
require '../../php_plugins/phpmailer/vendor/phpmailer/phpmailer/src/Exception.php';
require '../../php_plugins/phpmailer/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '../../php_plugins/phpmailer/vendor/phpmailer/phpmailer/src/SMTP.php';

$dev_name = BONANZA_HW_DEV_NAME;
$cert_name = BONANZA_HW_CERT_NAME;
$token = BONANZA_HW_TOKEN_VALUE;
$url = "https://api.bonanza.com/api_requests/secure_request";
$headers = array("X-BONANZLE-API-DEV-NAME: " . $dev_name, "X-BONANZLE-API-CERT-NAME: " . $cert_name);
$update = array();
	date_default_timezone_set('UTC');

	$StartMem = memory_get_usage();

	//ec and hw listings download
	curl_file_download();

	$ec_l1_data=get_l1price_skus_list('files_to_compare/ec_l1.csv');
	$hw_l1_data=get_l1price_skus_list('files_to_compare/hw_l1.csv');


	//server connection
	$servername =DATABASE_SERVER;
	$username = DATABASE_USER_ONE;
  	$password = DATABASE_PASSWORD_ONE;

$econ=mysqli_connect($servername,$username, $password ,DATABASE_ECONTHEN_PORTAL)or die(mysqli_error($econ));
$greatval_4p_conn=mysqli_connect($servername, $username, $password, DATABASE_GREATVAL_INVENTORY_4P)or die(mysqli_error($greatval_4p_conn));
$reports=mysqli_connect($servername,$username, $password ,DATABASE_REPORTS)or die(mysqli_error($reports));
$notify_conn=mysqli_connect(DATABASE_SERVER,DATABASE_USER_ONE,DATABASE_PASSWORD_ONE,DATABASE_NOTIFY_DASHBOARD) or die(mysqli_error($notify_conn));
$price_mgt_conn=mysqli_connect($servername,$username, $password , DATABASE_PRICE_MGMT);
$notions = mysqli_connect(DATABASE_SERVER,DATABASE_USER_ONE,DATABASE_PASSWORD_ONE,DATABASE_FCSUSDBADMIN_NOTIONS_DROPSHIP) or die(mysqli_error($notions));
$morris_hw = mysqli_connect(DATABASE_SERVER,DATABASE_USER_ONE,DATABASE_PASSWORD_ONE,DATABASE_GREATVAL_MORRIS_HW) or die(mysqli_error($morris_hw));
$price_app = mysqli_connect(DATABASE_SERVER,DATABASE_USER_ONE,DATABASE_PASSWORD_ONE,DATABASE_PRICE_APPROVAL) or die(mysqli_error($price_app));

$curr_file_path = __FILE__;
$cur_day_time = date("Y-m-d H:i:s");
$script_name = '';

$get_details = mysqli_query($notify_conn, "select report_name, responsible, link_to_report_onedrive, supervisor from `script_details_dashboard` where cron_path='$curr_file_path'");
if (!$get_details) {
    $ins_alert = "Insert into alert_success_error_dashboard(script_name,link_to_onedrive, report_time, responsible, action, error_msg)
    values('Bonanza HW Price and Inventory Update','','$cur_day_time','','Issue','Issue with script_details_dashboard table')";
    $ins_query = mysqli_query($notify_conn, $ins_alert);
exit;
}
while ($get_row = mysqli_fetch_array($get_details))
{
    $script_name = trim($get_row['report_name']);
    $responsible = trim($get_row['responsible']);
    $main_link_to_onedrive = trim($get_row['link_to_report_onedrive']);
    $supervisor = trim($get_row['supervisor']);
}
if ($script_name == '') {
    $ins_alert = "Insert into alert_success_error_dashboard(script_name,link_to_onedrive, report_time, responsible, action, error_msg)
    values('Bonanza HW Price and Inventory Update','','$cur_day_time','$responsible','Issue',
    'Script name not found')";
    $ins_query = mysqli_query($notify_conn, $ins_alert);
    echo 'Script name not found';
    exit;
}

$ins_alert = "Insert into alert_success_error_dashboard(script_name,link_to_onedrive, report_time, responsible, action,supervisor,error_msg)
values('$script_name','$main_link_to_onedrive','$cur_day_time','$responsible','Issue','$supervisor',
'Unexpected error occured')";
$ins_query = mysqli_query($notify_conn, $ins_alert);
$alert_id = $notify_conn->insert_id;

$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log, alert_id)
values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
'Bonanza HW Price and Inventory Update script has started','$alert_id')");

$reports->query("insert into gvs_scripts_execution_log(script_name,start_on)
values('Inventory and Price Update Bonanza HW',NOW())");
$last_id = $reports->insert_id;

$to_emails = array();
$cc_emails = array();
//182
$sql = "select * from fcsus_scripts_details where id='182'";
$result = mysqli_query($reports, $sql);
while ($row = mysqli_fetch_array($result))
{
		$toemails = explode(",", $row['to_emails']);
		$ccemails = explode(",", $row['cc_emails']);
}

foreach ($toemails as $value)
{
		$email = explode('@', $value);
$to_emails[substr_replace($email[0], "", -1) ] = $value;

}
foreach ($ccemails as $value)
{
		$email = explode('@', $value);
		$cc_emails[substr_replace($email[0], "", -1) ] = $value;

}




$inv_arr=$db_data=$all_inv_arr=$inv_price_new_bonanza_data=$inv_old_price_bonanza_data=$_current_quantity=array();
$final_price=$_current_price=$null_sheet_price=$null_sheet_qty=$inv_qty_new_bonanza_data=$inv_old_qty_bonanza_data=array();
$b2b_skus=$b2c_skus=$price_updates_on_marketplaces=$min_price=$max_price=$_ec_all_listing=$_hw_all_listing=$new_updated_skus=array();

//$reports--- insert into bonanza_hw_all_listing_report------------------------------//
// $query_array=array();
// if (($handle = fopen('files_to_compare/listings.csv', "r")) !== FALSE)
//   {
//       while (($datas = fgetcsv($handle, 1000, ",")) !== FALSE)
//           {
//               $sku=$datas[0];
//               $qty=$datas[1];
//               $price=str_replace("$","",$datas[2]);
//               if($sku!="Identifier")
//               $query_array[] = "('" . $sku . "','" . $qty . "','" . $price . "')";
//             }
//             $del_query=mysqli_query($reports,"Delete from bonanza_hw_all_listing_report");
// echo "reached insert into bonanza_hw_all_listing_report\r\n";
  //           $ins = "INSERT INTO bonanza_hw_all_listing_report VALUES ";
  //           $ins .= implode(',', $query_array);
  //           //   echo $ins;
  //           $ins_query=mysqli_query($reports,$ins) or die(mysqli_error($reports));
  //           echo "<br>Bonanza HW Insert completed";
  // }


	$query_array=array();
	if(($handles = fopen('files_to_compare/listings.csv', "r")) !== FALSE)
	  {
	      while (($data = fgetcsv($handles, 1000, ",")) !== FALSE)
	          {
	                          $data_from_file []=$data[0];
	            }

	        }


	        foreach($data_from_file as $vals){
	          $values=explode("\t",$vals);
	          $sku=trim($values[0]);
	          $qty=trim($values[1]);

	          $price=trim($values[2]);
	          $itemid=trim($values[3]);
	          //echo $sku."_".$qty."<br>";
	          if($sku!="Identifier")
	          $query_array[] = "('" . $sku . "','" . $qty . "','" . $price . "','" . $itemid . "')";
	        }

					$del_query=mysqli_query($reports,"Delete from bonanza_hw_all_listing_report");
					if($del_query)
					$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log, alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
					'Delete values from bonanza_hw_all_listing_report table','$alert_id')");



					$ins = "INSERT INTO bonanza_hw_all_listing_report (Identifier,Quantity,Price,Itemid)VALUES ";
					$ins .= implode(',', $query_array);
					//   echo $ins;
					$ins_query=mysqli_query($reports,$ins) or die(mysqli_error($reports));
					if($ins_query)
					$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log, alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
					'Insert listing.csv file values into bonanza_hw_all_listing_report table','$alert_id')");

					echo "<br>Bonanza hw Insert completed";

////////////////////////////////////////////////////////

//bonanza db quantity check tables

$sql="SELECT  sku,qt  FROM  4p_inventory
where sku LIKE '%NM01%' OR sku LIKE '%LM01%' OR sku LIKE '%KW01%' OR sku LIKE '%ES01%'";
$result=mysqli_query($econ,$sql);

while($row=mysqli_fetch_array($result))
{

	$_current_quantity[$row['sku']]=$row['qt'];

}


$sql="SELECT  sku, qty FROM  `buy_season_inv`
WHERE sku LIKE 'WI01%' ";
$result=mysqli_query($econ,$sql);

while($row=mysqli_fetch_array($result))
{

	$_current_quantity[$row['sku']]=$row['qty'];

}

$sql="SELECT  sku, stock FROM  `prevuepet_op`
where sku LIKE 'PV01%' ";
$result=mysqli_query($econ,$sql);

while($row=mysqli_fetch_array($result))
{

	$_current_quantity[$row['sku']]=$row['stock'];

}

$sql="SELECT  sku, in_stock FROM  `bosspetedge_op`
WHERE sku LIKE 'BP01%' ";
$result=mysqli_query($econ,$sql);

while($row=mysqli_fetch_array($result))
{

	$_current_quantity[$row['sku']]=$row['in_stock'];

}


$sql="SELECT  sku, current_count, amz_inv_current_count   FROM  sd300_notinv_inv
where sku LIKE '%NM01%' OR sku LIKE '%LM01%' OR sku LIKE '%KW01%' OR sku LIKE '%ES01%'";
$result=mysqli_query($notions,$sql);
$k=0;
while($row=mysqli_fetch_array($result))
{

	if(strpos($row['sku'],"NM01")!==FALSE){
		if(strpos($row['sku'],"_b2b")!==FALSE){}
		else	{
			$sk=explode("_", $row['sku']);
			$_current_quantity[$sk[0]]=$row['amz_inv_current_count'];
		}
	}else if(strpos($row['sku'],"KW01")!==FALSE){
		if(strpos($row['sku'],"_b2b")!==FALSE){}
		else
			$_current_quantity[$row['sku']]=$row['amz_inv_current_count'];
	}
	else if(strpos($row['sku'],"ES01")!==FALSE){
		if(strpos($row['sku'],"_b2b")!==FALSE){}
		else
			$_current_quantity[$row['sku']]=$row['amz_inv_current_count'];
	}
	else if(strpos($row['sku'],"LM01")!==FALSE){
		if(strpos($row['sku'],"_b2b")!==FALSE){}
		else
			$_current_quantity[$row['sku']]=$row['current_count'];
	}


}


//price from ec_all_listing table
$sql="SELECT  seller_sku as sku, price  FROM  ec_all_listing";
$result=mysqli_query($reports,$sql);

while($row=mysqli_fetch_array($result))
{

	$_ec_all_listing[$row['sku']]=$row['price'];

}

//price from hw_all_listing table
$sql="SELECT  seller_sku as sku, price  FROM  hw_all_listing";
$result=mysqli_query($reports,$sql);

while($row=mysqli_fetch_array($result))
{

	$_hw_all_listing[$row['sku']]=$row['price'];

}



	$sql="SELECT * FROM  price_rule_stores WHERE store='bonanza_hw' AND sku_type='b2b'";
$result=mysqli_query($price_mgt_conn,$sql);

while($row=mysqli_fetch_array($result))
	{
		if($row['rule_percentage'] == '')
		{
			$row['rule_percentage']=0;
		}
		$rule_percentage_b2b= $row['rule_percentage'];
		$add_sub_b2b= $row['add_subtract'];
		$amz_store1_b2b= array('store'=>$row['amazon_store1'], 'prefix'=>$row['sku_prefix1']);
		$amz_store2_b2b= array('store'=>$row['amazon_store2'], 'prefix'=>$row['sku_prefix2']);
		if($add_sub_b2b == 0){
		$sym_b2b= -1;
		}else {
		$sym_b2b= 1;
		}

	}


	$sql="SELECT * FROM  price_rule_stores WHERE store='bonanza_hw' AND sku_type='b2c'";
	$result=mysqli_query($price_mgt_conn,$sql);

	while($row=mysqli_fetch_array($result))
		{
			if($row['rule_percentage'] == '')
			{
				$row['rule_percentage']=0;
			}
			$rule_percentage_b2c= $row['rule_percentage'];
			$add_sub_b2c= $row['add_subtract'];

			$amz_store1_b2c= array('store'=>$row['amazon_store1'], 'prefix'=>$row['sku_prefix1']);
			$amz_store2_b2c= array('store'=>$row['amazon_store2'], 'prefix'=>$row['sku_prefix2']);

			if($add_sub_b2c == 0){
			$sym_b2c= -1;
			}else {
			$sym_b2c= 1;
			}

		}

$sql="select sku,Our_final_price,Minimum_price,Maximum_price from leemarpet_fbm_new";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];
	}

$sql="select sku,Our_final_price,Minimum_price,Maximum_price from notions_sd300_fbm_new";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];

	}

$sql="select sku,Our_final_price,Minimum_price,Maximum_price from Essential_fbm ";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];

	}

$sql="select sku,Our_final_price,Minimum_price,Maximum_price from buy_season_bonanza_new ";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];

	}
	
	$sql="select sku,Our_final_price,Minimum_price,Maximum_price from bosspetedge_bonanza ";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];

	}
	
	
	$sql="SELECT sku,Our_final_price,Minimum_price,Maximum_price FROM prevuepet_bonanza";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
		$final_price[$row['sku']]=$row['Our_final_price'];
		$b2c_skus[$row['sku']] =$row['sku'];

	}

$sql="select sku,Minimum_price,Maximum_price,Our_final_price from KW01_bonanza";
$result=mysqli_query($notions,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Minimum_price'];
		$max_price[$row['sku']]=$row['Maximum_price'];
			$final_price[$row['sku']]=$row['Our_final_price'];
			$b2c_skus[$row['sku']] =$row['sku'];

	}


$sql="select our_productID,Our_final_price,Minimum_price,Maximum_price from morris_bonanza";
$result=mysqli_query($morris_hw,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['our_productID']]=$row['Minimum_price'];
		$max_price[$row['our_productID']]=$row['Maximum_price'];
			$final_price[$row['our_productID']]=$row['Our_final_price'];
	}

$sql="select sku,final_price_fbm,Min_price_fbm, Max_price_fbm from all_price_approval_new ";
$result=mysqli_query($price_app,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Min_price_fbm'];
		$max_price[$row['sku']]=$row['Max_price_fbm'];

			$final_price[$row['sku']]=$row['final_price_fbm'];
	}

$sql="select sku,final_price_fbm,Min_price_fbm, Max_price_fbm from all_price_approval_NM01_new";
$result=mysqli_query($price_app,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Min_price_fbm'];
		$max_price[$row['sku']]=$row['Max_price_fbm'];
		$final_price[$row['sku']]=$row['final_price_fbm'];
	}


$sql="select sku,final_price_fbm,Min_price_fbm, Max_price_fbm from all_price_PET_b2b ";
$result=mysqli_query($price_app,$sql);

while($row=mysqli_fetch_array($result))
	{
		$min_price[$row['sku']]=$row['Min_price_fbm'];
		$max_price[$row['sku']]=$row['Max_price_fbm'];
			$final_price[$row['sku']]=$row['final_price_fbm'];
			$b2b_skus[$row['sku']]=$row['sku'];
	}

//check sku for b2b or not (consider price_approval.all_price_PET_b2b)

	$sql="select sku from product_master_catalog ";
$result=mysqli_query($price_app,$sql);

while($row=mysqli_fetch_array($result))
	{
		$b2b_skus[$row['sku']]=$row['sku'];
	}


$sql="select sku from product_master_catalog_NM01 ";
$result=mysqli_query($price_app,$sql);

while($row=mysqli_fetch_array($result))
	{

		$b2b_skus[$row['sku']]=$row['sku'];
	}

//check sku for b2b or not end
$sql="SELECT sku, price,price_band_override, as_per_rule FROM  price_updates_on_marketplaces WHERE store='bonanza_hw' AND as_per_rule=0";
$result=mysqli_query($price_mgt_conn,$sql);
while($row=mysqli_fetch_array($result))
{
	$price_updates_on_marketplaces[$row['sku']]=array('price'=>$row['price'], 'price_band_override'=> $row['price_band_override']);
}




mysqli_query($greatval_4p_conn,"delete from inv_compare_bonanza");


	try
	{

		$estTime = (new DateTime('America/New_York'))->format('H');
		$est =new DateTime('America/New_York');

        $day=$est->format('l');
		$hour= $est->format('H');
		$EST= FALSE;
		$Filepath='files_to_compare/listings.csv';


		$Spreadsheet = new SpreadsheetReader($Filepath);
		$BaseMem = memory_get_usage();

		$Sheets = $Spreadsheet -> Sheets();

		foreach ($Sheets as $Index => $Name)
		{
			$Spreadsheet -> ChangeSheet($Index);
			$is_first_row=0;
			foreach ($Spreadsheet as $Key => $Row)
			{

				if ($is_first_row==0)
				{
					$is_first_row=1;
					continue;
				}

				$all_inv_arr[]=$Row;



			}
		}

foreach($all_inv_arr as $price_rec)
{
	$price_rec[2]=str_replace(array("$",","),array("",""),$price_rec[2]);
	$is_price_found=$price_diff=$is_qty_found=$qty_diff=0;
  $is_current_price=0;
	$_sku=$price_rec[0];
	$sku=$price_rec[0];
	$item_id=$price_rec[3];

	if(strpos($sku,"NM01")!==FALSE){
		$sk=explode("_", $sku);
		$sku=$sk[0];
	}
    $prev_qty= $new_quantity=$price_rec[1];
    $prev_price=$new_price=$price_rec[2];

	$sku_prefix=substr($sku, 0, 4);
	if(strpos($sku, '_b2b') !== false)
	{
		$sku_prefix= $sku_prefix."_b2b";
	}

	if(array_key_exists($sku, $b2b_skus))
    {
		if( strpos($amz_store1_b2b['prefix'], $sku_prefix) !== false)
		{
			$amz_cp_data= get_amz_current_price_using_db_storeName($amz_store1_b2b['store'], $_ec_all_listing, $_hw_all_listing);

			$l1_data= get_store_data_using_db_storeName($amz_store1_b2b['store'], $ec_l1_data, $hw_l1_data);

			if(array_key_exists($sku, $amz_cp_data))
			{
				if($amz_cp_data[$sku] !== '')
				{
					$is_current_price=1;
					$_current_price[$sku]= round($amz_cp_data[$sku] + ($amz_cp_data[$sku]*($rule_percentage_b2b/100)* $sym_b2b), 2);
				}
			}
			if($is_current_price == 0 )
			{
				if(array_key_exists($sku, $l1_data))
					{
						if($l1_data[$sku]['l1_price'] !== '')
						{
							$_current_price[$sku]= $l1_data[$sku]['l1_price'];
						}
					}
			}
		}else if( strpos($amz_store2_b2b['prefix'], $sku_prefix) !== false)
		{
			$amz_cp_data= get_amz_current_price_using_db_storeName($amz_store1_b2b['store'], $_ec_all_listing, $_hw_all_listing);

			$l1_data= get_store_data_using_db_storeName($amz_store2_b2b['store'], $ec_l1_data, $hw_l1_data);

			if(array_key_exists($sku, $amz_cp_data))
			{
				if($amz_cp_data[$sku] !== '')
				{
					$is_current_price=1;
					$_current_price[$sku]= round($amz_cp_data[$sku] + ($amz_cp_data[$sku]*($rule_percentage_b2b/100)* $sym_b2b),2);
				}
			}
			if($is_current_price == 0 )
			{
				if(array_key_exists($sku, $l1_data))
					{
						if($l1_data[$sku]['l1_price'] !== '')
						{
							$_current_price[$sku]= $l1_data[$sku]['l1_price'];
						}
					}
			}
		}
	}
	else if(array_key_exists($sku, $b2c_skus))
    {
		if( strpos($amz_store1_b2c['prefix'], $sku_prefix) !== false)
		{
			$amz_cp_data= get_amz_current_price_using_db_storeName($amz_store1_b2c['store'], $_ec_all_listing, $_hw_all_listing);

			$l1_data= get_store_data_using_db_storeName($amz_store1_b2c['store'], $ec_l1_data, $hw_l1_data);

			if(array_key_exists($sku, $amz_cp_data))
			{
				if($amz_cp_data[$sku] !== '')
				{
					$is_current_price=1;
					$_current_price[$sku]= round($amz_cp_data[$sku] + ($amz_cp_data[$sku]*($rule_percentage_b2c/100)* $sym_b2c), 2);
				}
			}
			if($is_current_price == 0 )
			{
				if(array_key_exists($sku, $l1_data))
					{
						if($l1_data[$sku]['l1_price'] !== '')
						{
							$_current_price[$sku]= $l1_data[$sku]['l1_price'];
						}
					}
			}
		}else if( strpos($amz_store2_b2c['prefix'], $sku_prefix) !== false)
			{
				$amz_cp_data= get_amz_current_price_using_db_storeName($amz_store1_b2c['store'], $_ec_all_listing, $_hw_all_listing);

				$l1_data= get_store_data_using_db_storeName($amz_store2_b2c['store'], $ec_l1_data, $hw_l1_data);

				if(array_key_exists($sku, $amz_cp_data))
				{
					if($amz_cp_data[$sku] !== '')
					{
						$is_current_price=1;
						$_current_price[$sku]= round($amz_cp_data[$sku] + ($amz_cp_data[$sku]*($rule_percentage_b2c/100)* $sym_b2c), 2);
					}
				}
				if($is_current_price == 0 )
				{
					if(array_key_exists($sku, $l1_data))
						{
							if($l1_data[$sku]['l1_price'] !== '')
							{
								$_current_price[$sku]= $l1_data[$sku]['l1_price'];
							}
						}
				}
			}

	}

if(array_key_exists($sku, $price_updates_on_marketplaces))
{
	$is_price_found=1;
	if($price_updates_on_marketplaces[$sku]['price_band_override'] == 0)
	{
		if(array_key_exists($sku, $min_price))
			{
				if($price_updates_on_marketplaces[$sku]['price'] < $min_price[$sku])
				{

					$price_updates_on_marketplaces[$sku]['price']=$min_price[$sku];
				}

			}
		if(array_key_exists($sku, $max_price))
			{
				if($price_updates_on_marketplaces[$sku]['price'] > $max_price[$sku]){

					$price_updates_on_marketplaces[$sku]['price']=$max_price[$sku];
				}

			}
	}
	if($price_rec[2] != $price_updates_on_marketplaces[$sku]['price'])
	{
		$price_diff=1;
		$prev_price=$new_price=$price_updates_on_marketplaces[$sku]['price'];
	}

}else{

	if(array_key_exists($sku, $_current_price))
    {
        $is_price_found=1;

		if(array_key_exists($sku, $min_price))
			{
				if($_current_price[$sku] < $min_price[$sku])
				{

					$_current_price[$sku]=$min_price[$sku];
				}

			}
		if(array_key_exists($sku, $max_price))
			{
				if($_current_price[$sku] > $max_price[$sku]){

					$_current_price[$sku]=$max_price[$sku];
				}

			}

        if($price_rec[2] != $_current_price[$sku])
        {
            $price_diff=1;
            $prev_price=$new_price=$_current_price[$sku];
        }


    }else{

		if(array_key_exists($sku, $final_price))
		{
			$is_price_found=1;

			if($price_rec[2] != $final_price[$sku])
			{
				$price_diff=1;
				$prev_price=$new_price=$final_price[$sku];
			}
		}
    }
}
	if(array_key_exists($sku, $_current_quantity))
    {
        $is_qty_found=1;

            if($_current_quantity[$sku] < 0)
            {
                $_current_quantity[$sku]=0;
            }

        if($price_rec[1] != $_current_quantity[$sku])
        {
            $qty_diff=1;
            $prev_qty=$new_quantity=$_current_quantity[$sku];
        }


    }else{
        if(strpos($sku,"_b2b")!==FALSE)
            {
                $_sku= substr($sku, 0, strpos($sku, "_"));
                if(strpos($sku, "_b2b_") !== FALSE)
                {
                    $_sku= substr($sku, 0, strpos($sku, "_")).'_b2b';
                }


                    if(array_key_exists($_sku, $_current_quantity))
                    {
                        $is_qty_found=1;
						if($_current_quantity[$_sku] < 0)
						{
							$_current_quantity[$_sku]=0;
						}
                        if($price_rec[1] != $_current_quantity[$_sku])
                        {
                            $qty_diff=1;
                            $prev_qty=$new_quantity=$_current_quantity[$_sku];
                        }

                    }
            }else
            {
                if((strpos($sku,"_")!==FALSE))
                {
                    $_sku= substr($sku, 0, strpos($sku, "_"));
                    if(array_key_exists($_sku, $_current_quantity))
                    {
                        $is_qty_found=1;
						if($_current_quantity[$_sku] < 0)
						{
							$_current_quantity[$_sku]=0;
						}
                        if($price_rec[1] != $_current_quantity[$_sku])
                        {
                            $qty_diff=1;
                            $prev_qty=$new_quantity=$_current_quantity[$_sku];
                        }

                    }
                }

            }

    }

    if($is_price_found === 1)
    {
        if($price_diff === 1)
        {
            $inv_price_new_bonanza_data[]=array('Identifier'=> $_sku, 'Price'=>$new_price, 'Force_Update'=> 'TRUE');

			if(array_key_exists($sku, $null_sheet_price) ||  array_key_exists($sku, $null_sheet_qty))
			{

			}else{
				$combined_bonanza_data[$_sku]=array('Identifier'=> $_sku, 'Quantity'=>$_current_quantity[$sku], 'Price'=>$new_price, 'Force_Update'=>'TRUE');
				$update[] = array("sku" => $_sku,"quantity" => $_current_quantity[$sku], "price" => $new_price, "item_id"=>$item_id);

			}
        }

    }else{
        $inv_old_price_bonanza_data[]=array('sku'=> $_sku, 'previous price'=>$prev_price, 'new price'=> '');
		$null_sheet_price[$_sku]=array('Identifier'=> $_sku, 'Quantity'=> $prev_qty, 'Price'=>$prev_price);
    }


	if($is_qty_found === 1)
	{
		if($qty_diff === 1)
		{
			$inv_qty_new_bonanza_data[]=array('Identifier'=> $_sku, 'Quantity'=> $_current_quantity[$sku], 'Force_Update'=>'TRUE' );

			if(array_key_exists($sku, $null_sheet_price) ||  array_key_exists($sku, $null_sheet_qty))
			{

			}else{
				$combined_bonanza_data[$_sku]=array('Identifier'=> $_sku, 'Quantity'=> $_current_quantity[$sku], 'Price'=>$new_price, 'Force_Update'=>'TRUE');
        		$update[] = array("sku" => $_sku,"quantity" => $_current_quantity[$sku], "item_id"=>$item_id, "price" => $new_price);


			}

		}

	}else{
		$inv_old_qty_bonanza_data[]=array('sku'=> $_sku, 'previous qty'=>$prev_qty, 'new qty'=> '');
		$null_sheet_qty[$_sku]=array('Identifier'=> $_sku, 'Quantity'=> $prev_qty, 'Price'=>$prev_price);
	}

	$k++;

	$data[]="('$k','".$_sku."','".$price_rec[1]."','".$new_quantity."','".$price_rec[2]."','".$new_price."')";
}
echo "reached insert into inv_compare_bonanza\r\n";
$sql="insert into inv_compare_bonanza values".implode(",",$data);
mysqli_query($greatval_4p_conn,$sql) or die(mysqli_error($greatval_4p_conn));
echo count($data);


		if(count($inv_price_new_bonanza_data) <= 0)
		{
			$inv_price_new_bonanza_data[]=array('sku'=> '', 'previous price'=>'', 'new price'=> '');
		}
        if(count($inv_old_price_bonanza_data) <= 0)
		{
			$inv_old_price_bonanza_data[]=array('sku'=> '', 'previous price'=>'', 'new price'=> '');
		}


            $file[]=generate_file($inv_old_price_bonanza_data, 'price_null_bon_new_'.date("Y_m_d_H_i_s"));

		if(count($inv_qty_new_bonanza_data) <= 0)
		{
			$inv_qty_new_bonanza_data[]=array('sku'=> '', 'previous qty'=>'', 'new qty'=> '');
		}
		if(count($inv_old_qty_bonanza_data) <= 0)
		{
			$inv_old_qty_bonanza_data[]=array('sku'=> '', 'previous qty'=>'', 'new qty'=> '');
		}

		$chunks = array_chunk($update, 99);
echo "api started";
		foreach($chunks as $sku_list) {
		$args=$updates=array();
		foreach($sku_list as $sku_rec) {
			$updates[$sku_rec['item_id']]=array("quantity"=>$sku_rec['quantity'],"price"=>$sku_rec['price']);
			}
			$args = array("updates" => $updates);

		    $args["requesterCredentials"]["bonanzleAuthToken"] = $token;
		    $post_fields = "updateInventory=" .  urlencode(json_encode($args));

		    $connection = curl_init($url);
		    $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
		                    CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
		    curl_setopt_array($connection, $curl_options);
		    $json_response = curl_exec($connection);
		    if (curl_errno($connection) > 0) {
		      echo curl_error($connection) . "\n";
		      exit(2);
		    }
		    curl_close($connection);

			}
echo "api completed";
		if(count($combined_bonanza_data) > 48000)
		{
			$i=0;
			foreach(array_chunk($combined_bonanza_data, 48000) as $sku ) {
				$i++;
				$new_updated_skus=array();
				foreach($sku as $sku_rec) {

					$new_updated_skus[]=$sku_rec;
				}
				$file[]=generate_file($new_updated_skus, 'Bonanza_HW_price_update_template'.$i."_".date("Y_m_d_H_i_s"));
			}
		}


			$file[]=generate_file($inv_old_qty_bonanza_data, 'inv_null_bon_new_'.date("Y_m_d_H_i_s"));



			$file[]=generate_file($combined_bonanza_data, 'Bonanza_HW_price_inventory_update_template_'.date("Y_m_d_H_i_s"), array( 'Identifier', 'Quantity', 'Price', 'Force_Update'));


			print_r($file);
//email
$mail = new PHPMailer(true);
try
  {
      //Server settings
      $mail->isSMTP();
      $mail->SMTPAuth = true;
      $mail->Host = EMAIL_HOST;
      $mail->Username = EMAIL_USERNAME;

      $mail->Password =EMAIL_PASSWORD;
      $mail->SMTPSecure = 'tls';
      $mail->Port = EMAIL_PORT;

      $email_set_from = EMAIL_SET_FROM;
      $mail->setFrom($email_set_from, 'Mailer');
			if(is_array($file))
			{
				foreach ($file as $file_rec) {
					$mail->AddAttachment(  $file_rec );
				}
			}else{
				$mail->AddAttachment($file);
			}

      foreach($to_emails as $key => $email)
                     {
                         $mail->addAddress($email, $key);
                     }

                 foreach($cc_emails as $key => $email)
                     {
                         $mail->AddCC($email, $key);
                     }

       $mail->isHTML(true);                                  // Set email format to HTML
      $mail->Subject = 'Bonanza HW Price & Inventory';
      $mail->Body = "Hi,<br> PFA. ";
      $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

      $mail->send();
      $notify_conn->query("insert into script_execution(script_name,execution_time,execution_log, alert_id)
      values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
      'Mail has been sent to respective users','$alert_id')");

      echo 'Message has been sent';
  } catch (Exception $e) {
      echo 'Message could not be sent.'.$e;
}

			upload_file($file,$notify_conn,$main_link_to_onedrive,$script_name,$alert_id);

	}
	catch (Exception $E)
	{
		echo $E->getMessage();
	}


function upload_file($file,$notify_conn,$main_link_to_onedrive,$script_name,$alert_id){
//upload to one drive
$email_array='';
	$p = getcwd()."/all_upload_reports";
	$file_k_count=0;
	$foldername = $main_link_to_onedrive;
	foreach($file as $filer){
		$filer=trim(str_replace("all_upload_reports/","",$filer));
		$email_array.=$main_link_to_onedrive."/".$filer.",";
echo "python ../../python_scripts/upload_file_onedrive.py $p $foldername $filer";
	$command1 = escapeshellcmd("python ../../python_scripts/upload_file_onedrive.py $p $foldername $filer");
	$output1 = shell_exec($command1);
	echo $output1;
unlink("all_upload_reports/".$filer);
	if(trim($output1) == 'done'){
	    $notify_conn->query("insert into script_execution(script_name,execution_time,execution_log,alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "','Uploaded file $filer in onedrive Successfully','$alert_id')");

	$file_k_count++;
	}else{
	$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log,alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "','Unable to upload file $filer in onedrive folder','$alert_id')");
	$q2 = "UPDATE alert_success_error_dashboard SET error_msg = 'Unable to upload file in onedrive', action = 'Issue' WHERE id = '$alert_id'";
	$succ_query = mysqli_query($notify_conn, $q2);
   	}
	}//foreach
	if($file_k_count >1){
		$link_to_onedrive=$email_array;
	$q2 = "UPDATE alert_success_error_dashboard SET
	success_msg = 'Successfully Uploaded file to one drive ', action = 'No Action Needed', link_to_onedrive = '$link_to_onedrive', error_msg = '' WHERE id = '$alert_id'";
	$succ_query = mysqli_query($notify_conn, $q2);
	}
	else
	{
	  $q2 = "UPDATE alert_success_error_dashboard SET
	   error_msg = 'Unable to upload file in onedrive',
	   action = 'Issue' WHERE id = '$alert_id'";
	  $succ_query = mysqli_query($notify_conn, $q2);
	}
	$foldertocheck=$main_link_to_onedrive;
	if ($foldertocheck != '')
	{
			$command1 = escapeshellcmd("python ../../python_scripts/delete_file_onedrive_thirty.py $foldertocheck");
			$output1 = shell_exec($command1);
			if(trim($output1) == 'done'){
					$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log,alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
					'Deleted data from onedrive above 30 days','$alert_id')");
			}else{
			$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log,alert_id) values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
			'Unable to delete onedrive folder','$alert_id')");
			}
	}

	// delete data in execution log
	$del_data = "Delete from script_execution  WHERE DATEDIFF(CURRENT_DATE, execution_time) > 30 and script_name ='$script_name' ";
	$del = $notify_conn->query($del_data);
	if ($del)
		$notify_conn->query("insert into script_execution(script_name,execution_time,execution_log,alert_id)
			values('$script_name','" . date('Y-m-d H:i:s', time()) . "','Deleted data from log table above 30 days','$alert_id')");

}


	function generate_file($final_array, $name, $header='')
	{
		$file='all_upload_reports/'.$name.'.csv';
		$fp = fopen($file, 'w');

		if($header != '')
		{
			$array_columns=$header;
		}else{
			$array_columns=array_keys($final_array[0]);
		}

		fputcsv($fp, $array_columns);
		if(count($final_array) > 1)
		{
			foreach ($final_array as $row) {
					fputcsv($fp, $row);
			}
		}



		// close the file
		fclose($fp);
		return $file;
	}


	function curl_file_download()
		{
			 $dest_files=array(array('url' => 'https://greatvaluestores.com/applications/amazon/generate_ec_hw_l1_reports/ec_l1.csv',
																'file'=>'ec_l1.csv'),
												array('url' => 'https://greatvaluestores.com/applications/amazon/generate_ec_hw_l1_reports/hw_l1.csv',
												'file'=>'hw_l1.csv'));
				foreach( $dest_files as $file_rec)
				{

			$url=$file_rec['url'];
			$return = array();
			$dest = 'files_to_compare/'.$file_rec['file'];
			unlink($dest);
			$fp = fopen ($dest, 'w+');
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 50);
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			$response = curl_exec($ch);

			$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
			curl_close($ch);
			fclose($fp);
		}


		}

	function get_l1price_skus_list($sourcefile)
	{
		$totalskus=array();
		$srcFile = fopen($sourcefile, "r");

		// build a list of all of the sku's in L1 File
		if (($srcFile = fopen($sourcefile, "r")) !== false) {
			$columns = fgetcsv($srcFile, 1000, ",");

			while ($rec = fgetcsv($srcFile))
			{
				$totalskus[$rec[0]] = array('amz_price'=>$rec[3], 'l1_price'=>$rec[4]);
			}

		fclose($srcFile);
		}

		return $totalskus;
	}


	function get_store_data_using_db_storeName($store_name, $ec_l1_data, $hw_l1_data)
	{
		if($store_name == 'ec')
		{
			return $ec_l1_data;
		}
		if($store_name == 'hw')
		{
			return $hw_l1_data;
		}
	}


	function get_amz_current_price_using_db_storeName($store_name, $ec_l1_data, $hw_l1_data)
	{
		if($store_name == 'ec')
		{
			return $ec_l1_data;
		}
		if($store_name == 'hw')
		{
			return $hw_l1_data;
		}
	}

$sql_query="UPDATE gvs_scripts_execution_log  set closed_on=NOW() where  id='$last_id' ";
mysqli_query($reports	,$sql_query) ;

$q1="insert into script_execution(script_name,execution_time,execution_log,alert_id)
values('$script_name','" . date('Y-m-d H:i:s', time()) . "',
'Bonanza HW Price & Inventory Update script  has been completed','$alert_id')";
$succ_query = mysqli_query($notify_conn, $q1);



?>
