<?php
session_start();
ini_set('max_execution_time', '0');
date_default_timezone_set('America/New_York');
require('../../../../../shell/gvs_cf.php');
require('sub_db_connection.php');
require('../../../php_plugins/php-excel-reader/excel_reader2.php');
require('../../../php_plugins/SpreadsheetReader/SpreadsheetReader.php');


$reports_conn = mysqli_connect(DATABASE_SERVER, DATABASE_USER_ONE, DATABASE_PASSWORD_ONE, DATABASE_REPORTS) or die(mysqli_error($reports_conn));
$notify_conn = mysqli_connect(DATABASE_SERVER, DATABASE_USER_ONE, DATABASE_PASSWORD_ONE, DATABASE_NOTIFY_DASHBOARD) or die(mysqli_error($notify_conn));

$date = date('Y-m-d H:i:s', time());
$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('Ebay EC Inventory Update','','$cur_day_time','','Issue','Issue with cron_scripts_applications.script_details_dashboard table')";
    $ins_query = mysqli_query($notify_conn, $ins_alert) or die(mysqli_error($notify_conn));
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('Ebay EC Inventory Update','','$cur_day_time','','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) or die(mysqli_error($notify_conn));
$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()) . "','Ebay EC Inventory Update script has been started','$alert_id')");

$reports_conn->query("insert into gvs_scripts_execution_log(script_name,start_on) values('Update Inventory on ebay EC',NOW())");
$last_id = $reports_conn->insert_id;
if (!$last_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()) . "','Unable to connect table Reports.gvs_scripts_execution_log','$alert_id')");
}

if ((($handle = fopen("../../../python_scripts/delete_file_onedrive_thirty.py", "r")) == false) || (($handle = fopen("../../../python_scripts/upload_file_onedrive.py", "r")) == false))
    {
      $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 find python onedrive folder','$alert_id')");
      $q1 = "UPDATE alert_success_error_dashboard SET error_msg = 'Unable to found python onedrive folder', action = 'Issue' WHERE id = '$alert_id'";
      $err_query = mysqli_query($notify_conn, $q1);
      exit;
   }

//date_default_timezone_set('UTC');
	$StartMem = memory_get_usage();

	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='../../ebay_ec/files_to_compare/ActiveInventoryReport.csv';

		$pv_query="SELECT UPPER(CONVERT(sku USING latin1)) AS sku,stock FROM prevuepet_op";
		$db_pv_data=$db->getdata($pv_query);
		if(count($db_pv_data)>0){
	 $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()) . "',
	 'Fetched inventory for PV01 sku from fcsusdbadmin_notions_dropship.prevuepet_op table','$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()) . "',
	 'Couldnt fetch any inventory for PV01 sku from fcsusdbadmin_notions_dropship.prevuepet_op table','$alert_id')");
 }

 $bp_query="SELECT UPPER(CONVERT(sku USING latin1)) AS sku,in_stock FROM bosspetedge_op";
 $db_bp_data=$db->getdata($bp_query);
 if(count($db_bp_data)>0){
$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()) . "',
'Fetched inventory for BP01 sku from fcsusdbadmin_notions_dropship.bosspetedge_op table','$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()) . "',
'Couldnt fetch any inventory for BP01 sku from fcsusdbadmin_notions_dropship.bosspetedge_op table','$alert_id')");
}

		$lm_query="SELECT UPPER(CONVERT(child_sku USING latin1)) AS child_sku,current_count, ebay_inv_update_flag FROM sd300_notinv_inv WHERE child_sku LIKE 'LM01%'";
		$db_lm_data=$db->getdata($lm_query);
		$count_lm=count($db_lm_data);
		   if(count($db_lm_data)>0){
				$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()) . "',
				'Fetched $count_lm inventory for LM01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$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()) . "',
				'Couldnt fetch any inventory for LM01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$alert_id')");
			}

		$kw_query="SELECT UPPER(CONVERT(child_sku USING latin1)) AS child_sku,amz_inv_current_count, ebay_inv_update_flag FROM sd300_notinv_inv WHERE child_sku LIKE 'KW01%'";
		$db_kw_data=$db->getdata($kw_query);

		if(count($db_kw_data)>0){
	 		$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()) . "',
	 		'Fetched inventory for KW01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$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()) . "',
	 	'Couldnt fetch any inventory for KW01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$alert_id')");
	 }

		$es_query="SELECT UPPER(CONVERT(child_sku USING latin1)) AS child_sku,amz_inv_current_count, ebay_inv_update_flag FROM sd300_notinv_inv WHERE child_sku LIKE 'ES01%'";
		$db_es_data=$db->getdata($es_query);

		$count_es=count($db_es_data);
		 if(count($db_es_data)>0){
				$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()) . "',
				'Fetched $count_es inventory for ES01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$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()) . "',
			'Couldnt fetch any inventory for ES01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$alert_id')");
		}

		$final_lm_array=$final_kw_array=$final_array=$filtered_nm_source_data=$limit_array=$total_sheet_array=$compare_qnty=array();
		$lm01_data=array();
		$pv01_data=array();
		$kw01_data=array();
		$es01_data=array();
		$nm01_data=array();
    $bp01_data=array();
		$rem_u_nm_data_with_undrscr='';
		$Spreadsheet = new SpreadsheetReader($Filepath);
		$BaseMem = memory_get_usage();

		$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()) . "',
		'Read ActiveInventoryReport.csv file (downloaded from Ebay EC) ','$alert_id')");

		$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;
					$header[]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => '',
												'ItemID'=> '',
												'*Quantity'=> '');
					continue;
				}

				if(isset($sheet_array[strtoupper($Row[0])]))
				{
					$dup[]=$Row;
				}
				$search='LM01';
				$lm = strpos($Row[0], $search);
				$es=strpos($Row[0], 'ES01');
				$kw=strpos($Row[0], 'KW01');
				$nm=strpos($Row[0], 'NM01');
				$pv=strpos($Row[0], 'PV01');
        $bp=strpos($Row[0], 'BP01');
				$Row[4]= $Row[1]*$Row[2];
				$Row[2]= intval($Row[2]);
				$total_sheet_array[strtoupper($Row[0])]= $Row;
				$sheet_array[strtoupper($Row[0])]= $Row;


				if ($nm !== false)
				{
					$b2b = strpos($Row[0], '_b2b');
					if($b2b !== false)
					{
						continue;
					}

					$nm01_data[$Row[0]]=$Row;
					continue;
				}
				$Row[0]=strtoupper($Row[0]);
				 if ($lm !== false)
				{
					$b2b = strpos($Row[0], '_B2B');
					if($b2b !== false)
					{
						continue;

					}
					$lm01_data[$Row[0]]=$Row;
					continue;
				}else if ($es !== false)
				{
					$es01_data[$Row[0]]=$Row;
					continue;

				}else if ($kw !== false)
				{
					$kw01_data[$Row[0]]=$Row;
					continue;
				}
				else if ($pv !== false)
				{
					$pv01_data[$Row[0]]=$Row;
					continue;
				}
        else if ($bp !== false)
				{
					$bp01_data[$Row[0]]=$Row;
					continue;
				}

			}
		}


				$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()) . "',
				'Fetched NM01,PV01,LM01,KW01,BP01 and ES01 inventory  from ActiveInventoryReport','$alert_id')");

		$EST= TRUE;
		$str="";



		$query="SELECT  UPPER(CONVERT(child_sku USING latin1)) AS sku,amz_inv_current_count,ebay_inv_update_flag FROM sd300_notinv_inv WHERE child_sku LIKE 'NM01%' ";
		$db_nm_data=$db->getdata($query);

		if(count($db_nm_data)>0){
		$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()) . "',
		'Fetch inventory for NM01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$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()) . "',
	'Couldnt fetch any inventory for NM01 sku from fcsusdbadmin_notions_dropship.sd300_notinv_inv table','$alert_id')");
	}
		$nm01_child=array();


		foreach($db_nm_data as $d_nm_rec)
		{
			$total_db_nm_data[$d_nm_rec['sku']]=$d_nm_rec;
			$nm01_child[]=$d_nm_rec['sku'];

		}

		$nm01_file=array();
		foreach($nm01_data as $key => $value){

			$nm01_file[]=$key;

		}
		$not_found_child = array_diff( $nm01_file,$nm01_child);
		foreach($not_found_child as $value){
			unset($nm01_data[$value]);
		}

		$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()) . "',
		'Comparing skus from file with db sku,removing those sku from file which are not in our db ','$alert_id')");

		// if($hour == '9' || $hour == '11'  || $hour == '17'|| $hour == '1'|| $hour == '5'|| $hour == '21'){
			$EST= TRUE;
			$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()) . "',
			'Comparing NM01 skus inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final array','$alert_id')");

		foreach($nm01_data as $nm_rec)
		{

			$u_inv_sku=strtoupper($nm_rec[0]);

			if(isset($total_db_nm_data[$nm_rec[0]]))
			{
				if($total_db_nm_data[$nm_rec[0]]['ebay_inv_update_flag'] == 0)
				{
					$total_db_nm_data[$nm_rec[0]]['amz_inv_current_count']=0;
				}
				$current_count=$total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'];
				if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <= 2)
				{
					$current_count = 0;
				}
				if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 2 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <3)
				{
					$current_count = 0;
				}
				if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 3 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <4)
				{
					$current_count = 1;
				}
				if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 4 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <5)
				{
					$current_count = 2;
				}
				if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 5)
				{
					$current_count = 3;
				}

			}else{
				$nm = strpos($u_inv_sku, '_');
				if($nm !== false)
				{
					$remv_u_nm = substr($nm_rec[0], 0, strpos($nm_rec[0], "_"));
					if(isset($total_db_nm_data[$remv_u_nm]))
					{
							if($total_db_nm_data[$remv_u_nm]['ebay_inv_update_flag'] == 0)
							{
								$total_db_nm_data[$remv_u_nm]['amz_inv_current_count']=0;
							}
							$current_count=intval($total_db_nm_data[$remv_u_nm]['amz_inv_current_count']);

							if($total_db_nm_data[$remv_u_nm]['amz_inv_current_count'] <= 2)
							{
								$current_count = 0;
							}


							if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 2 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <3)
							{
								$current_count = 0;
							}
							if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 3 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <4)
							{
								$current_count = 1;
							}
							if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 4 && $total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] <5)
							{
								$current_count = 2;
							}
							if($total_db_nm_data[$nm_rec[0]]['amz_inv_current_count'] >= 5)
							{
								$current_count = 3;
							}
					}
				}

			}

			if(intval($current_count) !== intval($nm_rec[2]))
			{
				if(isset($total_sheet_array[$u_inv_sku]))
				{
					$total_sheet_array[$u_inv_sku][4] = $current_count*$nm_rec[1];
					$total_sheet_array[$u_inv_sku][2] = $current_count;
				}


				$final_array[$nm_rec[0]]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => 'Revise',
										'ItemID'=> $nm_rec[3],
										'*Quantity'=> $current_count);

			}


		}

// }


		//end --------nm data
		if($day != "Saturday" )
		{
			if($day != "Sunday"){
				// if($hour == '15')         {
					$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()) . "',
					'Comparing LM01 skus from inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final_array','$alert_id')");

					$EST= TRUE;
					foreach($db_lm_data as $db_rec)
					{
						if(isset($lm01_data[$db_rec['child_sku']][0]))
						{
							$sku=$db_rec['child_sku'];
              if($sku=='LM01KT42650')
              echo $sku."<br>";
							if(  $db_rec['child_sku'] == $lm01_data[$sku][0])
							{
                if($sku=='LM01KT42650') echo "reached here1";

								if($db_rec['ebay_inv_update_flag'] == 0)
								{
									$db_rec['current_count']=0;
                  if($sku=='LM01KT42650') echo "reached here2";

								}
								$current_count=0;
                if($db_rec['current_count'] == 1)
								{
									$current_count = 1;
                  if($sku=='LM01KT42650') echo "reached here3";

								}
								if($db_rec['current_count'] >= 2)
								{
									$current_count = 2;
								}
                // if($db_rec['current_count'] >= 3)
								// {
								// 	$current_count = 3;
								// }

								if(intval($current_count) !== intval($lm01_data[$sku][2]))
								{
                  if($sku=='LM01KT42650') echo "reached here4";

									$total_sheet_array[$db_rec['child_sku']][4] = $current_count*$lm01_data[$db_rec['child_sku']][1];
									$total_sheet_array[$db_rec['child_sku']][2] = $current_count;

									$final_array[$db_rec['child_sku']]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => 'Revise',
															'ItemID'=> $lm01_data[$sku][3],
															'*Quantity'=> $current_count);

								}

							}
						}

					}
				}
			}
		// }

		// if($hour == '1' || $hour == '3' || $hour == '5'|| $hour == '7'|| $hour == '9'|| $hour == '11'|| $hour == '13'|| $hour == '15'|| $hour == '17'|| $hour == '19'|| $hour == '21'|| $hour == '23' )			{

					$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()) . "',
					'Comparing PV01 skus from inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final_array','$alert_id')");

					$EST= TRUE;
					foreach($db_pv_data as $db_rec)
					{
						// $db_rec['sku'] = substr($db_rec['sku'], 0, strpos($db_rec['sku'], "_"));

						if(isset($pv01_data[$db_rec['sku']][0]))
						{
							$sku=$db_rec['sku'];
							if($db_rec['sku'] == $pv01_data[$sku][0])
							{
                $current_count =0;
                if($db_rec['stock']==1)
								$current_count =1;
                if($db_rec['stock'] ==2)
								$current_count =2;
                if($db_rec['stock'] >=3)
								$current_count =3;

									$total_sheet_array[$db_rec['sku']][4] = $current_count*$pv01_data[$db_rec['sku']][1];
									$total_sheet_array[$db_rec['sku']][2] = $current_count;

									$final_array[$db_rec['sku']]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => 'Revise',
															'ItemID'=> $pv01_data[$sku][3],
															'*Quantity'=> $current_count);

							}
						}

					}
		// }


		// if($hour == '11' || $hour == '17' || $hour == '01')		{
				$EST= TRUE;
				$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()) . "',
				'Comparing KW01 skus from inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final array','$alert_id')");

				foreach($db_kw_data as $db_rec)
				{

					if(isset($kw01_data[$db_rec['child_sku']][0]))
					{

						if($db_rec['child_sku'] == $kw01_data[$db_rec['child_sku']][0])
						{
							if($db_rec['ebay_inv_update_flag'] == 0)
							{
								$db_rec['amz_inv_current_count']=0;
							}
							$current_count=0;
							if($db_rec['amz_inv_current_count'] == 1)
							{
								$current_count = 1;
							}
              if($db_rec['amz_inv_current_count'] == 2)
              {
                $current_count = 2;
              }
              if($db_rec['amz_inv_current_count'] >= 3)
              {
                $current_count = 3;
              }
							if(intval($current_count) !== intval($kw01_data[$db_rec['child_sku']][2]))
							{
								$total_sheet_array[$db_rec['child_sku']][4] = $current_count*$kw01_data[$db_rec['child_sku']][1];
								$total_sheet_array[$db_rec['child_sku']][2] = $current_count;

								$final_array[$db_rec['child_sku']]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' =>'Revise',
														'ItemID'=> $kw01_data[$db_rec['child_sku']][3],
														'*Quantity'=> $current_count);

							}

						}
					}
				// }




				foreach($db_es_data as $db_rec)				{
					if(isset($es01_data[$db_rec['child_sku']][0]))
					{

						if($db_rec['child_sku'] == $es01_data[$db_rec['child_sku']][0])
						{
							if($db_rec['ebay_inv_update_flag'] == 0)
							{
								$db_rec['amz_inv_current_count']=0;
							}
							$current_count=0;
							if($db_rec['amz_inv_current_count'] == 1)
							{
								$current_count = 1;
							}
              if($db_rec['amz_inv_current_count'] >= 2)
							{
								$current_count = 2;
							}
							if(intval($current_count) !== intval($es01_data[$db_rec['child_sku']][2]))
							{
								$total_sheet_array[$db_rec['child_sku']][4] = $current_count*$es01_data[$db_rec['child_sku']][1];
								$total_sheet_array[$db_rec['child_sku']][2] = $current_count;

								$final_array[$db_rec['child_sku']]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => 'Revise',
														'ItemID'=> $es01_data[$db_rec['child_sku']][3],
														'*Quantity'=> $current_count);

							}
						}
					}
				}
			}

      $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()) . "',
      'Compared ES01 skus from inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final_array','$alert_id')");

      echo "hour:".$hour;
               // if($hour == '12')  {
                 echo "reached 12pm";
          					$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()) . "',
          					'Comparing BP01 skus from inventory from file and newly fetched inventory from db and inserting to total_sheet_array and final_array','$alert_id')");

          					$EST= TRUE;
          					foreach($db_bp_data as $db_rec)
          					{

          						if(isset($bp01_data[$db_rec['sku']][0]))
          						{

          							$sku=$db_rec['sku'];
          							if(  $db_rec['sku'] == $bp01_data[$sku][0])
          							{
                          $current_count =0;
                          if($db_rec['in_stock']==1)
          								$current_count =1;
                          if($db_rec['in_stock']>=2)
          								$current_count =2;
                          // if($db_rec['in_stock']>=3)
                          // $current_count =3;

          									$total_sheet_array[$db_rec['sku']][4] = $current_count*$bp01_data[$db_rec['sku']][1];
          									$total_sheet_array[$db_rec['sku']][2] = $current_count;

          									$final_array[$db_rec['sku']]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' => 'Revise',
          															'ItemID'=> $bp01_data[$sku][3],
          															'*Quantity'=> $current_count);
          							}
          						}

          					}
          		 // }



$_SESSION['final_array_ec']=count($final_array);
		if(count($final_array) <= 0)
		{
			$final_array[] = $header;
			$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()) . "',
			'Final array is empty, inserting only header inside it.','$alert_id')");

		}else{

				$ebay_sheet = array_sum(array_column($sheet_array,4));
				echo("listings limit---->".$ebay_sheet."<pre>");

				$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()) . "',
				'Existing Limit:$ebay_sheet','$alert_id')");

				$t_sheet_price = array_sum(array_column($total_sheet_array,4));
				echo("total limit---->".$t_sheet_price."<pre>");

				$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()) . "',
				'Newly Calculated Limit:$t_sheet_price','$alert_id')");


			$c=0;
				if($t_sheet_price > 3000000)
				{
					$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()) . "',
					'New Limit greater than 3 million,sorting the array','$alert_id')");

					if(isset($total_sheet_array))
					$col = array_column( $total_sheet_array, 4 );
					array_multisort(array_column($total_sheet_array, 2 ), SORT_DESC,
									array_column($total_sheet_array, 4 ), SORT_DESC,
									$total_sheet_array);

					foreach($total_sheet_array as $lmt_rec)
					{

						if( !isset($lmt_rec[0]) )
						{
							continue;
						}

						$nm=strpos($lmt_rec[0], 'NM01');
						if($nm !== false)
						{
							$b2b=strpos($lmt_rec[0], 'b2b');
							if($b2b !== false)
							{
								continue;
							}
							$lmt_rec[0]=strtoupper($lmt_rec[0]);
							if($lmt_rec[2] == 3)
							{
								$total_sheet_array[$lmt_rec[0]][2] = 2;
								$total_sheet_array[$lmt_rec[0]][4] = 2*$lmt_rec[1];
							}else if($lmt_rec[2] == 2)
							{
								$total_sheet_array[$lmt_rec[0]][2] = 1;
								$total_sheet_array[$lmt_rec[0]][4] = 1*$lmt_rec[1];
							}else if($lmt_rec[2] == 1)
							{
								$total_sheet_array[$lmt_rec[0]][2] = 0;
								$total_sheet_array[$lmt_rec[0]][4] = 0;
							}
							$compare_qnty[]= $total_sheet_array[$lmt_rec[0]];


						}else{
							continue;
						}
						$c++;
						if($c>=1000)
						{
              echo "reaced c >1000";

							$c=0;
						$new_value = round(array_sum(array_column($total_sheet_array, 4)), 2);
            $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()) . "',
            'New limit:$new_value, after reducing inventory by 1 for each sku.','$alert_id')");

						if( $new_value < 2900000 )
						{

							foreach($compare_qnty as $c_qnty_rec)
							{
								if( $c_qnty_rec[2] === $sheet_array[$c_qnty_rec[0]][2])
								{
									if(isset($final_array[$c_qnty_rec[0]]))
									{
										unset($final_array[$c_qnty_rec[0]]);
									}

								}else{
									if(isset($final_array[$c_qnty_rec[0]]))
									{
										$final_array[$c_qnty_rec[0]]['*Quantity'] = $c_qnty_rec[2];
									}else{
										$final_array[$c_qnty_rec[0]]=array('*Action(SiteID=US|Country=US|Currency=USD|Version=941)' =>'Revise',
																			'ItemID'=> $c_qnty_rec[3],
																			'*Quantity'=> $c_qnty_rec[2]);
									}
								}

							}
							break;
						}
					}
					}
				}
		}
		echo "new limit-------".$new_value;

		if($EST == TRUE)
		{
		$file="upload_ec_". date("Y_m_d_h_i_s") . ".csv";
    $_SESSION['upload_file_name']=$file;

			$fp = fopen($file, 'w');
			$array_columns=array_keys($header[0]);
			fputcsv($fp, $array_columns);
			foreach ($final_array as $row) {
				fputcsv($fp, $row);
			}
			$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()) . "',
      'Upload.csv created with final_array values','$alert_id')");

			$p = getcwd();
			$foldername = $main_link_to_onedrive;
			//https://back.greatvaluestores.com/python_scripts/upload_file_onedrive.py
			$command1 = escapeshellcmd("python ../../../python_scripts/upload_file_onedrive.py $p $foldername $file");
			$output1 = shell_exec($command1);
			echo $output1;

			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 in onedrive Successfully','$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 upload file 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);
			}
      //uncomment
		include('sub_ec_upload_inv.php');
      if(file_exists("error_log"))
			unlink('error_log');

			// close the file
			fclose($fp);



		}else{
			echo "File not generated due to time zone";
			$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()) . "',
      'No file generated due to time zone.','$alert_id')");

		}

	}
	catch (Exception $E)
	{
		$msg=$E->getMessage();
		echo $msg;
		$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()) . "',
		'Exception Occured:$msg','$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')");

   $foldertocheck = $main_link_to_onedrive;
$del_count=0;
   if ($foldertocheck != '')
   {
       //https://back.greatvaluestores.com/python_scripts/delete_file_onedrive_thirty.py
   		echo "python ../../../python_scripts/delete_file_onedrive_thirty.py $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 files','$alert_id')");
       $q2 = "UPDATE alert_success_error_dashboard SET error_msg = 'Unable to delete file in onedrive', action = 'Issue' WHERE id = '$alert_id'";
       $succ_query = mysqli_query($notify_conn, $q2);
       $del_count++;
       }
   }

	 $link_to_onedrive = $foldername . '/' . $file;
   if($del_count==0){
   $q2 = "UPDATE alert_success_error_dashboard SET success_msg = 'Successfully generated csv file', 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  link_to_onedrive = '$link_to_onedrive'  WHERE id = '$alert_id'";
   $err_query = mysqli_query($notify_conn, $q2);
 }


unlink($file);

$sql_query="UPDATE gvs_scripts_execution_log  set closed_on=NOW() where  id='$last_id' ";
mysqli_query($reports_conn,$sql_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()) . "','Ebay EC inventory update script completed','$alert_id')");


?>
