<?php

class Regular_sync extends CI_Model {


	///////////////////////////////////////////////////////////////////////////
	function strpos_arr_2021_check($haystack, $needle) {
		if(!is_array($needle)) $needle = array($needle);
		foreach($needle as $what) {
			if(($pos = strpos($haystack, $what))!==false) return $pos;
		}
		return false;
	}
	function pc_array_power_set($array) {
		// initialize by adding the empty set
		$results = array(array( ));

		foreach ($array as $element){
			foreach ($results as $combination){
				array_push($results, array_merge(array($element), $combination));
			}
		}
		return $results;
	}
	function do_per_slot_2021_item_check($current_date,$loop){

		$current_directory = getcwd();
		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']=0;
		}

		if($config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']==1){
			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}



			$array_find[]="One piece";
			$array_find[]="One Piece";
			$array_find[]="Tunic";

			$array_find_male_full_shirt[]="Male Full Shirt";
			$array_find_male_half_shirt[]="Male Half Shirt";


			$ospos_sales_items_discount=array();

			$price_combination=array();

			$pcr_challan_check_dis=array();
			$pcr_challan_check_all=array();

			$query = $this->db->query("SELECT a.stock_id,a.lot_no,CAST(a.item_cost_price AS SIGNED) AS item_cost_price,a.discount_percent,a.challan_no,a.loc_code,IF(b.item_size_id> 0,CONCAT(c.description,'</br>',b.description,' - ',d.size),CONCAT(c.description,'</br>',b.description)) AS description,b.gender AS item_gender
			FROM pcr_challan_check AS a
			LEFT JOIN stock_master AS b ON a.stock_id=b.stock_id
			LEFT JOIN stock_category AS c ON b.category_id=c.category_id
			LEFT JOIN pos_item_sizes AS d ON b.item_size_id=d.id 
			WHERE a.discount_percent>0 GROUP BY a.stock_id,a.lot_no,a.item_cost_price,a.discount_percent ORDER BY a.discount_percent DESC,a.item_cost_price DESC");

			foreach ($query->result() as $row) {

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

				$has_add=1;

				if ($this->strpos_arr_2021_check($row->description, $array_find, 1)) {
					if(trim($row->item_gender)=="girl"){
						$row->discount_percent=50;
					}else{
						$row->discount_percent=40;
					}
				}elseif ($this->strpos_arr_2021_check($row->description, $array_find_male_full_shirt, 1)) {
					if($row->item_cost_price<1090){
						$has_add=0;
					}
				}elseif ($this->strpos_arr_2021_check($row->description, $array_find_male_half_shirt, 1)) {
					if($row->item_cost_price>540){
						$has_add=0;
					}
				}
				if($has_add==1){
					////////////////////////////////////////////////////////////////////////////
					$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
					$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
					$pcr_challan_check_dis[$row->stock_id]=intval($row->discount_percent);

					if($row->lot_no<190701){
						$pcr_challan_check_all[$row->stock_id][intval($row->item_cost_price)][]=$row;
					}
				}
			}

			krsort($ospos_sales_items_discount);

			$consider_sale_id=array();
			$consider_sale_details=array();

			$query = $this->db->query("SELECT * FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0");

			foreach ($query->result() as $row) {
				$consider_sale_id[]=$row->sale_id;
				$consider_sale_details[$row->sale_id]=$row;
			}


			if(count($consider_sale_id)){

				$consider_sale_id_str="'".implode("','",$consider_sale_id)."'";

				$not_consider_pcr_lot_no=array();

				$query = $this->db->query("SELECT sale_id,pcr_lot_no,COUNT(pcr_lot_no) AS count_same_pcr
									   FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.") 
									   AND discount_percent>0 
									   AND (sales_employee_code!='200110111' OR sales_employee_code='0' OR sales_employee_code='' OR sales_employee_code is null) AND pcr_lot_no!=lot_no 
									   GROUP BY sale_id,pcr_lot_no ORDER BY sale_id");
				foreach ($query->result() as $row_not_same) {

					if(trim($row_not_same->pcr_lot_no)!=""){
						if($row_not_same->count_same_pcr>1){
							$not_consider_pcr_lot_no[$row_not_same->sale_id][]=$row_not_same->pcr_lot_no;
						}
					}
				}

				$pcr_sales_details=array();
				$pcr_sales_details_value_wise=array();
				$pcr_sales_details_price=array();
				$pcr_sales_details_max_discount=array();

				$pcr_sales_details_item_cost_price_total=0;
				$mrp_sales_details=array();
				$mrp_sales_details_item_cost_price_total=0;
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.") AND discount_percent>0 AND (sales_employee_code!='200110111' OR sales_employee_code='0' OR sales_employee_code='' OR sales_employee_code is null)  ORDER BY sale_id,line");


				$block=5;
				$serial=0;
				$max_discount=0;

				foreach ($query->result() as $row) {
					if(trim($row->pcr_lot_no)!=""){

						if(!in_array($row->pcr_lot_no,$not_consider_pcr_lot_no[$row->sale_id])){

							if(count($pcr_sales_details[$serial])>=$block){
								$max_discount=0;
								$serial++;
							}
							if($row->discount_percent>=$pcr_sales_details_max_discount[$serial][intval($row->item_cost_price*$row->quantity_purchased)]){
								$max_discount=intval($row->discount_percent);
								$pcr_sales_details_max_discount[$serial][intval($row->item_cost_price*$row->quantity_purchased)]=$max_discount;
							}
							$pcr_sales_details[$serial][]=$row;
							$pcr_sales_details_value_wise[$serial][intval($row->item_cost_price*$row->quantity_purchased)][]=$row;
							$pcr_sales_details_item_cost_price_total[$serial]+=intval($row->item_cost_price*$row->quantity_purchased);
							$pcr_sales_details_price[$serial][intval($row->item_cost_price*$row->quantity_purchased)]=intval($row->item_cost_price*$row->quantity_purchased);
						}
					}
				}


				foreach ($pcr_sales_details as $block_key => $block_value) {

					$block_execute=0;

					$array=array();
					foreach ($pcr_sales_details_price[$block_key] as $key => $value) {
						$array[]=$value;
					}

					$combination_array=array();
					$combination_array=$this->pc_array_power_set($array);
					$combination_array_compare=array();
					foreach ($combination_array as $com_key => $com_value) {
						if(count($com_value)>=2){
							$combination_array_compare[]=$com_value;
						}
					}



					if(count($combination_array_compare)){
						krsort($combination_array_compare);
						foreach ($combination_array_compare as $check_key => $check_value) {


							$total_check=0;
							foreach ($check_value as $ch_key => $ch_value) {
								$total_check+=$ch_value;
							}
							if (array_key_exists($total_check,$ospos_sales_items_discount)){

								$max_discount_block=0;

								foreach ($pcr_sales_details_max_discount[$block_key] as $max_dis_key => $max_value) {
									if($max_value>=$max_discount_block){
										$max_discount_block=intval($max_value);
									}
								}

								$ospos_sales_items_discount_for_max_discount=$ospos_sales_items_discount[$total_check];


								$max_discount_block_dummy=array();

								for($imo=$max_discount_block;$imo<=70;$imo=$imo+10){
									if (array_key_exists($imo,$ospos_sales_items_discount_for_max_discount)){
										$max_discount_block=$imo;
										break;
									}
								}

								if (array_key_exists($max_discount_block,$ospos_sales_items_discount_for_max_discount)){

									if($block_execute==0){
										$execution_query_insert=array();
										$execution_query_delete=array();

										$new_items_information=array();
										$new_items_information_found=array();
										$new_items_information_found=$ospos_sales_items_discount[$total_check][$max_discount_block];

										$index=rand(0,count($new_items_information_found)-1);

										$new_items_information=$new_items_information_found[$index];

										$real_total_discount=0;
										$real_total_sale_amount=0;
										$real_vat_enable_price_after_discount=0;
										$real_vat_amount=0;

										$inserted_vat_enable_price_after_discount=0;
										$inserted_vat_amount=0;


										$mrp_details_array_for_new=array();

										foreach ($check_value as $old_key => $old_value) {
											$existing_item_information=array();
											$existing_item_information=$pcr_sales_details_value_wise[$block_key][$old_value][0];

											$pos_ospos_sales_items_pcr_lot_no_explode_array=explode("#",$existing_item_information->pcr_lot_no);

											if(trim($pos_ospos_sales_items_pcr_lot_no_explode_array[1])){

												$receipt_no_pcr=$consider_sale_details[$existing_item_information->sale_id]->receipt_no;
												$force_reference_pcr=substr($receipt_no_pcr,3).substr($receipt_no_pcr,0,3);


												$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($pos_ospos_sales_items_pcr_lot_no_explode_array[1])."' 
					AND a.lot_no='".mysql_real_escape_string($pos_ospos_sales_items_pcr_lot_no_explode_array[0])."' 
					AND a.price='".mysql_real_escape_string($pos_ospos_sales_items_pcr_lot_no_explode_array[2])."' 
					AND a.type=16 AND a.reference='".mysql_real_escape_string($force_reference_pcr)."' 
					AND a.qty<0
					GROUP BY a.stock_id,a.lot_no,a.price");

												$stock_moves_lot_data=$query_moves->row();

												$standard_cost=0;
												$visible=1;
												$is_imported=0;
												$swatch_code=0;
												if(count($stock_moves_lot_data)){
													if($stock_moves_lot_data->standard_cost==0){
														$standard_cost=round(($existing_item_information->item_cost_price*52)/100);
														$stock_moves_lot_data->standard_cost=round(($existing_item_information->item_cost_price*52)/100);
													}else{
														$standard_cost=$stock_moves_lot_data->standard_cost;
													}
													$visible=$stock_moves_lot_data->visible;
													$is_imported=$stock_moves_lot_data->is_imported;
													$swatch_code=$stock_moves_lot_data->swatch_code;

													$stock_moves_mrp_delete_query="DELETE FROM stock_moves WHERE
											stock_id='".$stock_moves_lot_data->stock_id."' 
											AND type='16'
											AND loc_code='".LOCATION_CODE."'
											AND tran_date='".$stock_moves_lot_data->tran_date."' 
											AND price='".$stock_moves_lot_data->price."' 
											AND reference='".$force_reference_pcr."' 
											AND qty='".$stock_moves_lot_data->qty."' 
											AND lot_no='".$stock_moves_lot_data->lot_no."'";

													$execution_query_delete[]=$stock_moves_mrp_delete_query;////////////////////////////////////QUERY


													$mrp_details_array_for_new[]=$stock_moves_lot_data->stock_id."#".$stock_moves_lot_data->tran_date."#".$stock_moves_lot_data->price."#".$force_reference_pcr."#".$stock_moves_lot_data->qty."#".$standard_cost."#".$visible."#".$stock_moves_lot_data->lot_no."#".$is_imported."#".$swatch_code;
												}
											}

											$real_total_discount+=$existing_item_information->total_discount;
											$real_total_sale_amount+=$existing_item_information->total_sale_amount;
											$real_vat_enable_price_after_discount+=$existing_item_information->vat_enable_price_after_discount;
											$real_vat_amount+=$existing_item_information->vat_amount;

											$last_item_deatils=array();
											$last_item_deatils=$existing_item_information;

											if(trim($existing_item_information->mrp_details)){
												$mrp_details_array=array();
												$mrp_details_array=explode("NEWMRP",trim($existing_item_information->mrp_details));

												if(count($mrp_details_array)==2){

													$mrp_details_array_for_new[]=$mrp_details_array[0];


													foreach ($mrp_details_array as $mrd_key => $mrd_value) {

														$mrp_details_stock_moves_insert_array=array();
														$mrp_details_stock_insert_array=explode("#",$mrd_value);

														$mrp_details_stock_moves_insert_array["value_stock_id"]=$mrp_details_stock_insert_array[0];
														$mrp_details_stock_moves_insert_array["value_tran_date"]=$mrp_details_stock_insert_array[1];
														$mrp_details_stock_moves_insert_array["value_price"]=$mrp_details_stock_insert_array[2];
														$mrp_details_stock_moves_insert_array["value_reference"]=$mrp_details_stock_insert_array[3];
														$mrp_details_stock_moves_insert_array["value_qty"]=$mrp_details_stock_insert_array[4];
														$mrp_details_stock_moves_insert_array["value_standard_cost"]=$mrp_details_stock_insert_array[5];
														$mrp_details_stock_moves_insert_array["value_visible"]=$mrp_details_stock_insert_array[6];
														$mrp_details_stock_moves_insert_array["value_lot_no"]=$mrp_details_stock_insert_array[7];
														$mrp_details_stock_moves_insert_array["value_is_imported"]=$mrp_details_stock_insert_array[8];
														$mrp_details_stock_moves_insert_array["value_swatch_code"]=$mrp_details_stock_insert_array[9];


														$stock_moves_mrp_delete_query="DELETE FROM stock_moves WHERE
											stock_id='".$mrp_details_stock_moves_insert_array["value_stock_id"]."' 
								AND type='16'
								AND loc_code='".LOCATION_CODE."'
								AND tran_date='".$mrp_details_stock_moves_insert_array["value_tran_date"]."' 
								AND price='".$mrp_details_stock_moves_insert_array["value_price"]."' 
								AND reference='".$mrp_details_stock_moves_insert_array["value_reference"]."' 
								AND qty='".$mrp_details_stock_moves_insert_array["value_qty"]."' 
								AND standard_cost='".$mrp_details_stock_moves_insert_array["value_standard_cost"]."' 
								AND lot_no='".$mrp_details_stock_moves_insert_array["value_lot_no"]."'";

														$execution_query_delete[]=$stock_moves_mrp_delete_query;////////////////////////////////////QUERY
													}
												}
											}
											$receipt_no=$consider_sale_details[$existing_item_information->sale_id]->receipt_no;
											$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);

											$stock_moves_sales_delete_query="DELETE FROM stock_moves WHERE
											stock_id='".$existing_item_information->stock_id."' 
								AND type='201'
								AND loc_code='".LOCATION_CODE."'
								AND price='".$existing_item_information->item_cost_price."' 
								AND reference='".$receipt_no."' 
								AND qty='".($existing_item_information->quantity_purchased*-1)."' 
								AND lot_no='".$existing_item_information->lot_no."'";

											$execution_query_delete[]=$stock_moves_sales_delete_query;////////////////////////////////////QUERY

											$stock_moves_pcr_delete_query="DELETE FROM stock_moves WHERE
											stock_id='".$existing_item_information->stock_id."' 
								AND type='16'
								AND loc_code='".LOCATION_CODE."'
								AND price='".$existing_item_information->item_cost_price."' 
								AND reference='".$force_reference."' 
								AND qty='".$existing_item_information->quantity_purchased."' 
								AND lot_no='".$existing_item_information->lot_no."'";

											$execution_query_delete[]=$stock_moves_pcr_delete_query;////////////////////////////////////QUERY

											$delete_query="DELETE FROM ospos_sales_items
									WHERE sale_id='".$existing_item_information->sale_id."' 
									AND line='".$existing_item_information->line."' 
									AND stock_id='".$existing_item_information->stock_id."'
									AND lot_no='".$existing_item_information->lot_no."'
									AND quantity_purchased='".$existing_item_information->quantity_purchased."'
									AND item_cost_price='".$existing_item_information->item_cost_price."'
									AND discount_percent='".$existing_item_information->discount_percent."'";

											$execution_query_delete[]=$delete_query;////////////////////////////////////QUERY
										}

										$current_discount_percent=$new_items_information->discount_percent;
										$current_total_discount=round(($new_items_information->item_cost_price*$new_items_information->discount_percent)/100);
										$current_item_unit_price=round($new_items_information->item_cost_price-$current_total_discount);
										$current_total_sale_amount=($new_items_information->item_cost_price-$current_total_discount)*1;

										$current_vat_enable_price_after_discount=round($new_items_information->item_cost_price-$current_total_discount);
										$current_vat_amount=number_format($current_vat_enable_price_after_discount*7.5/100,2,'.','');



										////////////GAP VEP/////////////////////
										$gap_vat_enable_price_after_discount=$real_total_sale_amount-$real_vat_enable_price_after_discount;
										$gap_vat_amount=number_format($real_total_sale_amount*7.5/100,2,'.','')-$real_vat_amount;

										$inserted_vat_enable_price_after_discount=0;
										$inserted_vat_amount=0;

										$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$cash_in_hand=$row->payment_amoount;
										}


										$clr_cash=0;
										$clr_purchase_discount=0;

										if(round($real_total_sale_amount)>round($current_total_sale_amount)){
											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount-($real_total_sale_amount-$current_total_sale_amount));
											$inserted_vat_amount=$real_vat_amount-number_format(round($real_total_sale_amount-$current_total_sale_amount)*7.5/100,2,'.','');
											$clr_cash=round($real_total_sale_amount-$current_total_sale_amount)+round((round($real_total_sale_amount-$current_total_sale_amount)*7.5)/100);
										}else{
											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount);
											$inserted_vat_amount=$real_vat_amount;
										}

										$sale_id_modify_def=$last_item_deatils->sale_id;


										$cash_update_def=$clr_cash;
										//$card_discount_def=$clr_purchase_discount;

										if($cash_in_hand>=round($clr_cash+129)){

											if($cash_update_def>0){

												$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify_def."' AND payment_type='Cash' LIMIT 1";
												$query = $this->db->query($sql);

												$payment_sale_id=0;
												foreach ($query->result() as $row) {
													$payment_sale_id=$row->sale_id;
													$payment_sale_id_amount=$row->payment_amount;
												}
												if($payment_sale_id){
													$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update_def))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
													$this->db->query($update_query_permission);////////////////NEXT

												}else{
													$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
										VALUES('".$sale_id_modify_def."',
										'Cash',
										'-".round($cash_update_def)."')";
													$this->db->query($insert_sql);////NEXT
												}

												$insert_query="
										INSERT INTO ospos_clr_locwise(
										sales_time,
										loc_code,
										sale_id,
										total_price,
										previous_clr,
										current_clr,
										previous_sale_price_total,
										clr_amount_total,
										clr_amount
										)
										VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
										'".LOCATION_CODE."',
										'".$last_item_deatils->sale_id."',
										'".$last_item_deatils->vat_enable_price."',
										'".$last_item_deatils->discount_percent."',
										'".round($cash_update_def)."',
										'".$last_item_deatils->total_sale_amount."',
										'".round($cash_update_def)."',
										'".round($cash_update_def)."')";

												$this->db->query($insert_query);////NEXT
											}
										}else{
											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount);
											$inserted_vat_amount=$real_vat_amount;
										}


										$standard_cost=0;
										$visible=1;
										$is_imported=0;
										$swatch_code=0;

										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($new_items_information->stock_id)."' AND a.lot_no='".mysql_real_escape_string($new_items_information->lot_no)."' AND a.price='".mysql_real_escape_string($new_items_information->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();

										if(count($stock_moves_lot_data)){
											if($stock_moves_lot_data->standard_cost==0){
												$standard_cost=round(($new_items_information->item_cost_price*52)/100);
												$stock_moves_lot_data->standard_cost=round(($new_items_information->item_cost_price*52)/100);
											}else{
												$standard_cost=$stock_moves_lot_data->standard_cost;
											}
											$visible=$stock_moves_lot_data->visible;
											$is_imported=$stock_moves_lot_data->is_imported;
											$swatch_code=$stock_moves_lot_data->swatch_code;
										}else{
											$standard_cost=round(($new_items_information->item_cost_price*52)/100);
										}

										$receipt_no=$consider_sale_details[$last_item_deatils->sale_id]->receipt_no;
										$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);

										$date_moves_update="20".substr($new_items_information->lot_no,0,2)."-".substr($new_items_information->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

										$mrp_details_array_for_new[]=$new_items_information->stock_id."#".$date_moves_update."#".$new_items_information->item_cost_price."#".$force_reference."#1#".$standard_cost."#".$visible."#".$new_items_information->lot_no."#".$is_imported."#".$swatch_code;

										krsort($mrp_details_array_for_new);
										$mrp_dtails="";
										if(count($mrp_details_array_for_new)){
											$mrp_dtails=implode("NEWMRP",$mrp_details_array_for_new);

										}

										/////////////////////////////////////////INSERT ITEM////////////////////////////////////////////////
										$sales_items_data="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission,
								mrp_details) VALUES(
								'".$last_item_deatils->sale_id."',
								'".$new_items_information->stock_id."',
								'".$new_items_information->description."',
								'".$new_items_information->lot_no."',
								'".$last_item_deatils->line."',
								'1',
								'".$new_items_information->item_cost_price."',
								'".$current_item_unit_price."',
								'".$current_discount_percent."',
								'".$current_total_discount."',
								'".$current_item_unit_price."',
								'".$new_items_information->item_cost_price."',
								'".$last_item_deatils->vat_percentage."',
								'".$inserted_vat_amount."',
								'200110111',
								'".$inserted_vat_enable_price_after_discount."',
								'".$new_items_information->lot_no."',
								'".$last_item_deatils->sync_permission."',
								'".$last_item_deatils->cus_permission."',
								'".$mrp_dtails."')";

										$execution_query_insert[]=$sales_items_data;/////////////////////////////////////QUERY

										foreach ($mrp_details_array_for_new as $key => $value) {

											$mrp_details_stock_insert_array=explode("#",$value);
											$mrp_details_stock_moves_insert_array["value_stock_id"]=$mrp_details_stock_insert_array[0];
											$mrp_details_stock_moves_insert_array["value_tran_date"]=$mrp_details_stock_insert_array[1];
											$mrp_details_stock_moves_insert_array["value_price"]=$mrp_details_stock_insert_array[2];
											$mrp_details_stock_moves_insert_array["value_reference"]=$mrp_details_stock_insert_array[3];
											$mrp_details_stock_moves_insert_array["value_qty"]=$mrp_details_stock_insert_array[4];
											$mrp_details_stock_moves_insert_array["value_standard_cost"]=$mrp_details_stock_insert_array[5];
											$mrp_details_stock_moves_insert_array["value_visible"]=$mrp_details_stock_insert_array[6];
											$mrp_details_stock_moves_insert_array["value_lot_no"]=$mrp_details_stock_insert_array[7];
											$mrp_details_stock_moves_insert_array["value_is_imported"]=$mrp_details_stock_insert_array[8];
											$mrp_details_stock_moves_insert_array["value_swatch_code"]=$mrp_details_stock_insert_array[9];


											$insert_query_stock_moves_data_mrp="INSERT INTO stock_moves(trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES("
											."'".$last_item_deatils->sale_id."',"
											."'".$mrp_details_stock_moves_insert_array["value_stock_id"]."',"
											."'16',"
											."'".LOCATION_CODE."',"
											."'".$mrp_details_stock_moves_insert_array["value_tran_date"]."',"
											."'".$last_item_deatils->sale_id."',"
											."'".$mrp_details_stock_moves_insert_array["value_price"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_reference"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_qty"]."',"
											."'0',"
											."'".$mrp_details_stock_moves_insert_array["value_standard_cost"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_visible"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_lot_no"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_is_imported"]."',"
											."'".$mrp_details_stock_moves_insert_array["value_swatch_code"]."')";

											$execution_query_insert[]=$insert_query_stock_moves_data_mrp;/////////////////////////////////////QUERY
										}

										$stock_moves_new_sale_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$last_item_deatils->sale_id."',
								'".$new_items_information->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".date("Y-m-d",strtotime($consider_sale_details[$last_item_deatils->sale_id]->sale_time))."',
								'".$last_item_deatils->sale_id."',
								'".$new_items_information->item_cost_price."',
								'".$consider_sale_details[$last_item_deatils->sale_id]->receipt_no."',
								'-1',
								'0',
								'".$standard_cost."',
								'".$visible."',
								'".$new_items_information->lot_no."',
								'".$is_imported."',
								'".$swatch_code."')";

										$execution_query_insert[]=$stock_moves_new_sale_data;////////////////////////////////QUERY

										$block_execute=1;
										/////////////////////////////////////////////
										foreach ($execution_query_delete as $key => $delete_value) {
											$this->db->query($delete_value);////NEXT
										}
										foreach ($execution_query_insert as $key => $insert_value) {
											$this->db->query($insert_value);////NEXT
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	function do_per_slot_2021_same_item_replace($current_date){

		$current_directory = getcwd();
		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']=0;
		}

		if($config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']==1){

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}
			$array_find[]="One piece";
			$array_find[]="One Piece";
			$array_find[]="Tunic";

			$array_find_male_full_shirt[]="Male Full Shirt";
			$array_find_male_half_shirt[]="Male Half Shirt";


			$ospos_sales_items_discount=array();

			$price_combination=array();

			$pcr_challan_check_dis=array();
			$pcr_challan_check_all=array();

			$query = $this->db->query("SELECT a.stock_id,a.lot_no,CAST(a.item_cost_price AS SIGNED) AS item_cost_price,a.discount_percent,a.challan_no,a.loc_code,IF(b.item_size_id> 0,CONCAT(c.description,'</br>',b.description,' - ',d.size),CONCAT(c.description,'</br>',b.description)) AS description,b.gender AS item_gender
			FROM pcr_challan_check AS a
			LEFT JOIN stock_master AS b ON a.stock_id=b.stock_id
			LEFT JOIN stock_category AS c ON b.category_id=c.category_id
			LEFT JOIN pos_item_sizes AS d ON b.item_size_id=d.id 
			WHERE a.discount_percent>0 GROUP BY a.stock_id,a.lot_no,a.item_cost_price,a.discount_percent ORDER BY a.discount_percent DESC,a.item_cost_price DESC");

			foreach ($query->result() as $row) {

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

				$has_add=1;

				if ($this->strpos_arr_2021_check($row->description, $array_find, 1)) {
					if(trim($row->item_gender)=="girl"){
						$row->discount_percent=50;
					}else{
						$row->discount_percent=40;
					}
				}elseif ($this->strpos_arr_2021_check($row->description, $array_find_male_full_shirt, 1)) {
					if($row->item_cost_price<1090){
						$has_add=0;
					}
				}elseif ($this->strpos_arr_2021_check($row->description, $array_find_male_half_shirt, 1)) {
					if($row->item_cost_price>540){
						$has_add=0;
					}
				}
				if($has_add==1){
					////////////////////////////////////////////////////////////////////////////
					$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
					$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
					$pcr_challan_check_dis[$row->stock_id]=intval($row->discount_percent);


					if($row->lot_no<190701){
						$pcr_challan_check_all[$row->stock_id][intval($row->item_cost_price)][]=$row;
					}
				}
			}


			krsort($ospos_sales_items_discount);

			$consider_sale_id=array();
			$consider_sale_details=array();

			$query = $this->db->query("SELECT * FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0");

			foreach ($query->result() as $row) {
				$consider_sale_id[]=$row->sale_id;
				$consider_sale_details[$row->sale_id]=$row;
			}

			if(count($consider_sale_id)){
				$consider_sale_id_str="'".implode("','",$consider_sale_id)."'";
				$query = $this->db->query("SELECT *
									   FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.") 
									   AND discount_percent>0 AND quantity_purchased>0 AND lot_no>=190701
									  ORDER BY sale_id");


				$wrong_pcr_lot_array=array();
				$new_item_sales_price_array=array();
				foreach ($query->result() as $row_not_same) {

					if(trim($row_not_same->pcr_lot_no)!=""){
						$wrong_pcr_lot_array[]=$row_not_same;
						$new_item_sales_price_array[intval($row_not_same->item_cost_price)]=intval($row_not_same->item_cost_price);
					}
				}

				if(count($wrong_pcr_lot_array)){

					krsort($new_item_sales_price_array);

					$new_item_sales_price_array_sm=array();
					foreach ($new_item_sales_price_array as $key => $value) {
						$new_item_sales_price_array_sm[]=$value;
					}


					$new_items_stock_moves=array();
					$new_item_sales_price_array_sm_string="'".implode("','",$new_item_sales_price_array_sm)."'";

					$query = $this->db->query("SELECT *
									   FROM pcr_stock_moves_recheck WHERE price IN(".$new_item_sales_price_array_sm_string.")
									   GROUP BY stock_id,price,lot_no ORDER BY lot_no ASC");

					foreach ($query->result() as $row_not_same) {
						$new_items_stock_moves[intval($row_not_same->price)][intval($row_not_same->discount_percent)][]=$row_not_same;
					}

					////////////////////////////////////REPLACE/////////////////////////////////////


					foreach ($wrong_pcr_lot_array as $wrong_key => $wrong_value) {

						$execution_query_delete_bigger_lot=array();


						$has_product_in_mrp=0;
						$new_mrp_array=array();

						$has_found=0;
						$found_array=$new_items_stock_moves[intval($wrong_value->item_cost_price)][intval($wrong_value->discount_percent)];

						$receipt_no=$consider_sale_details[$wrong_value->sale_id]->receipt_no;
						$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);


						$replace_array=array();

						if(count($found_array)){
							$index=rand(0,count($found_array)-1);
							foreach ($found_array[$index] as $f_key => $f_value) {
								$replace_array[$f_key]=$f_value;
								$has_found=1;
							}
						}else{
							$replace_array['stock_id'] = $wrong_value->stock_id;
							$replace_array['lot_no'] = rand(16,18).str_pad(rand(1,12),2,"0",STR_PAD_LEFT).str_pad(rand(1,28),2,"0",STR_PAD_LEFT);
							$replace_array['price']= $wrong_value->item_cost_price;
							$replace_array['standard_cost']= number_format($wrong_value->item_cost_price*52/100,2,'.','');
							$replace_array['discount_percent']= $wrong_value->discount_percent;
							$has_found=0;
						}

						if(trim($wrong_value->mrp_details)){
							$found_inside_mrp=0;
							$mrp_details_array=explode("NEWMRP",trim($wrong_value->mrp_details));
							foreach ($mrp_details_array as $mrd_key => $mrd_value) {

								$mrp_details_stock_moves_insert_array=array();
								$mrp_details_stock_insert_array=explode("#",$mrd_value);

								$mrp_details_stock_moves_insert_array["value_stock_id"]=$mrp_details_stock_insert_array[0];
								$mrp_details_stock_moves_insert_array["value_tran_date"]=$mrp_details_stock_insert_array[1];
								$mrp_details_stock_moves_insert_array["value_price"]=$mrp_details_stock_insert_array[2];
								$mrp_details_stock_moves_insert_array["value_reference"]=$mrp_details_stock_insert_array[3];
								$mrp_details_stock_moves_insert_array["value_qty"]=$mrp_details_stock_insert_array[4];
								$mrp_details_stock_moves_insert_array["value_standard_cost"]=$mrp_details_stock_insert_array[5];
								$mrp_details_stock_moves_insert_array["value_visible"]=$mrp_details_stock_insert_array[6];
								$mrp_details_stock_moves_insert_array["value_lot_no"]=$mrp_details_stock_insert_array[7];
								$mrp_details_stock_moves_insert_array["value_is_imported"]=$mrp_details_stock_insert_array[8];
								$mrp_details_stock_moves_insert_array["value_swatch_code"]=$mrp_details_stock_insert_array[9];


								if($mrp_details_stock_moves_insert_array["value_stock_id"]==$wrong_value->stock_id
								AND intval($mrp_details_stock_moves_insert_array["value_price"])==intval($wrong_value->item_cost_price)
								AND $mrp_details_stock_moves_insert_array["value_qty"]==$wrong_value->quantity_purchased
								AND $mrp_details_stock_moves_insert_array["value_lot_no"]==$wrong_value->lot_no
								){
									$stock_moves_mrp_delete_query="DELETE FROM stock_moves WHERE
											stock_id='".$mrp_details_stock_moves_insert_array["value_stock_id"]."' 
								AND type='16'
								AND loc_code='".LOCATION_CODE."'
								AND tran_date='".$mrp_details_stock_moves_insert_array["value_tran_date"]."' 
								AND price='".$mrp_details_stock_moves_insert_array["value_price"]."' 
								AND reference='".$mrp_details_stock_moves_insert_array["value_reference"]."' 
								AND qty='".$mrp_details_stock_moves_insert_array["value_qty"]."' 
								AND standard_cost='".$mrp_details_stock_moves_insert_array["value_standard_cost"]."' 
								AND lot_no='".$mrp_details_stock_moves_insert_array["value_lot_no"]."' LIMIT 1";

									$execution_query_delete_bigger_lot[]=$stock_moves_mrp_delete_query;////////////////////////////////////QUERY


								}else{
									$new_mrp_array[]=$mrd_value;
								}

							}
						}

						$receipt_no=$consider_sale_details[$wrong_value->sale_id]->receipt_no;
						$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);

						$date_moves_update="20".substr($replace_array['lot_no'],0,2)."-".substr($replace_array['lot_no'],2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

						$stock_moves_new_sale_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$wrong_value->sale_id."',
								'".$replace_array['stock_id']."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update."',
								'".$wrong_value->sale_id."',
								'".$replace_array['price']."',
								'".$force_reference."',
								'".$wrong_value->quantity_purchased."',
								'0',
								'".$replace_array['standard_cost']."',
								'1',
								'".$replace_array['lot_no']."',
								'0',
								'0')";

						$execution_query_delete_bigger_lot[]=$stock_moves_new_sale_data;////////////////////////////////QUERY

						$stock_moves_sales_delete_query="UPDATE stock_moves SET stock_id='".$replace_array['stock_id']."',lot_no='".$replace_array['lot_no']."',standard_cost='".$replace_array['standard_cost']."' WHERE
											stock_id='".$wrong_value->stock_id."' 
								AND type='201'
								AND loc_code='".LOCATION_CODE."'
								AND price='".$wrong_value->item_cost_price."' 
								AND reference='".$receipt_no."' 
								AND qty='".($wrong_value->quantity_purchased*-1)."' 
								AND lot_no='".$wrong_value->lot_no."' LIMIT 1";
						$execution_query_delete_bigger_lot[]=$stock_moves_sales_delete_query;////////////////////////////////////QUERY


						$new_mrp_array[]=$replace_array['stock_id']."#".$date_moves_update."#".$replace_array['price']."#".$force_reference."#".$wrong_value->quantity_purchased."#".$replace_array['standard_cost']."#1#".$replace_array['lot_no']."#0#0";



						$query_root_stock=$this->db->query("SELECT a.description,a.item_size_id,b.size,c.description AS cat_description
															FROM stock_master AS a
															LEFT JOIN pos_item_sizes AS b ON a.item_size_id=b.id
															LEFT JOIN stock_category AS c ON a.category_id=c.category_id
															WHERE a.stock_id='".$replace_array['stock_id']."'");

						$cat_description="";
						$item_description="";

						foreach ($query_root_stock->result() as $row_line) {
							$cat_description=$row_line->cat_description;
							if($row_line->item_size_id==0){
								$item_description=$row_line->description." - N/A";
							}else{
								$item_description=$row_line->description." - ".$row_line->size;
							}
						}


						$mrp_details="";
						if(count($new_mrp_array)){
							$mrp_details=implode("NEWMRP",$new_mrp_array);

						}
						$update_sale_items="UPDATE ospos_sales_items SET
				stock_id='".mysql_real_escape_string($replace_array['stock_id'])."',
				description='".mysql_real_escape_string($cat_description."</br>".$item_description)."',
				lot_no='".mysql_real_escape_string($replace_array['lot_no'])."',
				mrp_details='".mysql_real_escape_string($mrp_details)."'

				WHERE sale_id='".mysql_real_escape_string($wrong_value->sale_id)."' 
				AND stock_id='".mysql_real_escape_string($wrong_value->stock_id)."' 
				AND lot_no='".mysql_real_escape_string($wrong_value->lot_no)."' 
				AND line='".mysql_real_escape_string($wrong_value->line)."' 
				AND quantity_purchased='".mysql_real_escape_string($wrong_value->quantity_purchased)."'
				AND item_cost_price='".mysql_real_escape_string($wrong_value->item_cost_price)."'
				AND total_sale_amount='".mysql_real_escape_string($wrong_value->total_sale_amount)."'
				AND vat_enable_price_after_discount='".mysql_real_escape_string($wrong_value->vat_enable_price_after_discount)."' LIMIT 1";
						$execution_query_delete_bigger_lot[]=$update_sale_items;////////////////////////////////QUERY


						if(count($execution_query_delete_bigger_lot)){

							foreach ($execution_query_delete_bigger_lot as $ex_key => $ex_query) {
								$this->db->query($ex_query);////////////////Seedupriya
							}
						}
					}
				}
			}

			if(count($consider_sale_id)){

				$consider_sale_id_str="'".implode("','",$consider_sale_id)."'";

				/////////////////More Than 1 qty/////////////////////

				$query = $this->db->query("SELECT *
									   FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.") 
									   AND discount_percent>0 AND quantity_purchased>1
									  ORDER BY sale_id");
				foreach ($query->result() as $row_not_same) {

					if(trim($row_not_same->pcr_lot_no)!=""){


						$row_not_same_temp=array();

						foreach ($row_not_same as $mul_key => $mul_value) {
							$row_not_same_temp[$mul_key]=$mul_value;
						}

						$row_quantity_purchased=$row_not_same->quantity_purchased;

						$row_not_same_temp['quantity_purchased']="1.00";
						$row_not_same_temp['total_discount']=number_format(($row_not_same->total_discount/$row_quantity_purchased),2,'.','');
						$row_not_same_temp['total_sale_amount']=number_format(($row_not_same->total_sale_amount/$row_quantity_purchased),2,'.','');
						$row_not_same_temp['vat_enable_price']=number_format(($row_not_same->vat_enable_price/$row_quantity_purchased),2,'.','');
						$row_not_same_temp['vat_amount']=number_format(($row_not_same->vat_amount/$row_quantity_purchased),2,'.','');
						$row_not_same_temp['vat_enable_price_after_discount']=number_format(($row_not_same->vat_enable_price_after_discount/$row_quantity_purchased),2,'.','');


						///////////////////MAX LINE///////////////////////////////////
						$query_line = $this->db->query("SELECT MAX(line) AS line
						FROM ospos_sales_items WHERE sale_id='".$row_not_same->sale_id."'");

						$next_line=0;
						foreach ($query_line->result() as $row_line) {
							$next_line=$row_line->line+1;
						}

						for($j=1;$j<=$row_quantity_purchased;$j++){

							if($j==1){
								///////////////////////MODIFY////////////////////////
								$update_query="UPDATE ospos_sales_items SET
							quantity_purchased='".$row_not_same_temp['quantity_purchased']."',
							total_discount='".$row_not_same_temp['total_discount']."',
							total_sale_amount='".$row_not_same_temp['total_sale_amount']."',
							vat_enable_price='".$row_not_same_temp['vat_enable_price']."',
							vat_amount='".$row_not_same_temp['vat_amount']."',
							vat_enable_price_after_discount='".$row_not_same_temp['vat_enable_price_after_discount']."'
							WHERE sale_id='".$row_not_same->sale_id."' 
							AND stock_id='".$row_not_same->stock_id."'
							AND lot_no='".$row_not_same->lot_no."'
							AND line='".$row_not_same->line."'
							AND quantity_purchased='".$row_not_same->quantity_purchased."'
							AND item_cost_price='".$row_not_same->item_cost_price."'
							AND item_unit_price='".$row_not_same->item_unit_price."'
							AND total_discount='".$row_not_same->total_discount."'
							AND total_sale_amount='".$row_not_same->total_sale_amount."'
							AND vat_enable_price='".$row_not_same->vat_enable_price."'";

								$this->db->query($update_query);////NEXT

							}else{
								$insert_query="INSERT INTO ospos_sales_items(
							sale_id,
							stock_id,
							description,
							lot_no,
							line,
							quantity_purchased,
							item_cost_price,
							item_unit_price,
							discount_percent,
							total_discount,
							total_sale_amount,
							vat_enable_price,
							vat_percentage,
							vat_amount,
							sales_employee_code,
							vat_enable_price_after_discount,
							pcr_lot_no,
							sync_permission,
							cus_permission,
							mrp_details,
							vat_enable_price_after_discount_cal)VALUES(
							'".$row_not_same->sale_id."', 
							'".$row_not_same->stock_id."', 
							'".$row_not_same->description."', 
							'".$row_not_same->lot_no."', 
							'".$next_line."', 
							'".$row_not_same_temp['quantity_purchased']."',
							'".$row_not_same->item_cost_price."',
							'".$row_not_same->item_unit_price."',
							'".$row_not_same->discount_percent."',
							'".$row_not_same_temp['total_discount']."',
							'".$row_not_same_temp['total_sale_amount']."',
							'".$row_not_same_temp['vat_enable_price']."',
							'".$row_not_same->vat_percentage."',
							'".$row_not_same_temp['vat_amount']."',
							'".$row_not_same->sales_employee_code."',
							'".$row_not_same_temp['vat_enable_price_after_discount']."',
							'".$row_not_same->pcr_lot_no."',
							'".$row_not_same->sync_permission."',
							'".$row_not_same->cus_permission."',
							'',
							'".$row_not_same->vat_enable_price_after_discount_cal."')";
								//////INSERT///////////////////////////////////////
								$this->db->query($insert_query);////NEXT
								$next_line++;
							}
						}
					}
				}


				$all_pcr_prducts=array();
				$all_pcr_stock_id_count=array();

				$compare_same_stock_id=array();

				$query = $this->db->query("SELECT *
									   FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.") 
									   AND discount_percent>0 AND (sales_employee_code!='200110111' OR sales_employee_code='0' OR sales_employee_code='' OR sales_employee_code is null) 
									  ORDER BY sale_id ASC,mrp_details ASC");
				foreach ($query->result() as $row_all) {
					if(trim($row_all->pcr_lot_no)!=""){
						$all_pcr_prducts[$row_all->stock_id][]=$row_all;
						$all_pcr_stock_id_count[$row_all->stock_id]+=1;
						$compare_same_stock_id[$row_all->stock_id]=$row_all->stock_id;
					}
				}

				foreach ($all_pcr_stock_id_count as $stock_key => $value) {

					if($value>1){

						$compare_sales_information_all=$all_pcr_prducts[$stock_key];


						////////////////////////STOCK MOVES ACTION////////////////////////////

						$receipt_no_pcr=$consider_sale_details[$compare_sales_information_all[0]->sale_id]->receipt_no;
						$force_reference_pcr=substr($receipt_no_pcr,3).substr($receipt_no_pcr,0,3);


						$update_query_stock="UPDATE stock_moves SET qty=qty/qty WHERE
					stock_id='".$compare_sales_information_all[0]->stock_id."'
					AND type='16'
					AND loc_code='".LOCATION_CODE."'
					AND price='".$compare_sales_information_all[0]->item_cost_price."'
					AND reference='".$force_reference_pcr."'
					AND lot_no='".$compare_sales_information_all[0]->lot_no."'";

						$this->db->query($update_query_stock);////NEXT


						$update_query_sale="UPDATE stock_moves SET qty=qty/qty WHERE
					stock_id='".$compare_sales_information_all[0]->stock_id."'
					AND type='201'
					AND loc_code='".LOCATION_CODE."'
					AND price='".$compare_sales_information_all[0]->item_cost_price."'
					AND reference='".$receipt_no_pcr."'
					AND lot_no='".$compare_sales_information_all[0]->lot_no."'";

						$this->db->query($update_query_sale);////NEXT


						for ($i=1;$i<count($compare_sales_information_all);$i++){



							$compare_sales_information=$compare_sales_information_all[$i];

							$last_item_deatils=array();
							$last_item_deatils=$compare_sales_information;

							$ospos_sales_items_discount_for_max_discount=$ospos_sales_items_discount[intval($compare_sales_information->item_cost_price)];

							$max_discount_block=intval($compare_sales_information->discount_percent);

							$max_discount_block_dummy=array();

							for($imo=$max_discount_block;$imo<=70;$imo=$imo+10){
								if (array_key_exists($imo,$ospos_sales_items_discount_for_max_discount)){
									$max_discount_block=$imo;
									break;
								}
							}



							if (array_key_exists($max_discount_block,$ospos_sales_items_discount_for_max_discount)){
								$new_items_information_found_all=$ospos_sales_items_discount_for_max_discount[$max_discount_block];

								$without_exisiting_stock_id=array();
								$without_exisiting_lot_no=array();

								foreach ($new_items_information_found_all as $new_key => $new_value) {
									if($new_value->stock_id!=$compare_sales_information->stock_id AND !array_key_exists($new_value->stock_id,$compare_same_stock_id)){
										if($new_value->lot_no<'190701'){
											$without_exisiting_stock_id[]=$new_value;
										}
									}
									if($new_value->stock_id==$compare_sales_information->stock_id AND $new_value->lot_no!=$compare_sales_information->lot_no){
										if($new_value->lot_no<'190701'){
											$without_exisiting_lot_no[]=$new_value;
										}
									}
								}

								/////////////////////////////////////////////////////SAME DIS PERCENTAGE//////////////////////////////////////////////////////////////////
								$new_stock_id="";
								$new_description="";
								$new_lot_no="";


								$has_found=0;

								if(count($without_exisiting_stock_id)){

									$index=rand(0,count($without_exisiting_stock_id)-1);
									$without_exisiting_stock_id_index_value=$without_exisiting_stock_id[$index];
									$new_stock_id=$without_exisiting_stock_id_index_value->stock_id;
									$new_description=$without_exisiting_stock_id_index_value->description;
									$new_lot_no=$without_exisiting_stock_id_index_value->lot_no;
									$new_price=$without_exisiting_stock_id_index_value->item_cost_price;


									$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($new_stock_id)."' 
					AND a.lot_no='".mysql_real_escape_string($new_lot_no)."' 
					AND a.price='".mysql_real_escape_string($new_price)."' 
					GROUP BY a.stock_id,a.lot_no,a.price");

									$stock_moves_lot_data=$query_moves->row();

									$new_standard_cost=0;
									$new_visible=1;
									$new_is_imported=0;
									$new_swatch_code=0;

									if(count($stock_moves_lot_data)){
										if($stock_moves_lot_data->standard_cost==0){
											$new_standard_cost=round(($new_price*52)/100);
										}else{
											$new_standard_cost=$stock_moves_lot_data->standard_cost;
										}
										$new_visible=$stock_moves_lot_data->visible;
										$new_is_imported=$stock_moves_lot_data->is_imported;
										$new_swatch_code=$stock_moves_lot_data->swatch_code;
									}
									$has_found=1;
								}

								if($has_found==0){

									if(count($without_exisiting_lot_no)){

										$index=rand(0,count($without_exisiting_lot_no)-1);
										$without_exisiting_stock_id_index_value=$without_exisiting_lot_no[$index];
										$new_stock_id=$without_exisiting_stock_id_index_value->stock_id;
										$new_description=$without_exisiting_stock_id_index_value->description;
										$new_lot_no=$without_exisiting_stock_id_index_value->lot_no;
										$new_price=$without_exisiting_stock_id_index_value->item_cost_price;


										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($new_stock_id)."' 
					AND a.lot_no='".mysql_real_escape_string($new_lot_no)."' 
					AND a.price='".mysql_real_escape_string($new_price)."' 
					GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();

										$new_standard_cost=0;
										$new_visible=1;
										$new_is_imported=0;
										$new_swatch_code=0;

										if(count($stock_moves_lot_data)){
											if($stock_moves_lot_data->standard_cost==0){
												$new_standard_cost=round(($new_price*52)/100);
											}else{
												$new_standard_cost=$stock_moves_lot_data->standard_cost;
											}
											$new_visible=$stock_moves_lot_data->visible;
											$new_is_imported=$stock_moves_lot_data->is_imported;
											$new_swatch_code=$stock_moves_lot_data->swatch_code;
										}
										$has_found=1;
									}
								}


								if($has_found==1){

									$date_moves_update_first="20".substr($new_lot_no,0,2)."-".substr($new_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

									$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$compare_sales_information->sale_id."',
								'".$new_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$compare_sales_information->sale_id."',
								'".$new_price."',
								'".$force_reference_pcr."',
								'".$compare_sales_information->quantity_purchased."',
								'0',
								'".$new_standard_cost."',
								'".$new_visible."',
								'".$new_lot_no."',
								'".$new_is_imported."',
								'".$new_swatch_code."')";

									$this->db->query($stock_moves_data_first);////NEXT

									$stock_moves_data_second="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$compare_sales_information->sale_id."',
								'".$new_stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".date("Y-m-d",strtotime($consider_sale_details[$compare_sales_information->sale_id]->sale_time))."',
								'".$compare_sales_information->sale_id."',
								'".$new_price."',
								'".$receipt_no_pcr."',
								'".($compare_sales_information->quantity_purchased*-1)."',
								'".$max_discount_block."',
								'".$new_standard_cost."',
								'".$new_visible."',
								'".$new_lot_no."',
								'".$new_is_imported."',
								'".$new_swatch_code."')";
									$this->db->query($stock_moves_data_second);////NEXT

									$compare_same_stock_id[$new_stock_id]=$new_stock_id;




									if(intval($compare_sales_information->discount_percent)!=$max_discount_block){


										$real_total_discount=0;
										$real_total_sale_amount=0;
										$real_vat_enable_price_after_discount=0;
										$real_vat_amount=0;


										$inserted_item_unit_price=0;
										$inserted_discount_percent=0;
										$inserted_total_discount=0;
										$inserted_total_sale_amount=0;

										$inserted_vat_enable_price_after_discount=0;
										$inserted_vat_amount=0;



										$real_total_discount=$compare_sales_information->total_discount;
										$real_total_sale_amount=$compare_sales_information->total_sale_amount;
										$real_vat_enable_price_after_discount=$compare_sales_information->vat_enable_price_after_discount;
										$real_vat_amount=$compare_sales_information->vat_amount;



										$current_discount_percent=$max_discount_block;
										$current_total_discount=round(($compare_sales_information->item_cost_price*$current_discount_percent)/100);
										$current_item_unit_price=round($compare_sales_information->item_cost_price-$current_total_discount);
										$current_total_sale_amount=($compare_sales_information->item_cost_price-$current_total_discount)*$compare_sales_information->quantity_purchased;

										$current_vat_enable_price_after_discount=round($compare_sales_information->item_cost_price-$current_total_discount);
										$current_vat_amount=number_format($current_vat_enable_price_after_discount*7.5/100,2,'.','');




										////////////GAP VEP/////////////////////
										$gap_vat_enable_price_after_discount=$real_total_sale_amount-$real_vat_enable_price_after_discount;
										$gap_vat_amount=number_format($real_total_sale_amount*7.5/100,2,'.','')-$real_vat_amount;


										$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$cash_in_hand=$row->payment_amoount;
										}


										$clr_cash=0;
										$clr_purchase_discount=0;

										if(round($real_total_sale_amount)>round($current_total_sale_amount)){
											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount-($real_total_sale_amount-$current_total_sale_amount));
											$inserted_vat_amount=$real_vat_amount-number_format(round($real_total_sale_amount-$current_total_sale_amount)*7.5/100,2,'.','');
											$clr_cash=round($real_total_sale_amount-$current_total_sale_amount)+round((round($real_total_sale_amount-$current_total_sale_amount)*7.5)/100);

											$inserted_item_unit_price=$current_item_unit_price;
											$inserted_discount_percent=$max_discount_block;
											$inserted_total_discount=$current_total_discount;
											$inserted_total_sale_amount=$current_total_sale_amount;

										}else{

											$inserted_item_unit_price=$compare_sales_information->item_unit_price;
											$inserted_discount_percent=$compare_sales_information->discount_percent;
											$inserted_total_discount=$compare_sales_information->total_discount;;
											$inserted_total_sale_amount=$compare_sales_information->total_sale_amount;;

											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount);
											$inserted_vat_amount=$real_vat_amount;
										}

										$sale_id_modify_def=$compare_sales_information->sale_id;

										$cash_update_def=$clr_cash;
										//$card_discount_def=$clr_purchase_discount;

										if($cash_in_hand>=round($clr_cash+129)){


											if($cash_update_def>0){

												$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify_def."' AND payment_type='Cash' LIMIT 1";
												$query = $this->db->query($sql);

												$payment_sale_id=0;
												foreach ($query->result() as $row) {
													$payment_sale_id=$row->sale_id;
													$payment_sale_id_amount=$row->payment_amount;
												}
												if($payment_sale_id){
													$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update_def))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
													$this->db->query($update_query_permission);////////////////NEXT

												}else{
													$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
										VALUES('".$sale_id_modify_def."',
										'Cash',
										'-".round($cash_update_def)."')";
													$this->db->query($insert_sql);////NEXT
												}

												$insert_query="
										INSERT INTO ospos_clr_locwise(
										sales_time,
										loc_code,
										sale_id,
										total_price,
										previous_clr,
										current_clr,
										previous_sale_price_total,
										clr_amount_total,
										clr_amount
										)
										VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
										'".LOCATION_CODE."',
										'".$last_item_deatils->sale_id."',
										'".$last_item_deatils->vat_enable_price."',
										'".$last_item_deatils->discount_percent."',
										'".round($cash_update_def)."',
										'".$last_item_deatils->total_sale_amount."',
										'".round($cash_update_def)."',
										'".round($cash_update_def)."')";

												$this->db->query($insert_query);////NEXT
											}
										}else{
											$inserted_vat_enable_price_after_discount=round($real_vat_enable_price_after_discount);
											$inserted_vat_amount=$real_vat_amount;

											$inserted_item_unit_price=$compare_sales_information->item_unit_price;
											$inserted_discount_percent=$compare_sales_information->discount_percent;
											$inserted_total_discount=$compare_sales_information->total_discount;;
											$inserted_total_sale_amount=$compare_sales_information->total_sale_amount;;

										}

										///////////////////////////////////////
										$pos_ospos_sales_items_pcr_lot_no_explode_array_check=explode("#",$compare_sales_information->pcr_lot_no);

										if(trim($pos_ospos_sales_items_pcr_lot_no_explode_array_check[1])){
											$new_pcr_lot_no=$compare_sales_information->pcr_lot_no;
										}else{
											$new_pcr_lot_no=$new_lot_no;
										}

										$update_query="UPDATE ospos_sales_items SET
							stock_id='".$new_stock_id."',
							description='".$new_description."',
							lot_no='".$new_lot_no."',
							item_unit_price='".$inserted_item_unit_price."',
							discount_percent='".$inserted_discount_percent."',
							total_discount='".$inserted_total_discount."',
							total_sale_amount='".$inserted_total_sale_amount."',
							vat_amount='".$inserted_vat_amount."',
							vat_enable_price_after_discount='".$inserted_vat_enable_price_after_discount."',
							pcr_lot_no='".$new_pcr_lot_no."'
						
							WHERE sale_id='".$compare_sales_information->sale_id."' 
							AND stock_id='".$compare_sales_information->stock_id."'
							AND lot_no='".$compare_sales_information->lot_no."'
							AND line='".$compare_sales_information->line."'
							AND quantity_purchased='".$compare_sales_information->quantity_purchased."'
							AND item_cost_price='".$compare_sales_information->item_cost_price."'
							AND item_unit_price='".$compare_sales_information->item_unit_price."'
							AND total_discount='".$compare_sales_information->total_discount."'
							AND total_sale_amount='".$compare_sales_information->total_sale_amount."'
							AND vat_enable_price='".$compare_sales_information->vat_enable_price."'";

										$this->db->query($update_query);////NEXT
									}else{

										$pos_ospos_sales_items_pcr_lot_no_explode_array_check=explode("#",$compare_sales_information->pcr_lot_no);

										if(trim($pos_ospos_sales_items_pcr_lot_no_explode_array_check[1])){
											$new_pcr_lot_no=$compare_sales_information->pcr_lot_no;
										}else{
											$new_pcr_lot_no=$new_lot_no;
										}

										$update_query="UPDATE ospos_sales_items SET
							stock_id='".$new_stock_id."',
							description='".$new_description."',
							lot_no='".$new_lot_no."',
							discount_percent='".$max_discount_block."',
							pcr_lot_no='".$new_pcr_lot_no."'
						
							WHERE sale_id='".$compare_sales_information->sale_id."' 
							AND stock_id='".$compare_sales_information->stock_id."'
							AND lot_no='".$compare_sales_information->lot_no."'
							AND line='".$compare_sales_information->line."'
							AND quantity_purchased='".$compare_sales_information->quantity_purchased."'
							AND item_cost_price='".$compare_sales_information->item_cost_price."'
							AND item_unit_price='".$compare_sales_information->item_unit_price."'
							AND total_discount='".$compare_sales_information->total_discount."'
							AND total_sale_amount='".$compare_sales_information->total_sale_amount."'
							AND vat_enable_price='".$compare_sales_information->vat_enable_price."'";

										$this->db->query($update_query);////NEXT
									}
								}
							}
						}
					}
				}
			}
		}
	}

	function do_per_slot_2021($current_date){

		$current_directory = getcwd();
		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']=0;
		}

		if($config_mrp['CORE_PRODUCT_DISCOUNT_ACTIVE']==1){

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}
			///////////////////////////////////////////////////////////////////////////
			function strpos_arr_2021($haystack, $needle) {
				if(!is_array($needle)) $needle = array($needle);
				foreach($needle as $what) {
					if(($pos = strpos($haystack, $what))!==false) return $pos;
				}
				return false;
			}

			$array_find[]="One piece";
			$array_find[]="One Piece";
			$array_find[]="Tunic";

			$array_find_male_full_shirt[]="Male Full Shirt";
			$array_find_male_half_shirt[]="Male Half Shirt";


			$ospos_sales_items_discount=array();

			$price_combination=array();

			$pcr_challan_check_dis=array();
			$pcr_challan_check_all=array();

			$query = $this->db->query("SELECT a.stock_id,a.lot_no,CAST(a.item_cost_price AS SIGNED) AS item_cost_price,a.discount_percent,a.challan_no,a.loc_code,IF(b.item_size_id> 0,CONCAT(c.description,'</br>',b.description,' - ',d.size),CONCAT(c.description,'</br>',b.description)) AS description,b.gender AS item_gender
			FROM pcr_challan_check AS a
			LEFT JOIN stock_master AS b ON a.stock_id=b.stock_id
			LEFT JOIN stock_category AS c ON b.category_id=c.category_id
			LEFT JOIN pos_item_sizes AS d ON b.item_size_id=d.id 
			WHERE a.discount_percent>0 GROUP BY a.stock_id,a.lot_no,a.item_cost_price,a.discount_percent ORDER BY a.discount_percent DESC,a.item_cost_price DESC");

			foreach ($query->result() as $row) {

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

				$has_add=1;

				if (strpos_arr_2021($row->description, $array_find, 1)) {
					if(trim($row->item_gender)=="girl"){
						$row->discount_percent=50;
					}else{
						$row->discount_percent=40;
					}
				}elseif (strpos_arr_2021($row->description, $array_find_male_full_shirt, 1)) {
					if($row->item_cost_price<1090){
						$has_add=0;
					}
				}elseif (strpos_arr_2021($row->description, $array_find_male_half_shirt, 1)) {
					if($row->item_cost_price>540){
						$has_add=0;
					}
				}
				if($has_add==1){
					////////////////////////////////////////////////////////////////////////////
					$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
					$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
					$pcr_challan_check_dis[$row->stock_id]=intval($row->discount_percent);

					if($row->lot_no<190701){
						$pcr_challan_check_all[$row->stock_id][intval($row->item_cost_price)][]=$row;
					}
				}
			}

			////////////////////////////////////////////AUTO LOT BEFORE 190701//////////////////////////////////////////////////////////////////////////////
			$pcr_challan_check_all_stock_id=array();
			foreach ($pcr_challan_check_all as $key => $value) {
				$pcr_challan_check_all_stock_id[]=$key;
			}
			if(count($pcr_challan_check_all_stock_id)>0){




				$consider_lot_no="190100";
				$consider_percentage="100";

				if(isset($config_mrp['CORE_PRODUCT_DISCOUNT_LESSTHAN_LOT'])){
					$consider_lot_no=trim($config_mrp['CORE_PRODUCT_DISCOUNT_LESSTHAN_LOT']);
				}if(isset($config_mrp['CORE_PRODUCT_DISCOUNT_LESSTHAN_LOT_PERCENTAGE'])){
					$consider_percentage=intval($config_mrp['CORE_PRODUCT_DISCOUNT_LESSTHAN_LOT_PERCENTAGE']);
				}

				$consider_sale_id=array();
				$consider_sale_quantity_purchased=0;
				$pcr_challan_check_all_stock_id_str="'".implode("','",$pcr_challan_check_all_stock_id)."'";

				$query = $this->db->query("SELECT sale_id,quantity_purchased FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND acc_location='".LOCATION_CODE."')
				AND stock_id IN(".$pcr_challan_check_all_stock_id_str.") AND lot_no<".$consider_lot_no." 
				AND quantity_purchased>0 AND discount_percent=0 GROUP BY sale_id ORDER BY lot_no ASC,cus_permission ASC, sale_id DESC ");

				foreach ($query->result() as $row) {
					$consider_sale_id[]=$row->sale_id;
					$consider_sale_quantity_purchased+=$row->quantity_purchased;
				}


				$enable_qty=round(($consider_sale_quantity_purchased*$consider_percentage)/100);


				if(count($consider_sale_id)){
					$real_purchase_discount_per_100_saleswise=array();


					foreach ($consider_sale_id as $begain_key => $row_begain) {
						$real_purchase_discount=0;
						$has_purchase_discount=0;
						$sql_payment="SELECT  payment_amount FROM ospos_sales_payments WHERE sale_id ='".$row_begain."' AND payment_type='Purchase Discount' LIMIT 1";
						$query_payment = $this->db->query($sql_payment);
						foreach ($query_payment->result() as $row_payment) {
							$real_purchase_discount=$row_payment->payment_amount;
							$has_purchase_discount=1;
						}
						$real_total_sale_amount_sum=0;
						$real_sales_info_default=array();

						$sql_total_sale="SELECT  *
				FROM ospos_sales_items WHERE sale_id ='".$row_begain."'";
						$query_total_sale = $this->db->query($sql_total_sale);
						foreach ($query_total_sale->result() as $row_total_sale) {
							$real_total_sale_amount_sum+=$row_total_sale->total_sale_amount;
							$real_sales_info_default[]=$row_total_sale;
						}


						$real_purchase_discount_per_100=0;
						if($real_purchase_discount!=0){
							$real_purchase_discount_per_100=number_format(($real_purchase_discount*100)/$real_total_sale_amount_sum,2,'.','');
						}
						$real_purchase_discount_per_100_saleswise[$row_begain]=$real_purchase_discount_per_100;

						foreach ($real_sales_info_default as $dedault_key => $default_value) {
							$vat_enable_price_after_discount_update=round($default_value->total_sale_amount-round(($default_value->total_sale_amount*$real_purchase_discount_per_100)/100));
							$vat_amount_update=number_format($vat_enable_price_after_discount_update*$default_value->vat_percentage/100,2,'.','');

							$update_sale_items_default="UPDATE ospos_sales_items SET
                vat_amount='".mysql_real_escape_string($vat_amount_update)."',
                vat_enable_price_after_discount='".mysql_real_escape_string($vat_enable_price_after_discount_update)."',
                 vat_enable_price_after_discount_cal='1'
                
				WHERE sale_id='".mysql_real_escape_string($default_value->sale_id)."' 
				AND stock_id='".mysql_real_escape_string($default_value->stock_id)."' 
				AND lot_no='".mysql_real_escape_string($default_value->lot_no)."' 
				AND line='".mysql_real_escape_string($default_value->line)."' 
				AND quantity_purchased='".mysql_real_escape_string($default_value->quantity_purchased)."'
				AND item_cost_price='".mysql_real_escape_string($default_value->item_cost_price)."'
				AND total_sale_amount='".mysql_real_escape_string($default_value->total_sale_amount)."'
				AND vat_enable_price_after_discount='".mysql_real_escape_string($default_value->vat_enable_price_after_discount)."'"
							;
							$this->db->query($update_sale_items_default);////////////////NEXT
						}
					}


					if($enable_qty>0){
						///////////////////////////////////////////////////////
						$consider_sale_id_str="'".implode("','",$consider_sale_id)."'";

						$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_str.")
				AND stock_id IN(".$pcr_challan_check_all_stock_id_str.") 
				AND lot_no<".$consider_lot_no."
				AND quantity_purchased>0 AND discount_percent=0 
				ORDER BY lot_no ASC,cus_permission ASC, sale_id DESC ");

						foreach ($query->result() as $value) {

							if($enable_qty>0){

								$enable_qty=$enable_qty-$value->quantity_purchased;

								$discount_percenatage=0;
								$discount_percenatage=$pcr_challan_check_all[$value->stock_id][intval($value->item_cost_price)][0]->discount_percent;

								if($discount_percenatage>0){

									$card_discount_def=0;
									$card_discount_vat_def=0;

									if(intval($real_purchase_discount_per_100_saleswise[$value->sale_id])){
										$card_discount_def=($value->vat_enable_price*intval($real_purchase_discount_per_100_saleswise[$value->sale_id]))/100;
										$card_discount_vat_def=($card_discount_def*$value->vat_percentage)/100;
									}


									$mrp_amount_def=0;
									$item_unit_price_def=$value->item_cost_price-doubleval((($value->item_cost_price*(doubleval($discount_percenatage)))/100));

									$total_discount_def=$value->vat_enable_price-($item_unit_price_def*$value->quantity_purchased);
									$total_sale_amount_def=$value->vat_enable_price-$total_discount_def;

									$permission_vat_enable_price_after_discount_def=$value->vat_enable_price-$total_discount_def;
									$permission_vat_amount_def=($permission_vat_enable_price_after_discount_def*$value->vat_percentage)/100;

									$mrp_amount_def=round($total_discount_def+($total_discount_def*$value->vat_percentage)/100);
									$mrp_amount_def=$mrp_amount_def-round($card_discount_def+$card_discount_vat_def);

									$cash_update_def=round($total_discount_def+($total_discount_def*$value->vat_percentage)/100)-round($card_discount_def+$card_discount_vat_def);



									$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
									$query = $this->db->query($sql);

									foreach ($query->result() as $row) {
										$cash_in_hand=$row->payment_amoount;
									}

									$sale_id_modify_def=$value->sale_id;

									if($cash_in_hand>=round($cash_update_def+129)){


										$update_sql_def="
			UPDATE ospos_sales_items
			SET item_unit_price='".$item_unit_price_def."',
			discount_percent=discount_percent+'".intval($discount_percenatage)."',
			lot_no='".$value->lot_no."',
			total_discount='".$total_discount_def."',
			total_sale_amount='".$total_sale_amount_def."',
			vat_amount='".$permission_vat_amount_def."',
			vat_enable_price_after_discount='".$permission_vat_enable_price_after_discount_def."',
			pcr_lot_no='".$value->lot_no."'
			
			WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";

										$this->db->query($update_sql_def);////////////////NEXT


										$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify_def."' AND payment_type='Cash' LIMIT 1";
										$query = $this->db->query($sql);

										$payment_sale_id=0;
										foreach ($query->result() as $row) {
											$payment_sale_id=$row->sale_id;
											$payment_sale_id_amount=$row->payment_amount;
										}
										if($payment_sale_id){
											$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update_def))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
											$this->db->query($update_query_permission);////////////////NEXT

										}else{
											$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify_def."',
					'Cash',
					'-".round($cash_update_def)."')";
											$this->db->query($insert_sql);////NEXT
										}

										if(intval($card_discount_def)){
											$payment_sale_id=0;
											$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify_def."' AND payment_type='Purchase Discount' LIMIT 1";
											$query = $this->db->query($sql);

											foreach ($query->result() as $row) {
												$payment_sale_id=$row->sale_id;
												$payment_sale_id_amount=$row->payment_amount;
											}

											if($payment_sale_id){

												$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount_def))."' WHERE sale_id='".$sale_id_modify_def."' AND payment_type='Purchase Discount'";
												$this->db->query($update_query_permission);////////////////NEXT
											}else{
												$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify_def."',
					'Purchase Discount',
					'-".round($card_discount_def)."')";
												$this->db->query($insert_sql);////NEXT
											}
										}


										$insert_query_clr="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$discount_percenatage."',
					'".round($cash_update_def)."',
					'".$value->total_sale_amount."',
					'".round($mrp_amount_def)."',
					'".round($mrp_amount_def)."')";
										$this->db->query($insert_query_clr);////NEXT
									}
								}
							}
						}
					}
				}
			}
			$today_sale_count=0;

			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND acc_location='".LOCATION_CODE."') AND quantity_purchased>0 AND discount_percent=0 ORDER BY cus_permission ASC, sale_id DESC ");

			$today_sales=array();

			$total_non_discount_sale=0;
			$has_sync_permission=array();



			foreach ($query->result() as $row) {
				if(trim($row->pcr_lot_no)=="" AND trim($row->mrp_details)=="" AND intval($row->sync_permission)==0){
					if($row->stock_id!="03500002" AND $row->stock_id!="03500001" AND $row->stock_id!="06139020" ){
						$today_sales[intval($row->item_cost_price)][]=$row;
					}
					$today_sale_count++;
				}else{
					$has_sync_permission[$row->sale_id]=$row->sale_id;
				}
				//$total_non_discount_sale+=ceil($row->vat_enable_price-(($row->vat_enable_price*$row->cus_permission)/100));/////////////////////NEXT CONSIDER
				$total_non_discount_sale+=$row->vat_enable_price;/////////////////////NEXT CONSIDER
				//$total_non_discount_sale+=$row->vat_enable_price_after_discount;
			}



			krsort($today_sales);


			$where_not_in_str=" AND stock_id NOT IN ('05306443',
'05307444',
'03500001',
'03500002',
'06139020',
'05341525',
'01114005',
'01122077',
'01111002',
'01123078',
'01123063',
'01124064',
'01111010',
'01122062',
'01125204',
'03714008',
'01123086',
'01141088',
'01125171',
'01111006',
'01122085',
'01124087',
'01123090',
'01124091',
'01122089',
'01125120',
'01105097',
'03616061',
'05322156',
'05322521',
'05325555',
'03135001',
'03135008',
'03136003',
'01108049',
'01109050',
'01106047',
'01110051',
'01107048',
'01109038',
'01108037',
'01110045',
'01107042',
'01108043',
'01108031',
'01109053',
'01114103',
'01122105',
'01123106',
'01113102',
'01151139',
'01106098',
'01105097',
'01107099',
'01108155',
'01150138',
'01115121',
'01118124',
'01120126',
'01119125',
'01122129',
'01124131',
'01114187',
'01116189',
'01125120',
'01124091',
'01114017',
'01112015',
'01122089',
'01111014',
'01123090',
'01146095',
'01122085',
'01114009',
'01123086',
'01113008',
'01125171',
'01112007',
'01146096',
'01124087',
'01141088',
'01111006',
'01112011',
'01111010',
'01122062',
'01123063',
'01114013',
'01124064',
'01141061',
'01113012',
'01125204',
'01113004',
'01112003',
'01124079',
'01141080',
'01111002',
'01125208',
'01122077',
'01114005',
'01123078',
'01120026',
'01119025',
'01116022',
'01114020',
'01118024',
'01117023',
'01121027',
'01117136',
'01122108',
'01118137',
'01116198',
'05339160',
'05308427',
'05306425',
'05309428',
'05307426',
'05353430',
'05310429',
'05341159',
'05339422',
'05322156',
'05325371',
'05323369',
'05341372',
'05340419',
'05324370',
'05322368',
'05351437',
'05318244',
'05316242',
'05319245',
'05317243',
'05307444',
'05305442',
'05308445',
'05306443',
'05322449',
'05341509',
'05324507',
'05322505',
'05325508',
'05323506',
'01010084',
'01008082',
'01009083',
'01021045',
'01018043',
'01017041',
'01019044',
'01017042',
'05318475',
'02639001',
'05323522',
'05322521',
'05360557',
'05341525',
'05340524',
'05325555',
'05323527',
'05322526',
'05341530',
'05340529',
'04915009',
'04913007',
'04916010',
'04914008',
'01039480',
'04964022',
'01024100',
'01022098',
'01023099',
'07024023',
'07022021',
'07023022') ";

			if(LOCATION_CODE=="BNK"){
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01022295' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}

			elseif(LOCATION_CODE=="CHK"){
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id NOT IN ('00533126','00539127','01039377','03439013','04639140','07039020') AND stock_id IN(SELECT stock_id FROM stock_master WHERE description IN('Female Full Fatua','Female Half Fatua','Female Panjabi','Female Punjabi','Girl Frock','Girl Half Fatua','Girl Skirt-Tops','Ladies Kurti','Male Full Fatua','Male Full Shirt','Male Half Fatua','Male Half Shirt','Male Panjabi','Panjabi') GROUP BY stock_id) ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");

			}
			elseif(LOCATION_CODE=="KLB"){

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01017323' AND stock_id !='01039377' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			elseif(LOCATION_CODE=="UTA"){

				$query = $this->db->query("SELECT sale_id,stock_id,description,lot_no,line,quantity_purchased,item_cost_price,item_unit_price,50 AS discount_percent,total_discount,total_sale_amount,vat_enable_price,vat_percentage,vat_amount,vat_enable_price_after_discount,pcr_lot_no,sync_permission,cus_permission
            FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'190101' AND discount_percent>30  AND stock_id !='05039017' 
			AND stock_id IN(SELECT stock_id FROM stock_master WHERE description IN('Female Loose  One piece','Female One piece','Male Panjabi','One Piece','Panjabi') GROUP BY stock_id)
			".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			elseif(LOCATION_CODE=="SDB"){

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01018104' AND stock_id !='01122089' AND stock_id !='01124091' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			else{

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}


			///////////////////////////////////////////////////////////////////////////
			foreach ($query->result() as $row) {
				///////////////////////////////////////////////////////////////////////////
				$has_add=1;

				if (strpos_arr_2021($row->description, $array_find, 1)) {
					$row->discount_percent=40;
				}elseif (strpos_arr_2021($row->description, $array_find_male_half_shirt, 1)) {
					if($row->item_cost_price>540){
						$has_add=0;
					}
				}
				///////////////////////////////////////////////////////////////////////////
				if($has_add==1){
					if($pcr_challan_check_dis[$row->stock_id]==0){
						if($row->discount_percent>50){
							$row->discount_percent=50;
						}

						$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
						$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
					}
				}
			}

			krsort($ospos_sales_items_discount);
			krsort($price_combination);

			$final_today_sales=array();
			$non_found_sales=array();


			foreach ($today_sales as $key => $value) {//////////////////FOR TEST LOCK

				$has_found_dis=0;
				foreach ($ospos_sales_items_discount as $pre_key => $pre_value) {
					if($has_found_dis==0){
						if($pre_key==$key){
							$final_today_sales[$key]=$value;
							$has_found_dis=1;
						}
					}
				}
				if($has_found_dis==0){
					$non_found_sales[$key]=$value;
				}
			}

			foreach ($non_found_sales as $non_key => $non_value) {
				$final_today_sales[$non_key]=$non_value;
			}

			$today_sales=array();
			$today_sales=$final_today_sales;



			$sales_consider_percentage=0;

			if(LOCATION_CODE=="RAJ"){
				$consider_start=6;//////////////////////Change if required/////IF 25% then 3
			}else{
				$consider_start=7;//////////////////////Change if required/////IF 25% then 4
			}


			if($total_non_discount_sale<4000){
				$sales_consider_percentage=0;
			}elseif ($total_non_discount_sale>=4000 AND $total_non_discount_sale<5000){
				$sales_consider_percentage=$consider_start;
			}elseif ($total_non_discount_sale>=5000 AND $total_non_discount_sale<10000){
				$sales_consider_percentage=$consider_start+0.5;
			}elseif ($total_non_discount_sale>=10000 AND $total_non_discount_sale<15000){
				$sales_consider_percentage=$consider_start+1;
			}elseif ($total_non_discount_sale>=15000 AND $total_non_discount_sale<20000){
				$sales_consider_percentage=$consider_start+1.5;
			}elseif ($total_non_discount_sale>=20000 AND $total_non_discount_sale<25000){
				$sales_consider_percentage=$consider_start+2;
			}elseif ($total_non_discount_sale>=25000 AND $total_non_discount_sale<30000){
				$sales_consider_percentage=$consider_start+2.5;
			}elseif ($total_non_discount_sale>=30000 AND $total_non_discount_sale<35000){
				$sales_consider_percentage=$consider_start+3;
			}elseif ($total_non_discount_sale>=35000 AND $total_non_discount_sale<40000){
				$sales_consider_percentage=$consider_start+3.5;
			}elseif ($total_non_discount_sale>=40000 AND $total_non_discount_sale<50000){
				$sales_consider_percentage=$consider_start+4;
			}elseif ($total_non_discount_sale>=50000){
				$sales_consider_percentage=$consider_start+4.5;
			}
			$sales_discount_permission=0;
			if($sales_consider_percentage>0){
				$sales_discount_permission=ceil(($total_non_discount_sale*$sales_consider_percentage)/100);
			}


			foreach ($today_sales as $key => $sale_value) {


				foreach ($sale_value as $sale_key => $value) {

					$sale_id_modify=$value->sale_id;
					$query_reference = $this->db->query("SELECT receipt_no FROM ospos_sales WHERE sale_id='".$value->sale_id."'");
					$receipt_no_sale="";
					foreach ($query_reference->result() as $row_receipt) {
						$receipt_no_sale=$row_receipt->receipt_no;
					}
					$force_reference=substr($receipt_no_sale,3).substr($receipt_no_sale,0,3);

					$info_consider=array();
					$discount_info=array();
					$has_found=0;
					$has_found_direct_product=0;
					$has_found_direct_product_data=array();

					if($sales_discount_permission>100){


						if(array_key_exists ( $value->stock_id, $pcr_challan_check_all)){
							$pcr_challan_check_single=array();
							$pcr_challan_check_single=$pcr_challan_check_all[$value->stock_id][intval($value->item_cost_price)];

							if(count($pcr_challan_check_single)){
								$index=rand(0,count($pcr_challan_check_single)-1);
								if($pcr_challan_check_single[$index]->lot_no>$value->lot_no){
									$pcr_challan_check_single[$index]->lot_no=$value->lot_no;
								}
								$info_consider[]=$pcr_challan_check_single[$index];
								$has_found=1;
								$has_found_direct_product=1;
								$has_found_direct_product_data=$pcr_challan_check_single[$index];

								$permission_calculation=0;
								$permission_calculation=round(($value->vat_enable_price*($pcr_challan_check_single[$index]->discount_percent-$value->cus_permission))/100);
								$sales_discount_permission=$sales_discount_permission-$permission_calculation;
							}
						}

						if($has_found==0){
							if(array_key_exists ( $key, $ospos_sales_items_discount)){

								$has_found=1;

								$discount_info=$ospos_sales_items_discount[$key];
								krsort($discount_info);

								$first_row=0;
								$discount_info_single=array();
								foreach ($discount_info as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}
								$index=rand(0,count($discount_info_single)-1);
								$info_consider[]=$discount_info_single[$index];

								$permission_calculation=0;
								$permission_calculation=round(($value->vat_enable_price*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

								$sales_discount_permission=$sales_discount_permission-$permission_calculation;

							}
						}
						/*


						if($has_found==0){

						$combine_array=array();

						$has_found_combine=0;
						foreach ($price_combination as $price_key => $price_value) {

						foreach ($price_combination as $compare_key => $compare_value) {

						if($has_found_combine==0){
						if($price_value+$compare_value==$key){
						$has_found_combine=1;
						$combine_array[0]=$price_value;
						$combine_array[1]=$compare_value;
						}
						}
						}
						}


						if($has_found_combine==1){

						$first_march=$ospos_sales_items_discount[$combine_array[0]];
						$first_row=0;
						$discount_info_single=array();
						foreach ($first_march as $first_key => $first_value) {

						if($first_row==0){
						$discount_info_single=$first_value;
						$first_row=1;
						}
						}

						$index=rand(0,count($discount_info_single)-1);
						$info_consider[]=$discount_info_single[$index];


						$permission_calculation=0;
						$permission_calculation=round((($discount_info_single[$index]->item_cost_price*$value->quantity_purchased)*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

						$sales_discount_permission=$sales_discount_permission-$permission_calculation;


						$second_march=$ospos_sales_items_discount[$combine_array[1]];
						$first_row=0;
						$discount_info_single=array();
						foreach ($second_march as $first_key => $first_value) {

						if($first_row==0){
						$discount_info_single=$first_value;
						$first_row=1;
						}
						}

						$index=rand(0,count($discount_info_single)-1);
						$info_consider[]=$discount_info_single[$index];

						$permission_calculation=0;
						$permission_calculation=round((($discount_info_single[$index]->item_cost_price*$value->quantity_purchased)*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

						$sales_discount_permission=$sales_discount_permission-$permission_calculation;
						}
						}*/

						if(count($info_consider)>0){

							if(count($info_consider)==1){

								/////MAX LINE////

								$query_line = $this->db->query("SELECT MAX(line) AS line,b.receipt_no AS receipt_no FROM ospos_sales_items AS a LEFT JOIN ospos_sales AS b ON a.sale_id=b.sale_id
			WHERE a.sale_id='".$value->sale_id."'");
								$receipt_no="";
								$next_line=0;
								foreach ($query_line->result() as $row_line) {
									$receipt_no=$row_line->receipt_no;
									$next_line=$row_line->line+1;
								}

								if($has_found_direct_product==1){
									$final_data=$has_found_direct_product_data;
								}else{
									//////FIRST///////////////
									$first_update_data=$ospos_sales_items_discount[intval($info_consider[0]->item_cost_price)];
									$first_row=0;
									$discount_info_single=array();
									foreach ($first_update_data as $first_key => $first_value) {

										if($first_row==0){
											$discount_info_single=$first_value;
											$first_row=1;
										}
									}

									$index=rand(0,count($discount_info_single)-1);

									$final_data=$discount_info_single[$index];
								}

								$item_description=explode("</br>",$final_data->description);

								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$value->line;

								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$value->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;
								$item_vat_amount=$value->vat_amount;
								$item_vat_enable_price_after_discount=$value->vat_enable_price_after_discount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;

								$card_discount=0;
								$card_discount_vat=0;

								$card_discount_add=0;
								$card_discount_vat_add=0;

								if(intval($value->cus_permission)){
									$card_discount=round(($item_vat_enable_price*intval($value->cus_permission))/100);
									$card_discount_vat=number_format(($card_discount*7.5)/100,2,'.','');
								}


								$permission_discount=$item_total_discount;
								$permission_discount_vat=number_format(($permission_discount*7.5)/100,2,'.','');

								$item_vat_enable_price_after_discount=$item_vat_enable_price_after_discount+$card_discount-$permission_discount;
								$item_vat_amount=number_format(($item_vat_enable_price_after_discount*7.5)/100,2,'.','');


								$delete_query="DELETE FROM ospos_sales_items WHERE sale_id='".$value->sale_id."' AND line='".$value->line."' AND stock_id='".$value->stock_id."'";

								$sales_items_data_first="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";



								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();

								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_first="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								$query_moves_original = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($value->stock_id)."' AND a.lot_no='".mysql_real_escape_string($value->lot_no)."' AND a.price='".mysql_real_escape_string($value->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data_original=$query_moves_original->row();




								$date_moves_update_original="20".substr($value->lot_no,0,2)."-".substr($value->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);


								$stock_moves_data_original="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$value->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_original."',
								'".$value->sale_id."',
								'".$value->item_cost_price."',
								'".$force_reference."',
								'-".$value->quantity_purchased."',
								'0',
								'".$stock_moves_lot_data_original->standard_cost."',
								'".$stock_moves_lot_data_original->visible."',
								'".$value->lot_no."',
								'".$stock_moves_lot_data_original->is_imported."',
								'".$stock_moves_lot_data_original->swatch_code."')";

								$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
								$query = $this->db->query($sql);

								foreach ($query->result() as $row) {
									$cash_in_hand=$row->payment_amoount;
								}

								$sale_id_modify=$value->sale_id;

								$cash_update=round($permission_discount+$permission_discount_vat)-round($card_discount+$card_discount_vat);


								if($cash_in_hand>=round($cash_update+129)){

									/////////////////VVI/////////////////////////

									$this->db->query($delete_query);////////////////////////////NEXT
									$this->db->query($sales_items_data_first);////NEXT
									$this->db->query($stock_moves_data_first);////NEXT
									$this->db->query($stock_moves_data_original);////NEXT


									$delete_stock_moves="DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$receipt_no."'";

									$this->db->query($delete_stock_moves);///////////////////////////////NEXT


									$sql_stock="SELECT  * FROM ospos_sales_items WHERE sale_id ='".$value->sale_id."'";
									$query_stock = $this->db->query($sql_stock);

									foreach ($query_stock->result() as $row_stock) {

										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($row_stock->stock_id)."' AND a.lot_no='".mysql_real_escape_string($row_stock->lot_no)."' AND a.price='".mysql_real_escape_string($row_stock->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();

										if($stock_moves_lot_data->standard_cost==0){
											$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
										}

										$stock_moves_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row_stock->sale_id."',
								'".$row_stock->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row_stock->sale_id."',
								'".$row_stock->item_cost_price."',
								'".$receipt_no."',
								'-".$row_stock->quantity_purchased."',
								'".$row_stock->discount_percent."',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$row_stock->lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

										$this->db->query($stock_moves_data);////NEXT

									}

									$sale_id_modify=$value->sale_id;

									$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
									$query = $this->db->query($sql);

									$payment_sale_id=0;
									foreach ($query->result() as $row) {
										$payment_sale_id=$row->sale_id;
										$payment_sale_id_amount=$row->payment_amount;
									}

									if($payment_sale_id){

										$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
										$this->db->query($update_query_permission);////////////////NEXT

									}else{
										$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'".round($cash_update*-1)."')";
										$this->db->query($insert_sql);////NEXT
									}

									if($card_discount>0){

										$payment_sale_id=0;
										$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$payment_sale_id=$row->sale_id;
											$payment_sale_id_amount=$row->payment_amount;
										}



										if($payment_sale_id){

											$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
											$this->db->query($update_query_permission);////////////////NEXT


										}else{
											$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
											$this->db->query($insert_sql);////NEXT

										}
									}

									$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

									$this->db->query($insert_query);////NEXT

									if(!array_key_exists($value->sale_id,$has_sync_permission)){
										$update_sale_sql="UPDATE ospos_sales set clr_sync=1 WHERE sale_id='".$value->sale_id."'";
										$this->db->query($update_sale_sql);
									}

								}
							}elseif(count($info_consider)==2){

								/////MAX LINE////

								$query_line = $this->db->query("SELECT MAX(line) AS line,b.receipt_no AS receipt_no FROM ospos_sales_items AS a LEFT JOIN ospos_sales AS b ON a.sale_id=b.sale_id
			WHERE a.sale_id='".$value->sale_id."'");
								$receipt_no="";
								$next_line=0;
								foreach ($query_line->result() as $row_line) {
									$receipt_no=$row_line->receipt_no;
									$next_line=$row_line->line+1;
								}

								//////FIRST///////////////
								$first_update_data=$ospos_sales_items_discount[intval($info_consider[0]->item_cost_price)];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_update_data as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);

								$final_data=$discount_info_single[$index];

								$item_description=explode("</br>",$final_data->description);


								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$value->line;


								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$final_data->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;

								$item_vat_amount=$value->vat_amount;
								$item_vat_enable_price_after_discount=$value->vat_enable_price_after_discount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;

								$card_discount=0;
								$card_discount_vat=0;

								$card_discount_add=0;
								$card_discount_vat_add=0;

								if(intval($value->cus_permission)){
									$card_discount=round(($value->vat_enable_price*intval($value->cus_permission))/100);
									$card_discount_vat=number_format(($card_discount*7.5)/100,2,'.','');
								}


								$permission_discount=$item_total_discount;
								$permission_discount_vat=number_format(($permission_discount*7.5)/100,2,'.','');

								$item_vat_enable_price_after_discount=round($item_vat_enable_price_after_discount+$card_discount-$permission_discount-($value->vat_enable_price-$item_vat_enable_price));
								$item_vat_amount=number_format(($item_vat_enable_price_after_discount*7.5)/100,2,'.','');


								$delete_query="DELETE FROM ospos_sales_items WHERE sale_id='".$value->sale_id."' AND line='".$value->line."' AND stock_id='".$value->stock_id."'";

								$sales_items_data_first="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";




								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();

								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_first="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								//////SECND///////////////
								$first_update_data=$ospos_sales_items_discount[intval($info_consider[1]->item_cost_price)];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_update_data as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);

								$final_data=$discount_info_single[$index];

								$item_description=explode("</br>",$final_data->description);

								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$next_line;
								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$final_data->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;
								$item_vat_amount=number_format(($item_total_sale_amount*$item_vat_percentage)/100,2,'.','');
								$item_vat_enable_price_after_discount=$item_total_sale_amount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;


								$permission_discount+=$item_total_discount;
								$permission_discount_vat+=number_format(($item_total_discount*7.5)/100,2,'.','');


								$sales_items_data_second="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";


								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();


								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_second="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_second="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_second."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								$query_moves_original = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($value->stock_id)."' AND a.lot_no='".mysql_real_escape_string($value->lot_no)."' AND a.price='".mysql_real_escape_string($value->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data_original=$query_moves_original->row();



								$date_moves_update_original="20".substr($value->lot_no,0,2)."-".substr($value->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);


								$stock_moves_data_original="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$value->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_original."',
								'".$value->sale_id."',
								'".$value->item_cost_price."',
								'".$force_reference."',
								'-".$value->quantity_purchased."',
								'0',
								'".$stock_moves_lot_data_original->standard_cost."',
								'".$stock_moves_lot_data_original->visible."',
								'".$value->lot_no."',
								'".$stock_moves_lot_data_original->is_imported."',
								'".$stock_moves_lot_data_original->swatch_code."')";

								$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
								$query = $this->db->query($sql);

								foreach ($query->result() as $row) {
									$cash_in_hand=$row->payment_amoount;
								}

								$sale_id_modify=$value->sale_id;

								$cash_update=round($permission_discount+$permission_discount_vat)-round($card_discount+$card_discount_vat);

								if($cash_in_hand>=round($cash_update+129)){

									/////////////////VVI/////////////////////////


									$this->db->query($delete_query);////////////////////////////NEXT
									$this->db->query($sales_items_data_first);////NEXT
									$this->db->query($stock_moves_data_first);////NEXT

									$this->db->query($sales_items_data_second);////NEXT
									$this->db->query($stock_moves_data_second);////NEXT
									$this->db->query($stock_moves_data_original);////NEXT


									$delete_stock_moves="DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$receipt_no."'";

									$this->db->query($delete_stock_moves);///////////////////////////////NEXT


									$sql_stock="SELECT  * FROM ospos_sales_items WHERE sale_id ='".$value->sale_id."'";
									$query_stock = $this->db->query($sql_stock);

									foreach ($query_stock->result() as $row_stock) {

										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($row_stock->stock_id)."' AND a.lot_no='".mysql_real_escape_string($row_stock->lot_no)."' AND a.price='".mysql_real_escape_string($row_stock->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();


										if($stock_moves_lot_data->standard_cost==0){
											$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
										}

										$stock_moves_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row_stock->sale_id."',
								'".$row_stock->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row_stock->sale_id."',
								'".$row_stock->item_cost_price."',
								'".$receipt_no."',
								'-".$row_stock->quantity_purchased."',
								'".$row_stock->discount_percent."',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$row_stock->lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

										$this->db->query($stock_moves_data);////NEXT

									}

									$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
									$query = $this->db->query($sql);

									$payment_sale_id=0;
									foreach ($query->result() as $row) {
										$payment_sale_id=$row->sale_id;
										$payment_sale_id_amount=$row->payment_amount;
									}

									if($payment_sale_id){

										$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
										$this->db->query($update_query_permission);////////////////NEXT

									}else{
										$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'".round($cash_update*-1)."')";
										$this->db->query($insert_sql);////NEXT
									}

									if($card_discount>0){

										$payment_sale_id=0;
										$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$payment_sale_id=$row->sale_id;
											$payment_sale_id_amount=$row->payment_amount;
										}

										if($payment_sale_id){

											$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
											$this->db->query($update_query_permission);////////////////NEXT
										}else{
											$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
											$this->db->query($insert_sql);////NEXT
										}
									}
									$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

									$this->db->query($insert_query);////NEXT

									if(!array_key_exists($value->sale_id,$has_sync_permission)){
										$update_sale_sql="UPDATE ospos_sales set clr_sync=1 WHERE sale_id='".$value->sale_id."'";
										$this->db->query($update_sale_sql);
									}

								}
							}
						}

					}
				}
			}


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL))
              AND sync_permission>0 ORDER BY sale_id DESC ");

			$sales_all_data_additional_all=array();
			foreach ($query->result() as $row) {
				$sales_all_data_additional_all[]=$row;
			}

			$loop=0;

			foreach ($sales_all_data_additional_all as $key => $value) {

				$loop++;
				$value->found_lot="";

				if(trim($value->pcr_lot_no)==""){

					if($value->lot_no<'190101'){
						$value->found_lot=$value->lot_no;
					}else{

						$live_data_str=stream_get_contents(fopen("https://pharma.santisirmdc.org/services/includes/product_request.php?stock_id=".$value->stock_id."&item_cost_price=".intval($value->item_cost_price), "r"));

						$live_data_array=array();

						$live_data_array=explode("#",$live_data_str);

						if(trim($live_data_array[0]) AND trim($live_data_array[0])!="NF" AND trim($live_data_array[0])<'200101'){
							$value->found_lot=$live_data_array[0];
						}else{

							$query = $this->db->query("
			SELECT * 
			FROM pcr_moves_check
			WHERE stock_id='".$value->stock_id."' AND price='".$value->item_cost_price."'
			ORDER BY lot_no ASC");

							$temp_lot_array=array();
							foreach ($query->result() as $row) {
								if($row->lot_no<'200101'){
									$temp_lot_array[]=$row->lot_no;
								}
							}

							if(count($temp_lot_array)){

								if($temp_lot_array[0]<='181231'){
									$lot_index=0;
									$value->found_lot=$temp_lot_array[$lot_index];
								}else{
									$lot_index=rand(0,count($temp_lot_array)-1);
									$value->found_lot=$temp_lot_array[$lot_index];
								}
							}
						}

					}


					if(trim($value->found_lot)==""){
						$value->found_lot=$value->lot_no;
					}


				}else{
					$value->found_lot=$value->pcr_lot_no;
				}


				if($value->found_lot>='200101'){
					$value->found_lot="";
				}

				if(trim($value->found_lot)){
					$card_discount=0;
					$card_discount_vat=0;

					if(intval($value->cus_permission)){
						$card_discount=($value->vat_enable_price*intval($value->cus_permission))/100;
						$card_discount_vat=($card_discount*7.5)/100;
					}

					$permission_discount=($value->vat_enable_price*doubleval($value->sync_permission))/100;
					$permission_discount_vat=($permission_discount*7.5)/100;

					$item_unit_price=$value->item_cost_price-doubleval((($value->item_cost_price*(doubleval($value->sync_permission+$value->discount_percent)))/100));

					$total_discount=$value->vat_enable_price-($item_unit_price*$value->quantity_purchased);
					$total_sale_amount=$value->vat_enable_price-$total_discount;

					$permission_vat_amount=$value->vat_amount+$card_discount_vat-$permission_discount_vat;
					$permission_vat_enable_price_after_discount=$value->vat_enable_price_after_discount+$card_discount-$permission_discount;



					$update_sql="
			UPDATE ospos_sales_items
			SET item_unit_price='".$item_unit_price."',
			discount_percent=discount_percent+'".intval($value->sync_permission)."',
			lot_no='".$value->found_lot."',
			total_discount='".$total_discount."',
			total_sale_amount='".$total_sale_amount."',
			vat_amount='".$permission_vat_amount."',
			vat_enable_price_after_discount='".$permission_vat_enable_price_after_discount."',
			pcr_lot_no='".$value->lot_no."',
			sync_permission='0'

			WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";

					$this->db->query($update_sql);////////////////////////////NEXT

					$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$cash_in_hand=$row->payment_amoount;
					}

					$sale_id_modify=$value->sale_id;

					$cash_update=($permission_discount+$permission_discount_vat)-($card_discount+$card_discount_vat);

					if($cash_in_hand>=round($cash_update+129)){


						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
						$query = $this->db->query($sql);

						$payment_sale_id=0;
						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}
						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
							$this->db->query($update_query_permission);////////////////NEXT

						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'-".round($cash_update)."')";
							$this->db->query($insert_sql);////NEXT
						}


						if(intval($value->cus_permission)){
							$payment_sale_id=0;
							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
							$query = $this->db->query($sql);

							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}

							if($payment_sale_id){

								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
								$this->db->query($update_query_permission);////////////////NEXT
							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
								$this->db->query($insert_sql);////NEXT
							}
						}


						$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

						$query = $this->db->query($insert_query);////NEXT

						$update_sale_sql="UPDATE ospos_sales set clr_sync=1
			WHERE sale_id='".$value->sale_id."'";
						$this->db->query($update_sale_sql);

					}
				}else{
					$update_sql="
			UPDATE ospos_sales_items
			SET pcr_lot_no='',
			sync_permission='0'
			WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT
				}
			}

			///////////////////////UPDATE shawpon::30-03-2021///////////////////////////

			if($total_non_discount_sale>=4000){
				$update_sale_sql_flag="UPDATE ospos_sales set clr_sync=1 WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND acc_location='".LOCATION_CODE."'";
				$this->db->query($update_sale_sql_flag);
			}

			//}
			return true;
		}
	}

	function do_regular_sync_user($location_code) {

		$this->db->trans_start();

		///user sync//
		$this->db->from('employees');
		$employee_data_result= $this->db->get();

		$employee_data=array();
		foreach($employee_data_result->result_array() as $row)
		{
			$employee_data[]=$row;
		}
		$this->db->trans_complete();


		if(count($employee_data)){
			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['employees'] =$employee_data;
				$api_data_final = json_encode($api_data);

				$result = $client->__soapCall('regularSyncEmployee', array('data' => $api_data_final));

				$json_data=json_decode($result);

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$default_permission_array[2][]="sales";
					$default_permission_array[2][]="customers";
					$default_permission_array[2][]="reports";
					$default_permission_array[2][]="employees";
					$default_permission_array[2][]="dbbackup";



					$default_permission_array[3][]="sales";
					$default_permission_array[3][]="customers";
					$default_permission_array[3][]="reports";
					$default_permission_array[3][]="employees";


					$default_permission_array[4][]="sales";
					$default_permission_array[4][]="customers";
					$default_permission_array[4][]="reports";
					$default_permission_array[4][]="employees";
					$default_permission_array[4][]="dbbackup";

					$this->db->trans_start();

					if(count($json_data->data->data)){
						foreach ($json_data->data->data as $key => $value) {

							if($key=="update"){
								$this->db->set_dbprefix('');
								foreach ($value as $update_key => $update_value) {
									$success = $this->db->query($update_value);
								}

								$this->db->set_dbprefix('ospos_');

							}if($key=="role_update"){


								$this->db->set_dbprefix('');
								foreach ($value as $role_update_key => $role_update_value) {

									$success = $this->db->query("DELETE FROM ospos_permissions WHERE person_id='".$role_update_key."'");

									foreach ($default_permission_array[$role_update_value] as $ro_key => $ro_value) {
										$insert_query_permission=" INSERT INTO ospos_permissions(
						module_id,
						person_id
						) VALUES('".$ro_value."','".$role_update_key."')";
										$this->db->query($insert_query_permission);
									}
								}
								$this->db->set_dbprefix('ospos_');
							}
							elseif($key=="delete"){
								$this->db->set_dbprefix('');
								foreach ($value as $delete_key => $delete_value) {
									$success = $this->db->query($delete_value);
								}
								$this->db->set_dbprefix('ospos_');

							}elseif($key=="insert"){
								$this->db->set_dbprefix('');

								foreach ($value as $insert_key => $insert_value) {

									$insert_query=" INSERT INTO ospos_people(
					first_name,
					phone_number,
					email,
					is_customer
					) VALUES('".$insert_value->real_name."','".$insert_value->phone."','".$insert_value->email."','0')";

									$this->db->query($insert_query);

									$person_id=$this->db->insert_id();

									$insert_query_employee=" INSERT INTO ospos_employees(
					username,
					password,
					person_id,
					pos_location_code,
					deleted,
					is_update
					) VALUES('".$insert_value->user_id."','".$insert_value->password."','".$person_id."','".LOCATION_CODE."','0','0')";

									$this->db->query($insert_query_employee);

									foreach ($default_permission_array[$insert_value->role_id] as $ro_key => $ro_value) {
										$insert_query_permission=" INSERT INTO ospos_permissions(
														module_id,
														person_id
														) VALUES('".$ro_value."','".$person_id."')";
										$this->db->query($insert_query_permission);
									}

								}
								$this->db->set_dbprefix('ospos_');
							}
						}
						$this->db->trans_complete();
						return $success;
					}
				}
			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}
	function do_regular_sync_fb_customer_otp($location_code) {


		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){

			$this->db->trans_start();
			///user sync//

			$sql = "SELECT * FROM pos_ospos_customer_otp WHERE need_to_sync ='1'";

			$query = $this->db->query($sql);

			$people_data=array();

			foreach ($query->result() as $row) {
				$people_data[]=$row;
			}

			$this->db->trans_complete();


			if(count($people_data)){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['new_customer'] =$people_data;
				$api_data_final = json_encode($api_data);

				$result = $client->__soapCall('regularSyncFaceBookCustomerOTP', array('data' => $api_data_final));




				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data->added_people_id;

					if(count($json_data)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');

						foreach ($json_data as $p_key => $p_value) {

							$this->db->query("UPDATE pos_ospos_customer_otp SET need_to_sync=0,use_status=1 WHERE id='".$p_value."' AND need_to_sync=1");
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						return $success;

					}else{
						return true;
					}
				}
			}else{
				return true;
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}

	function do_regular_sync_fb_customer_otp_update($location_code) {


		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){

			$people_data=array();

			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data['new_customer'] =$people_data;
			$api_data_final = json_encode($api_data);


			$result = $client->__soapCall('regularSyncFaceBookOTPUpdate', array('data' => $api_data_final));


			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;
			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{

				$json_data=json_decode($result)->data->added_people_id;



				if(count($json_data)){
					$this->db->trans_start();
					$this->db->set_dbprefix('');

					//$success = $this->db->query("TRUNCATE TABLE pos_ospos_customer_otp");

					foreach ($json_data as $p_key => $p_value) {


						$query=$this->db->query("
					DELETE FROM  pos_ospos_customer_otp
					WHERE facebook_customer_id='".$p_value->facebook_customer_id."'
					AND mobile_no='".$p_value->mobile_no."' 
					AND otp='".$p_value->otp."'");

						$insert_query="INSERT INTO pos_ospos_customer_otp(facebook_customer_id,
							mobile_no,
							otp,
							use_status,
							is_sms,
							use_date,
							need_to_sync) VALUES("
						."'".$p_value->facebook_customer_id."',"
						."'".$p_value->mobile_no."',"
						."'".$p_value->otp."',"
						."'".$p_value->use_status."',"
						."'".$p_value->is_sms."',"
						."'".$p_value->use_date."',"
						."'0')";
						$success=$this->db->query($insert_query);

					}
					$this->db->set_dbprefix('ospos_');
					$this->db->trans_complete();
					return $success;

				}else{
					return true;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}
	function do_regular_sync_challan($location_code) {


		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);
		if($status==0){
			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data_final = json_encode($api_data);

			$result = $client->__soapCall('regularSyncChallan', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;
			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{
				$json_data=json_decode($result)->data;

				
				echo "<pre>";
				print_r($json_data);
				echo "</pre>";
				exit();
				
				
				if(trim($json_data)){

					
					echo "<pre>";
					print_r($json_data);
					echo "</pre>";
					exit();
					
					
					
					$this->db->trans_start();
					$this->db->set_dbprefix('');
					$success = $this->db->query($json_data);
					$this->db->set_dbprefix('ospos_');
					$this->db->trans_complete();
					
					$api_data2 = array();
					$api_data2['api_user'] = API_USER;
					$api_data2['api_password'] = API_PASSWORD;
					$api_data2['location_code'] =$location_code;
					$api_data2_final = json_encode($api_data2);
					$result2 = $client->__soapCall('regularSyncChallanDone', array('data' => $api_data2_final));
					return $success;

				}else{
					return true;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}


	function roleback_local($loc_code,$current_date){

		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}

		$sale_id_rollback_array=array();

		$query_sql = "SELECT b.sale_id
FROM ospos_sales AS b 
WHERE DATE_FORMAT(b.sale_time,'%Y-%m-%d')='".$current_date."' AND b.acc_location='".$loc_code."' AND sale_id NOT IN ( SELECT sale_id FROM  ospos_sales_roleback_local WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".$loc_code."') ORDER BY b.sale_id ASC ";


		$sales_all_data_rollback=array();

		$query = $this->db->query($query_sql);
		foreach ($query->result() as $row) {
			$sales_all_data_rollback[]=$row->sale_id;
		}

		if(count($sales_all_data_rollback)){
			$sale_id_string_rollback="'".implode("','",$sales_all_data_rollback)."'";

			$query_sql = "SELECT a.*
FROM ospos_sales_items AS a 
WHERE a.sale_id IN(".$sale_id_string_rollback.") ORDER BY a.sale_id,a.line";

			$query = $this->db->query($query_sql);
			foreach ($query->result() as $si_each_value) {
				$insert_query_item="INSERT INTO ospos_sales_items_roleback_local(sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES("
				."'".$si_each_value->sale_id."',"
				."'".$si_each_value->stock_id."',"
				."'".$si_each_value->description."',"
				."'".$si_each_value->lot_no."',"
				."'".$si_each_value->line."',"
				."'".$si_each_value->quantity_purchased."',"
				."'".$si_each_value->item_cost_price."',"
				."'".$si_each_value->item_unit_price."',"
				."'".$si_each_value->discount_percent."',"
				."'".$si_each_value->total_discount."',"
				."'".$si_each_value->total_sale_amount."',"
				."'".$si_each_value->vat_enable_price."',"
				."'".$si_each_value->vat_percentage."',"
				."'".$si_each_value->vat_amount."',"
				."'".$si_each_value->sales_employee_code."',"
				."'".$si_each_value->vat_enable_price_after_discount."',"
				."'".$si_each_value->pcr_lot_no."',"
				."'".$si_each_value->sync_permission."',"
				."'".$si_each_value->cus_permission."')";
				$this->db->query($insert_query_item);///////////////////NEXT
			}


			$query_sql = "SELECT a.*
FROM ospos_sales_payments AS a 
WHERE a.sale_id IN(".$sale_id_string_rollback.") ORDER BY a.sale_id";

			$query = $this->db->query($query_sql);
			foreach ($query->result() as $sp_each_value) {

				$insert_query_payment="INSERT INTO ospos_sales_payments_roleback_local(sale_id,
								payment_type,
								payment_amount,
								bank_id,
								branch_name,
								account_holder_name,
								account_no,
								card_no,
								check_no,
								check_date,
								credit_card_expire_month,
								credit_card_expire_year) VALUES("
				."'".$sp_each_value->sale_id."',"
				."'".$sp_each_value->payment_type."',"
				."'".$sp_each_value->payment_amount."',"
				."'".$sp_each_value->bank_id."',"
				."'".$sp_each_value->branch_name."',"
				."'".$sp_each_value->account_holder_name."',"
				."'".$sp_each_value->account_no."',"
				."'".$sp_each_value->card_no."',"
				."'".$sp_each_value->check_no."',"
				."'".$sp_each_value->check_date."',"
				."'".$sp_each_value->credit_card_expire_month."',"
				."'".$sp_each_value->credit_card_expire_year."')";

				$this->db->query($insert_query_payment);///////////////////NEXT
			}

			$query_sql = "SELECT a.*
FROM ospos_sales AS a 
WHERE a.sale_id IN(".$sale_id_string_rollback.") ORDER BY a.sale_id";

			$query = $this->db->query($query_sql);
			foreach ($query->result() as $sp_each_value) {

				$insert_query_sales="INSERT INTO ospos_sales_roleback_local(sale_time,
					customer_id,
					employee_id,
					comment,
					receive_location,
					sale_id,
					payment_type,
					location,
					is_sync,
					receipt_no,
					acc_location,
					is_global,
					is_delivered,
					is_sync_golbal_flag,
					bag_big,
					bag_medium,
					bag_small,
					is_global_delivery_sync,
					is_permission,
					clr_sync) VALUES("
				."'".$sp_each_value->sale_time."',"
				."'".$sp_each_value->customer_id."',"
				."'".$sp_each_value->employee_id."',"
				."'".$sp_each_value->comment."',"
				."'".$sp_each_value->receive_location."',"
				."'".$sp_each_value->sale_id."',"
				."'".$sp_each_value->payment_type."',"
				."'".$sp_each_value->location."',"
				."'".$sp_each_value->is_sync."',"
				."'".$sp_each_value->receipt_no."',"
				."'".$sp_each_value->acc_location."',"
				."'".$sp_each_value->is_global."',"
				."'".$sp_each_value->is_delivered."',"
				."'".$sp_each_value->is_sync_golbal_flag."',"
				."'".$sp_each_value->bag_big."',"
				."'".$sp_each_value->bag_medium."',"
				."'".$sp_each_value->bag_small."',"
				."'".$sp_each_value->is_global_delivery_sync."',"
				."'".$sp_each_value->is_permission."',"
				."'".$sp_each_value->clr_sync."')";
				$this->db->query($insert_query_sales);///////////////////NEXT
			}
		}

		return 1;
	}

	function roleback_local_sync($location_code) {


		$this->db->trans_start();
		$this->db->set_dbprefix('ospos_');

		$this->db->from('sales_roleback_local');
		$this->db->where(array('role_back_sync'=>0));
		$ospos_sales_result= $this->db->get();

		$ospos_sales_data=array();
		$ospos_sales_items_data=array();
		$ospos_sales_payments_data=array();



		foreach($ospos_sales_result->result_array() as $row){
			$ospos_sales_data[$row['sale_id']]=$row;


			$this->db->from('sales_items_roleback_local');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_items_result= $this->db->get();

			foreach($ospos_sales_items_result->result_array() as $item_row){
				$ospos_sales_items_data[$row['sale_id']][]=$item_row;
			}
			$this->db->from('sales_payments_roleback_local');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_payments_result= $this->db->get();

			foreach($ospos_sales_payments_result->result_array() as $payment_row){
				$ospos_sales_payments_data[$row['sale_id']][]=$payment_row;
			}
		}

		$this->db->trans_complete();

		if(count($ospos_sales_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['ospos_sales'] =$ospos_sales_data;
				$api_data['ospos_sales_items'] =$ospos_sales_items_data;
				$api_data['ospos_sales_payments'] =$ospos_sales_payments_data;

				$api_data_final = json_encode($api_data);
				$result = $client->__soapCall('regularSyncSalesRoleBackAdd', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					//return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data;

					if(count($json_data->added_receipt_no)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');

						foreach ($json_data->added_receipt_no as $r_key => $r_value) {

							$update_query="UPDATE ospos_sales_roleback_local SET role_back_sync=1 WHERE receipt_no='".$r_value."'";
							$success = $this->db->query($update_query);
						}

						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						//return $success;
					}else{
						//return true;
					}
				}


			}else{
				//return 3;///Server not found. please check internet connection.
			}
		}else{
			//return true;
		}



		$this->db->trans_start();
		$this->db->set_dbprefix('ospos_');

		$this->db->from('sales_reprint');
		$this->db->where(array('is_sync'=>0));
		$ospos_sales_result= $this->db->get();

		$ospos_sales_data=array();
		$ospos_sales_items_data=array();
		$ospos_sales_payments_data=array();



		foreach($ospos_sales_result->result_array() as $row){
			$ospos_sales_data[$row['sale_id']]=$row;


			$this->db->from('sales_items_reprint');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_items_result= $this->db->get();

			foreach($ospos_sales_items_result->result_array() as $item_row){
				$ospos_sales_items_data[$row['sale_id']][]=$item_row;
			}
			$this->db->from('sales_payments_reprint');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_payments_result= $this->db->get();

			foreach($ospos_sales_payments_result->result_array() as $payment_row){
				$ospos_sales_payments_data[$row['sale_id']][]=$payment_row;
			}
		}

		$this->db->trans_complete();

		if(count($ospos_sales_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['ospos_sales'] =$ospos_sales_data;
				$api_data['ospos_sales_items'] =$ospos_sales_items_data;
				$api_data['ospos_sales_payments'] =$ospos_sales_payments_data;

				$api_data_final = json_encode($api_data);
				$result = $client->__soapCall('regularSyncSalesReprintAdd', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data;

					if(count($json_data->added_receipt_no)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');

						foreach ($json_data->added_receipt_no as $r_key => $r_value) {

							$update_query="UPDATE ospos_sales_reprint SET is_sync=1 WHERE receipt_no='".$r_value."'";
							$success = $this->db->query($update_query);
						}

						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						return $success;
					}else{
						return true;
					}
				}


			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}




	}



	function do_per_slot($current_date){
		$temporary_off=1;
		//if(CLR_PER_SLOT==1){
		if($temporary_off==0){

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}

			$today_sale_count=0;

			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND acc_location='".LOCATION_CODE."') AND quantity_purchased>0 AND discount_percent=0 ORDER BY cus_permission ASC, sale_id DESC ");

			$today_sales=array();

			$total_non_discount_sale=0;
			$has_sync_permission=array();

			foreach ($query->result() as $row) {
				if(trim($row->pcr_lot_no)=="" AND intval($row->sync_permission)==0){
					$today_sales[intval($row->item_cost_price)][]=$row;
					$today_sale_count++;
				}else{
					$has_sync_permission[$row->sale_id]=$row->sale_id;
				}
				//$total_non_discount_sale+=ceil($row->vat_enable_price-(($row->vat_enable_price*$row->cus_permission)/100));/////////////////////NEXT CONSIDER
				$total_non_discount_sale+=$row->vat_enable_price;/////////////////////NEXT CONSIDER
				//$total_non_discount_sale+=$row->vat_enable_price_after_discount;
			}



			krsort($today_sales);


			$where_not_in_str=" AND stock_id NOT IN ('05306443',
'05307444',
'05341525',
'01114005',
'01122077',
'01111002',
'01123078',
'01123063',
'01124064',
'01111010',
'01122062',
'01125204',
'03714008',
'01123086',
'01141088',
'01125171',
'01111006',
'01122085',
'01124087',
'01123090',
'01124091',
'01122089',
'01125120',
'01105097',
'03616061',
'05322156',
'05322521',
'05325555',
'03135001',
'03135008',
'03136003',
'01108049',
'01109050',
'01106047',
'01110051',
'01107048',
'01109038',
'01108037',
'01110045',
'01107042',
'01108043',
'01108031',
'01109053',
'01114103',
'01122105',
'01123106',
'01113102',
'01151139',
'01106098',
'01105097',
'01107099',
'01108155',
'01150138',
'01115121',
'01118124',
'01120126',
'01119125',
'01122129',
'01124131',
'01114187',
'01116189',
'01125120',
'01124091',
'01114017',
'01112015',
'01122089',
'01111014',
'01123090',
'01146095',
'01122085',
'01114009',
'01123086',
'01113008',
'01125171',
'01112007',
'01146096',
'01124087',
'01141088',
'01111006',
'01112011',
'01111010',
'01122062',
'01123063',
'01114013',
'01124064',
'01141061',
'01113012',
'01125204',
'01113004',
'01112003',
'01124079',
'01141080',
'01111002',
'01125208',
'01122077',
'01114005',
'01123078',
'01120026',
'01119025',
'01116022',
'01114020',
'01118024',
'01117023',
'01121027',
'01117136',
'01122108',
'01118137',
'01116198',
'05339160',
'05308427',
'05306425',
'05309428',
'05307426',
'05353430',
'05310429',
'05341159',
'05339422',
'05322156',
'05325371',
'05323369',
'05341372',
'05340419',
'05324370',
'05322368',
'05351437',
'05318244',
'05316242',
'05319245',
'05317243',
'05307444',
'05305442',
'05308445',
'05306443',
'05322449',
'05341509',
'05324507',
'05322505',
'05325508',
'05323506',
'01010084',
'01008082',
'01009083',
'01021045',
'01018043',
'01017041',
'01019044',
'01017042',
'05318475',
'02639001',
'05323522',
'05322521',
'05360557',
'05341525',
'05340524',
'05325555',
'05323527',
'05322526',
'05341530',
'05340529',
'04915009',
'04913007',
'04916010',
'04914008',
'01039480',
'04964022',
'01024100',
'01022098',
'01023099',
'07024023',
'07022021',
'07023022') ";

			if(LOCATION_CODE=="BNK"){
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01022295' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}

			elseif(LOCATION_CODE=="CHK"){
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id NOT IN ('00533126','00539127','01039377','03439013','04639140','07039020') AND stock_id IN(SELECT stock_id FROM stock_master WHERE description IN('Female Full Fatua','Female Half Fatua','Female Panjabi','Female Punjabi','Girl Frock','Girl Half Fatua','Girl Skirt-Tops','Ladies Kurti','Male Full Fatua','Male Full Shirt','Male Half Fatua','Male Half Shirt','Male Panjabi','Panjabi') GROUP BY stock_id) ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");

			}
			elseif(LOCATION_CODE=="KLB"){

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01017323' AND stock_id !='01039377' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			elseif(LOCATION_CODE=="UTA"){

				$query = $this->db->query("SELECT sale_id,stock_id,description,lot_no,line,quantity_purchased,item_cost_price,item_unit_price,50 AS discount_percent,total_discount,total_sale_amount,vat_enable_price,vat_percentage,vat_amount,vat_enable_price_after_discount,pcr_lot_no,sync_permission,cus_permission
            FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'190101' AND discount_percent>30  AND stock_id !='05039017' 
			AND stock_id IN(SELECT stock_id FROM stock_master WHERE description IN('Female Loose  One piece','Female One piece','Male Panjabi','One Piece','Panjabi') GROUP BY stock_id)
			".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			elseif(LOCATION_CODE=="SDB"){

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 AND stock_id !='01018104' AND stock_id !='01122089' AND stock_id !='01124091' ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}
			else{

				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')>='2020-11-15' AND acc_location='".LOCATION_CODE."') AND lot_no<'200101' AND discount_percent>30 ".$where_not_in_str."
			GROUP BY stock_id,item_cost_price,discount_percent
			ORDER BY stock_id ASC, lot_no ASC,sale_id DESC,discount_percent DESC");
			}

			$ospos_sales_items_discount=array();

			$price_combination=array();

			///////////////////////////////////////////////////////////////////////////
			function strpos_arr($haystack, $needle) {
				if(!is_array($needle)) $needle = array($needle);
				foreach($needle as $what) {
					if(($pos = strpos($haystack, $what))!==false) return $pos;
				}
				return false;
			}
			///////////////////////////////////////////////////////////////////////////
			foreach ($query->result() as $row) {
				///////////////////////////////////////////////////////////////////////////
				$array_find[]="One piece";
				$array_find[]="One Piece";
				$array_find[]="Tunic";
				if (strpos_arr($row->description, $array_find, 1)) {
					$row->discount_percent=40;
				}
				///////////////////////////////////////////////////////////////////////////
				$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
				$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
			}

			$query = $this->db->query("SELECT a.stock_id,a.lot_no,CAST(a.item_cost_price AS SIGNED) AS item_cost_price,a.discount_percent,a.challan_no,a.loc_code,IF(b.item_size_id> 0,CONCAT(c.description,'</br>',b.description,' - ',d.size),CONCAT(c.description,'</br>',b.description)) AS description,b.gender AS item_gender
			FROM pcr_challan_check AS a
			LEFT JOIN stock_master AS b ON a.stock_id=b.stock_id
			LEFT JOIN stock_category AS c ON b.category_id=c.category_id
			LEFT JOIN pos_item_sizes AS d ON b.item_size_id=d.id 
			WHERE a.discount_percent>0 AND a.loc_code='".LOCATION_CODE."' GROUP BY a.stock_id,a.lot_no,a.item_cost_price,a.discount_percent ORDER BY a.item_cost_price DESC,a.discount_percent DESC");

			foreach ($query->result() as $row) {
				///////////////////////////////////////////////////////////////////////////
				$array_find[]="One piece";
				$array_find[]="One Piece";
				$array_find[]="Tunic";
				if (strpos_arr($row->description, $array_find, 1)) {
					if(trim($row->item_gender)=="girl"){
						$row->discount_percent=50;
					}else{
						$row->discount_percent=40;
					}
				}
				////////////////////////////////////////////////////////////////////////////
				$ospos_sales_items_discount[intval($row->item_cost_price)][intval($row->discount_percent)][]=$row;
				$price_combination[intval($row->item_cost_price)]=intval($row->item_cost_price);
			}
			krsort($ospos_sales_items_discount);
			krsort($price_combination);

			$final_today_sales=array();
			$non_found_sales=array();

			foreach ($today_sales as $key => $value) {

				$has_found_dis=0;
				foreach ($ospos_sales_items_discount as $pre_key => $pre_value) {
					if($has_found_dis==0){
						if($pre_key==$key){
							$final_today_sales[$key]=$value;
							$has_found_dis=1;
						}
					}
				}
				if($has_found_dis==0){
					$non_found_sales[$key]=$value;
				}
			}

			foreach ($non_found_sales as $non_key => $non_value) {
				$final_today_sales[$non_key]=$non_value;
			}

			$today_sales=array();
			$today_sales=$final_today_sales;



			$sales_consider_percentage=0;

			if(LOCATION_CODE=="RAJ"){
				$consider_start=7;//////////////////////Change if required/////IF 25% then 3
			}else{
				$consider_start=8;//////////////////////Change if required/////IF 25% then 4
			}


			if($total_non_discount_sale<4000){
				$sales_consider_percentage=0;
			}elseif ($total_non_discount_sale>=4000 AND $total_non_discount_sale<10000){
				$sales_consider_percentage=$consider_start;
			}elseif ($total_non_discount_sale>=10000 AND $total_non_discount_sale<15000){
				$sales_consider_percentage=$consider_start+1;
			}elseif ($total_non_discount_sale>=15000 AND $total_non_discount_sale<20000){
				$sales_consider_percentage=$consider_start+1.5;
			}elseif ($total_non_discount_sale>=20000 AND $total_non_discount_sale<25000){
				$sales_consider_percentage=$consider_start+2;
			}elseif ($total_non_discount_sale>=25000 AND $total_non_discount_sale<30000){
				$sales_consider_percentage=$consider_start+2.5;
			}elseif ($total_non_discount_sale>=30000 AND $total_non_discount_sale<35000){
				$sales_consider_percentage=$consider_start+3;
			}elseif ($total_non_discount_sale>=35000 AND $total_non_discount_sale<40000){
				$sales_consider_percentage=$consider_start+3.5;
			}elseif ($total_non_discount_sale>=40000 AND $total_non_discount_sale<50000){
				$sales_consider_percentage=$consider_start+4;
			}elseif ($total_non_discount_sale>=50000){
				$sales_consider_percentage=$consider_start+4.5;
			}
			$sales_discount_permission=0;
			if($sales_consider_percentage>0){
				$sales_discount_permission=ceil(($total_non_discount_sale*$sales_consider_percentage)/100);
			}




			foreach ($today_sales as $key => $sale_value) {


				foreach ($sale_value as $sale_key => $value) {

					$sale_id_modify=$value->sale_id;
					$query_reference = $this->db->query("SELECT receipt_no FROM ospos_sales WHERE sale_id='".$value->sale_id."'");
					$receipt_no_sale="";
					foreach ($query_reference->result() as $row_receipt) {
						$receipt_no_sale=$row_receipt->receipt_no;
					}
					$force_reference=substr($receipt_no_sale,3).substr($receipt_no_sale,0,3);

					$info_consider=array();
					$discount_info=array();
					$has_found=0;




					if($sales_discount_permission>100){

						if(array_key_exists ( $key, $ospos_sales_items_discount)){

							$has_found=1;

							$discount_info=$ospos_sales_items_discount[$key];
							krsort($discount_info);

							$first_row=0;
							$discount_info_single=array();
							foreach ($discount_info as $first_key => $first_value) {

								if($first_row==0){
									$discount_info_single=$first_value;
									$first_row=1;
								}
							}

							$index=rand(0,count($discount_info_single)-1);
							$info_consider[]=$discount_info_single[$index];

							$permission_calculation=0;
							$permission_calculation=round(($value->vat_enable_price*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

							$sales_discount_permission=$sales_discount_permission-$permission_calculation;

						}

						if($has_found==0){

							$combine_array=array();

							$has_found_combine=0;
							foreach ($price_combination as $price_key => $price_value) {

								foreach ($price_combination as $compare_key => $compare_value) {

									if($has_found_combine==0){
										if($price_value+$compare_value==$key){
											$has_found_combine=1;
											$combine_array[0]=$price_value;
											$combine_array[1]=$compare_value;
										}
									}
								}
							}


							if($has_found_combine==1){

								$first_march=$ospos_sales_items_discount[$combine_array[0]];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_march as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);
								$info_consider[]=$discount_info_single[$index];


								$permission_calculation=0;
								$permission_calculation=round((($discount_info_single[$index]->item_cost_price*$value->quantity_purchased)*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

								$sales_discount_permission=$sales_discount_permission-$permission_calculation;


								$second_march=$ospos_sales_items_discount[$combine_array[1]];
								$first_row=0;
								$discount_info_single=array();
								foreach ($second_march as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);
								$info_consider[]=$discount_info_single[$index];

								$permission_calculation=0;
								$permission_calculation=round((($discount_info_single[$index]->item_cost_price*$value->quantity_purchased)*($discount_info_single[$index]->discount_percent-$value->cus_permission))/100);

								$sales_discount_permission=$sales_discount_permission-$permission_calculation;
							}
						}
						if(count($info_consider)>0){

							if(count($info_consider)==1){

								/////MAX LINE////

								$query_line = $this->db->query("SELECT MAX(line) AS line,b.receipt_no AS receipt_no FROM ospos_sales_items AS a LEFT JOIN ospos_sales AS b ON a.sale_id=b.sale_id
			WHERE a.sale_id='".$value->sale_id."'");
								$receipt_no="";
								$next_line=0;
								foreach ($query_line->result() as $row_line) {
									$receipt_no=$row_line->receipt_no;
									$next_line=$row_line->line+1;
								}

								//////FIRST///////////////
								$first_update_data=$ospos_sales_items_discount[intval($info_consider[0]->item_cost_price)];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_update_data as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);

								$final_data=$discount_info_single[$index];

								$item_description=explode("</br>",$final_data->description);


								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$value->line;

								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$value->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;
								$item_vat_amount=$value->vat_amount;
								$item_vat_enable_price_after_discount=$value->vat_enable_price_after_discount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;

								$card_discount=0;
								$card_discount_vat=0;

								$card_discount_add=0;
								$card_discount_vat_add=0;

								if(intval($value->cus_permission)){
									$card_discount=round(($item_vat_enable_price*intval($value->cus_permission))/100);
									$card_discount_vat=number_format(($card_discount*7.5)/100,2,'.','');
								}


								$permission_discount=$item_total_discount;
								$permission_discount_vat=number_format(($permission_discount*7.5)/100,2,'.','');

								$item_vat_enable_price_after_discount=$item_vat_enable_price_after_discount+$card_discount-$permission_discount;
								$item_vat_amount=number_format(($item_vat_enable_price_after_discount*7.5)/100,2,'.','');


								$delete_query="DELETE FROM ospos_sales_items WHERE sale_id='".$value->sale_id."' AND line='".$value->line."' AND stock_id='".$value->stock_id."'";

								$sales_items_data_first="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";



								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();

								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_first="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								$query_moves_original = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($value->stock_id)."' AND a.lot_no='".mysql_real_escape_string($value->lot_no)."' AND a.price='".mysql_real_escape_string($value->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data_original=$query_moves_original->row();




								$date_moves_update_original="20".substr($value->lot_no,0,2)."-".substr($value->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);


								$stock_moves_data_original="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$value->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_original."',
								'".$value->sale_id."',
								'".$value->item_cost_price."',
								'".$force_reference."',
								'-".$value->quantity_purchased."',
								'0',
								'".$stock_moves_lot_data_original->standard_cost."',
								'".$stock_moves_lot_data_original->visible."',
								'".$value->lot_no."',
								'".$stock_moves_lot_data_original->is_imported."',
								'".$stock_moves_lot_data_original->swatch_code."')";

								$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
								$query = $this->db->query($sql);

								foreach ($query->result() as $row) {
									$cash_in_hand=$row->payment_amoount;
								}

								$sale_id_modify=$value->sale_id;

								$cash_update=round($permission_discount+$permission_discount_vat)-round($card_discount+$card_discount_vat);


								if($cash_in_hand>=round($cash_update+129)){

									/////////////////VVI/////////////////////////


									$this->db->query($delete_query);////////////////////////////NEXT
									$this->db->query($sales_items_data_first);////NEXT
									$this->db->query($stock_moves_data_first);////NEXT
									$this->db->query($stock_moves_data_original);////NEXT


									$delete_stock_moves="DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$receipt_no."'";

									$this->db->query($delete_stock_moves);///////////////////////////////NEXT


									$sql_stock="SELECT  * FROM ospos_sales_items WHERE sale_id ='".$value->sale_id."'";
									$query_stock = $this->db->query($sql_stock);

									foreach ($query_stock->result() as $row_stock) {

										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($row_stock->stock_id)."' AND a.lot_no='".mysql_real_escape_string($row_stock->lot_no)."' AND a.price='".mysql_real_escape_string($row_stock->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();

										if($stock_moves_lot_data->standard_cost==0){
											$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
										}

										$stock_moves_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row_stock->sale_id."',
								'".$row_stock->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row_stock->sale_id."',
								'".$row_stock->item_cost_price."',
								'".$receipt_no."',
								'-".$row_stock->quantity_purchased."',
								'".$row_stock->discount_percent."',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$row_stock->lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

										$this->db->query($stock_moves_data);////NEXT

									}

									$sale_id_modify=$value->sale_id;

									$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
									$query = $this->db->query($sql);

									$payment_sale_id=0;
									foreach ($query->result() as $row) {
										$payment_sale_id=$row->sale_id;
										$payment_sale_id_amount=$row->payment_amount;
									}

									if($payment_sale_id){

										$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
										$this->db->query($update_query_permission);////////////////NEXT

									}else{
										$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'".round($cash_update*-1)."')";
										$this->db->query($insert_sql);////NEXT
									}

									if($card_discount>0){

										$payment_sale_id=0;
										$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$payment_sale_id=$row->sale_id;
											$payment_sale_id_amount=$row->payment_amount;
										}



										if($payment_sale_id){

											$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
											$this->db->query($update_query_permission);////////////////NEXT


										}else{
											$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
											$this->db->query($insert_sql);////NEXT

										}
									}

									$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

									$this->db->query($insert_query);////NEXT

									if(!array_key_exists($value->sale_id,$has_sync_permission)){
										$update_sale_sql="UPDATE ospos_sales set clr_sync=1 WHERE sale_id='".$value->sale_id."'";
										$this->db->query($update_sale_sql);
									}

								}
							}elseif(count($info_consider)==2){

								/////MAX LINE////

								$query_line = $this->db->query("SELECT MAX(line) AS line,b.receipt_no AS receipt_no FROM ospos_sales_items AS a LEFT JOIN ospos_sales AS b ON a.sale_id=b.sale_id
			WHERE a.sale_id='".$value->sale_id."'");
								$receipt_no="";
								$next_line=0;
								foreach ($query_line->result() as $row_line) {
									$receipt_no=$row_line->receipt_no;
									$next_line=$row_line->line+1;
								}

								//////FIRST///////////////
								$first_update_data=$ospos_sales_items_discount[intval($info_consider[0]->item_cost_price)];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_update_data as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);

								$final_data=$discount_info_single[$index];

								$item_description=explode("</br>",$final_data->description);


								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$value->line;


								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$final_data->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;

								$item_vat_amount=$value->vat_amount;
								$item_vat_enable_price_after_discount=$value->vat_enable_price_after_discount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;

								$card_discount=0;
								$card_discount_vat=0;

								$card_discount_add=0;
								$card_discount_vat_add=0;

								if(intval($value->cus_permission)){
									$card_discount=round(($value->vat_enable_price*intval($value->cus_permission))/100);
									$card_discount_vat=number_format(($card_discount*7.5)/100,2,'.','');
								}


								$permission_discount=$item_total_discount;
								$permission_discount_vat=number_format(($permission_discount*7.5)/100,2,'.','');

								$item_vat_enable_price_after_discount=round($item_vat_enable_price_after_discount+$card_discount-$permission_discount-($value->vat_enable_price-$item_vat_enable_price));
								$item_vat_amount=number_format(($item_vat_enable_price_after_discount*7.5)/100,2,'.','');


								$delete_query="DELETE FROM ospos_sales_items WHERE sale_id='".$value->sale_id."' AND line='".$value->line."' AND stock_id='".$value->stock_id."'";

								$sales_items_data_first="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";




								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();

								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_first="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								//////SECND///////////////
								$first_update_data=$ospos_sales_items_discount[intval($info_consider[1]->item_cost_price)];
								$first_row=0;
								$discount_info_single=array();
								foreach ($first_update_data as $first_key => $first_value) {

									if($first_row==0){
										$discount_info_single=$first_value;
										$first_row=1;
									}
								}

								$index=rand(0,count($discount_info_single)-1);

								$final_data=$discount_info_single[$index];

								$item_description=explode("</br>",$final_data->description);

								$item_stock_id=$final_data->stock_id;
								$item_description1=$item_description[0];
								$item_description2=$item_description[1];
								$item_lot_no=$final_data->lot_no;
								$item_line=$next_line;
								$item_quantity_purchase=$value->quantity_purchased;
								$item_item_cost_price=$final_data->item_cost_price;
								$item_discount_percent=$final_data->discount_percent;
								$item_item_unit_price=round($item_item_cost_price-($item_item_cost_price*$item_discount_percent)/100);
								$item_total_discount=round(($item_item_cost_price-$item_item_unit_price)*$item_quantity_purchase);
								$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
								$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);
								$item_vat_percentage=7.5;
								$item_vat_amount=number_format(($item_total_sale_amount*$item_vat_percentage)/100,2,'.','');
								$item_vat_enable_price_after_discount=$item_total_sale_amount;
								$item_pcr_lot_no=$value->lot_no."#".$value->stock_id."#".$value->item_cost_price;
								$item_sync_permission=0;
								$item_cus_permission=0;


								$permission_discount+=$item_total_discount;
								$permission_discount_vat+=number_format(($item_total_discount*7.5)/100,2,'.','');


								$sales_items_data_second="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";


								$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data=$query_moves->row();


								if($stock_moves_lot_data->standard_cost==0){
									$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
								}

								$date_moves_update_second="20".substr($item_lot_no,0,2)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$stock_moves_data_second="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_second."',
								'".$value->sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";



								$query_moves_original = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($value->stock_id)."' AND a.lot_no='".mysql_real_escape_string($value->lot_no)."' AND a.price='".mysql_real_escape_string($value->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

								$stock_moves_lot_data_original=$query_moves_original->row();



								$date_moves_update_original="20".substr($value->lot_no,0,2)."-".substr($value->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);


								$stock_moves_data_original="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$value->sale_id."',
								'".$value->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_original."',
								'".$value->sale_id."',
								'".$value->item_cost_price."',
								'".$force_reference."',
								'-".$value->quantity_purchased."',
								'0',
								'".$stock_moves_lot_data_original->standard_cost."',
								'".$stock_moves_lot_data_original->visible."',
								'".$value->lot_no."',
								'".$stock_moves_lot_data_original->is_imported."',
								'".$stock_moves_lot_data_original->swatch_code."')";

								$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
								$query = $this->db->query($sql);

								foreach ($query->result() as $row) {
									$cash_in_hand=$row->payment_amoount;
								}

								$sale_id_modify=$value->sale_id;

								$cash_update=round($permission_discount+$permission_discount_vat)-round($card_discount+$card_discount_vat);

								if($cash_in_hand>=round($cash_update+129)){

									/////////////////VVI/////////////////////////


									$this->db->query($delete_query);////////////////////////////NEXT
									$this->db->query($sales_items_data_first);////NEXT
									$this->db->query($stock_moves_data_first);////NEXT

									$this->db->query($sales_items_data_second);////NEXT
									$this->db->query($stock_moves_data_second);////NEXT
									$this->db->query($stock_moves_data_original);////NEXT


									$delete_stock_moves="DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$receipt_no."'";

									$this->db->query($delete_stock_moves);///////////////////////////////NEXT


									$sql_stock="SELECT  * FROM ospos_sales_items WHERE sale_id ='".$value->sale_id."'";
									$query_stock = $this->db->query($sql_stock);

									foreach ($query_stock->result() as $row_stock) {

										$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($row_stock->stock_id)."' AND a.lot_no='".mysql_real_escape_string($row_stock->lot_no)."' AND a.price='".mysql_real_escape_string($row_stock->item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

										$stock_moves_lot_data=$query_moves->row();


										if($stock_moves_lot_data->standard_cost==0){
											$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
										}

										$stock_moves_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row_stock->sale_id."',
								'".$row_stock->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row_stock->sale_id."',
								'".$row_stock->item_cost_price."',
								'".$receipt_no."',
								'-".$row_stock->quantity_purchased."',
								'".$row_stock->discount_percent."',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$row_stock->lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

										$this->db->query($stock_moves_data);////NEXT

									}

									$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
									$query = $this->db->query($sql);

									$payment_sale_id=0;
									foreach ($query->result() as $row) {
										$payment_sale_id=$row->sale_id;
										$payment_sale_id_amount=$row->payment_amount;
									}

									if($payment_sale_id){

										$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
										$this->db->query($update_query_permission);////////////////NEXT

									}else{
										$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'".round($cash_update*-1)."')";
										$this->db->query($insert_sql);////NEXT
									}

									if($card_discount>0){

										$payment_sale_id=0;
										$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
										$query = $this->db->query($sql);

										foreach ($query->result() as $row) {
											$payment_sale_id=$row->sale_id;
											$payment_sale_id_amount=$row->payment_amount;
										}

										if($payment_sale_id){

											$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
											$this->db->query($update_query_permission);////////////////NEXT
										}else{
											$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
											$this->db->query($insert_sql);////NEXT
										}
									}
									$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

									$this->db->query($insert_query);////NEXT

									if(!array_key_exists($value->sale_id,$has_sync_permission)){
										$update_sale_sql="UPDATE ospos_sales set clr_sync=1 WHERE sale_id='".$value->sale_id."'";
										$this->db->query($update_sale_sql);
									}

								}
							}
						}

					}
				}
			}


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL))
              AND sync_permission>0 ORDER BY sale_id DESC ");

			$sales_all_data_additional_all=array();
			foreach ($query->result() as $row) {
				$sales_all_data_additional_all[]=$row;
			}

			$loop=0;

			foreach ($sales_all_data_additional_all as $key => $value) {

				$loop++;
				$value->found_lot="";

				if(trim($value->pcr_lot_no)==""){

					if($value->lot_no<'190101'){
						$value->found_lot=$value->lot_no;
					}else{

						$live_data_str=stream_get_contents(fopen("https://pharma.santisirmdc.org/services/includes/product_request.php?stock_id=".$value->stock_id."&item_cost_price=".intval($value->item_cost_price), "r"));

						$live_data_array=array();

						$live_data_array=explode("#",$live_data_str);

						if(trim($live_data_array[0]) AND trim($live_data_array[0])!="NF" AND trim($live_data_array[0])<'200101'){
							$value->found_lot=$live_data_array[0];
						}else{

							$query = $this->db->query("
			SELECT * 
			FROM pcr_moves_check
			WHERE stock_id='".$value->stock_id."' AND price='".$value->item_cost_price."'
			ORDER BY lot_no ASC");

							$temp_lot_array=array();
							foreach ($query->result() as $row) {
								if($row->lot_no<'200101'){
									$temp_lot_array[]=$row->lot_no;
								}
							}

							if(count($temp_lot_array)){

								if($temp_lot_array[0]<='181231'){
									$lot_index=0;
									$value->found_lot=$temp_lot_array[$lot_index];
								}else{
									$lot_index=rand(0,count($temp_lot_array)-1);
									$value->found_lot=$temp_lot_array[$lot_index];
								}
							}
						}

					}


					if(trim($value->found_lot)==""){
						$value->found_lot=$value->lot_no;
					}


				}else{
					$value->found_lot=$value->pcr_lot_no;
				}


				if($value->found_lot>='200101'){
					$value->found_lot="";
				}

				if(trim($value->found_lot)){
					$card_discount=0;
					$card_discount_vat=0;

					if(intval($value->cus_permission)){
						$card_discount=($value->vat_enable_price*intval($value->cus_permission))/100;
						$card_discount_vat=($card_discount*7.5)/100;
					}

					$permission_discount=($value->vat_enable_price*doubleval($value->sync_permission))/100;
					$permission_discount_vat=($permission_discount*7.5)/100;

					$item_unit_price=$value->item_cost_price-doubleval((($value->item_cost_price*(doubleval($value->sync_permission+$value->discount_percent)))/100));

					$total_discount=$value->vat_enable_price-($item_unit_price*$value->quantity_purchased);
					$total_sale_amount=$value->vat_enable_price-$total_discount;

					$permission_vat_amount=$value->vat_amount+$card_discount_vat-$permission_discount_vat;
					$permission_vat_enable_price_after_discount=$value->vat_enable_price_after_discount+$card_discount-$permission_discount;



					$update_sql="
			UPDATE ospos_sales_items
			SET item_unit_price='".$item_unit_price."',
			discount_percent=discount_percent+'".intval($value->sync_permission)."',
			lot_no='".$value->found_lot."',
			total_discount='".$total_discount."',
			total_sale_amount='".$total_sale_amount."',
			vat_amount='".$permission_vat_amount."',
			vat_enable_price_after_discount='".$permission_vat_enable_price_after_discount."',
			pcr_lot_no='".$value->lot_no."',
			sync_permission='0'

			WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";

					$this->db->query($update_sql);////////////////////////////NEXT

					$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$cash_in_hand=$row->payment_amoount;
					}

					$sale_id_modify=$value->sale_id;

					$cash_update=($permission_discount+$permission_discount_vat)-($card_discount+$card_discount_vat);

					if($cash_in_hand>=round($cash_update+129)){


						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
						$query = $this->db->query($sql);

						$payment_sale_id=0;
						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}
						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
							$this->db->query($update_query_permission);////////////////NEXT

						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Cash',
					'-".round($cash_update)."')";
							$this->db->query($insert_sql);////NEXT
						}


						if(intval($value->cus_permission)){
							$payment_sale_id=0;
							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
							$query = $this->db->query($sql);

							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}

							if($payment_sale_id){

								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($card_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
								$this->db->query($update_query_permission);////////////////NEXT
							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$sale_id_modify."',
					'Purchase Discount',
					'-".round($card_discount)."')";
								$this->db->query($insert_sql);////NEXT
							}
						}


						$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$value->sale_id."',
					'".$value->vat_enable_price."',
					'".$value->discount_percent."',
					'".round($cash_update)."',
					'".$value->total_sale_amount."',
					'".round($cash_update)."',
					'".round($cash_update)."')";

						$query = $this->db->query($insert_query);////NEXT

						$update_sale_sql="UPDATE ospos_sales set clr_sync=1
			WHERE sale_id='".$value->sale_id."'";
						$this->db->query($update_sale_sql);

					}
				}else{
					$update_sql="
			UPDATE ospos_sales_items
			SET pcr_lot_no='',
			sync_permission='0'
			WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT
				}
			}

			///////////////////////UPDATE shawpon::30-03-2021///////////////////////////

			if($total_non_discount_sale>=4000){
				$update_sale_sql_flag="UPDATE ospos_sales set clr_sync=1 WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND acc_location='".LOCATION_CODE."'";
				$this->db->query($update_sale_sql_flag);
			}

		}
		return true;
	}


	function do_per_slot_bogo($current_date){

		$current_directory = getcwd();

		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_BOGO_ACTIVE']=0;
		}

		if($config_mrp['CORE_BOGO_ACTIVE']==1){


			$bogo_stock_id_datatable_data = file_get_contents("https://pharma.santisirmdc.org/services/includes/bogo_stock_id_datatable_request.php?loc_code=".LOCATION_CODE);


			if($bogo_stock_id_datatable_data=="NODATA"){
				$this->db->query("TRUNCATE TABLE bogo_stock_id_datatable");
			}else{
				if(trim($bogo_stock_id_datatable_data)){
					if(count(unserialize($bogo_stock_id_datatable_data))){
						$this->db->query("TRUNCATE TABLE bogo_stock_id_datatable");
						$insert_query="INSERT INTO bogo_stock_id_datatable(stock_id,lot_no,price) VALUES ";
						$insert_query_array=array();
						foreach (unserialize($bogo_stock_id_datatable_data) as $key => $value) {
							$insert_query_array[]=" ("."'".$value['stock_id']."','".$value['lot_no']."','".$value['price']."') ";
						}
						$insert_query.=implode(",",$insert_query_array);
						$this->db->query($insert_query);
					}
				}
			}

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}

			$today_sale_count=0;

			/* DATABASE QUERY LIVE SERVER///
			SELECT stock_id,lot_no,price FROM stock_moves AS a
			WHERE a.stock_id IN('05301304',
			'05304288',
			'05305289',
			'05306290',
			'05307302',
			'05308303',
			'05309517',
			'05310518',
			'05339574',
			'05344520',
			'05353519',
			'05356291',
			'05362549')
			GROUP BY stock_id,price,lot_no
			ORDER BY price DESC,stock_id ASC,lot_no ASC */

			$bogo_stock_ids=array();


			$query_bogo = $this->db->query("SELECT * FROM bogo_stock_id_datatable");

			foreach ($query_bogo->result() as $row_bogo) {
				$bogo_stock_ids[$row_bogo->price][$row_bogo->stock_id][]=$row_bogo->lot_no;
			}

			krsort($bogo_stock_ids);

			$non_consider_stock_id=array();

			foreach ($bogo_stock_ids as $key => $value) {
				foreach ($value as $item_key => $item_value) {
					if (!in_array($item_key, $non_consider_stock_id)){
						$non_consider_stock_id[]=$item_key;
					}
				}
			}

			$non_consider_stock_id_str="";
			if(count($non_consider_stock_id)){
				$non_consider_stock_id_str=" AND stock_id NOT IN ('".implode("','",$non_consider_stock_id)."')";
			}

			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL) AND (is_permission=0 OR is_permission IS NULL) AND acc_location='".LOCATION_CODE."') AND quantity_purchased>0 AND discount_percent=0  AND (pcr_lot_no='' OR pcr_lot_no IS NULL) AND cus_permission<50 ".$non_consider_stock_id_str." ORDER BY cus_permission ASC, sale_id DESC ");

			$today_sales=array();

			$total_non_discount_sale=0;
			$has_sync_permission=array();

			foreach ($query->result() as $row) {
				if(trim($row->pcr_lot_no)=="" AND intval($row->sync_permission)==0){
					$today_sales[intval($row->item_cost_price)][]=$row;
					$today_sale_count++;
				}else{
					$has_sync_permission[$row->sale_id]=$row->sale_id;
				}
				$total_non_discount_sale+=$row->vat_enable_price;/////////////////////NEXT CONSIDER
			}

			krsort($today_sales);


			$final_consider_data=array();

			foreach ($today_sales as $today_key => $today_value) {

				foreach ($today_value as $cosider_key => $consider_value) {

					$has_unique=1;

					$unique_price=$consider_value->item_cost_price/2;

					if(array_key_exists($unique_price,$bogo_stock_ids)){

						$random_exist=(rand(1,count($bogo_stock_ids[$unique_price])));
						$bogo_stock_id_count=1;
						foreach ($bogo_stock_ids[$unique_price] as $bogo_stock_id => $bogo_lot_value) {
							if($bogo_stock_id_count==$random_exist){
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_stock_id']=$bogo_stock_id;
								$random_exist_lot=(rand(0,(count($bogo_lot_value)-1)));
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_lot_no']=$bogo_lot_value[$random_exist_lot];
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_quantity_purchased']=$consider_value->quantity_purchased;
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_item_cost_price']=$unique_price;
							}
							$bogo_stock_id_count++;
						}

						$random_exist=(rand(1,count($bogo_stock_ids[$unique_price])));
						$bogo_stock_id_count=1;
						foreach ($bogo_stock_ids[$unique_price] as $bogo_stock_id => $bogo_lot_value) {
							if($bogo_stock_id_count==$random_exist){
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][1]['new_stock_id']=$bogo_stock_id;
								$random_exist_lot=(rand(0,(count($bogo_lot_value)-1)));
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][1]['new_lot_no']=$bogo_lot_value[$random_exist_lot];
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][1]['new_quantity_purchased']=$consider_value->quantity_purchased;
								$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][1]['new_item_cost_price']=$unique_price;
							}
							$bogo_stock_id_count++;
						}

					}else{
						$unique_price=$unique_price*2;
						$first_price=0;
						foreach ($bogo_stock_ids as $f_key => $f_value) {
							if($unique_price>$f_key){
								$first_price=$f_key;
								break;
							}
						}



						$remain_price_exist=0;
						$second_price=0;
						if($first_price>0){
							$remain_price=$unique_price-$first_price;
							foreach ($bogo_stock_ids as $r_key => $r_value) {
								if($remain_price==$r_key){
									$second_price=$r_key;
									$remain_price_exist=0;
									break;
								}else{
									$remain_price_exist=1;
								}
							}
						}else{
							$remain_price_exist=1;
						}


						if($remain_price_exist==0){

							////////////////FIRST PRICE//////////////////////////////

							$random_exist=(rand(1,count($bogo_stock_ids[$first_price])));
							$bogo_stock_id_count=1;
							foreach ($bogo_stock_ids[$first_price] as $bogo_stock_id => $bogo_lot_value) {
								if($bogo_stock_id_count==$random_exist){
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_stock_id']=$bogo_stock_id;
									$random_exist_lot=(rand(0,(count($bogo_lot_value)-1)));
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_lot_no']=$bogo_lot_value[$random_exist_lot];
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_quantity_purchased']=$consider_value->quantity_purchased;
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][0]['new_item_cost_price']=$first_price;
								}
								$bogo_stock_id_count++;
							}

							////////////////SECOND PRICE//////////////////////////////

							$random_exist=(rand(1,count($bogo_stock_ids[$second_price])));
							$bogo_stock_id_count=1;
							foreach ($bogo_stock_ids[$second_price] as $bogo_stock_id => $bogo_lot_value) {
								if($bogo_stock_id_count==$random_exist){
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][2]['new_stock_id']=$bogo_stock_id;
									$random_exist_lot=(rand(0,(count($bogo_lot_value)-1)));
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][2]['new_lot_no']=$bogo_lot_value[$random_exist_lot];
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][2]['new_quantity_purchased']=$consider_value->quantity_purchased;
									$final_consider_data[$consider_value->sale_id."#".$consider_value->stock_id."#".$consider_value->lot_no."#".$consider_value->line."#".$consider_value->quantity_purchased."#".$consider_value->item_cost_price][2]['new_item_cost_price']=$second_price;
								}
								$bogo_stock_id_count++;
							}
						}
					}
				}
			}


			$sales_consider_percentage=0;

			if(LOCATION_CODE=="RAJ"){
				$consider_start=0;//////////////////////Change if required/////IF 25% then 3
			}else{
				$consider_start=0;//////////////////////Change if required/////IF 25% then 4
			}

			if($total_non_discount_sale<4000){
				$sales_consider_percentage=0;
			}elseif ($total_non_discount_sale>=4000 AND $total_non_discount_sale<10000){
				//$sales_consider_percentage=$consider_start;
				$sales_consider_percentage=0;
			}elseif ($total_non_discount_sale>=10000 AND $total_non_discount_sale<15000){
				$sales_consider_percentage=$consider_start+1;
			}elseif ($total_non_discount_sale>=15000 AND $total_non_discount_sale<20000){
				$sales_consider_percentage=$consider_start+1.5;
			}elseif ($total_non_discount_sale>=20000 AND $total_non_discount_sale<25000){
				$sales_consider_percentage=$consider_start+2;
			}elseif ($total_non_discount_sale>=25000 AND $total_non_discount_sale<30000){
				$sales_consider_percentage=$consider_start+2.5;
			}elseif ($total_non_discount_sale>=30000 AND $total_non_discount_sale<35000){
				$sales_consider_percentage=$consider_start+3;
			}elseif ($total_non_discount_sale>=35000 AND $total_non_discount_sale<40000){
				$sales_consider_percentage=$consider_start+3.5;
			}elseif ($total_non_discount_sale>=40000 AND $total_non_discount_sale<50000){
				$sales_consider_percentage=$consider_start+4;
			}elseif ($total_non_discount_sale>=50000){
				$sales_consider_percentage=$consider_start+4.5;
			}
			$sales_discount_permission=0;
			if($sales_consider_percentage>0){
				$sales_discount_permission=ceil(($total_non_discount_sale*$sales_consider_percentage)/100);
			}




			if(count($final_consider_data)){

				foreach ($final_consider_data as $sales_key => $sales_value) {

					$sales_key_array=explode("#",$sales_key);

					$root_sale_id=$sales_key_array[0];
					$root_stock_id=$sales_key_array[1];
					$root_lot_no=$sales_key_array[2];
					$root_line=$sales_key_array[3];
					$root_quantity_purchased=$sales_key_array[4];
					$root_item_cost_price=$sales_key_array[5];

					$bogo_customer_id="27530";
					$bogo_permission_percentage="50";

					$database_execution=array();

					$can_do_execute=1;

					if($sales_discount_permission>100){

						$delete_query_root="DELETE FROM ospos_sales_items
											WHERE sale_id='".$root_sale_id."' 
											AND stock_id='".$root_stock_id."' 
											AND lot_no='".$root_lot_no."' 
											AND line='".$root_line."' 
											AND quantity_purchased='".$root_quantity_purchased."' 
											AND item_cost_price='".$root_item_cost_price."'";

						$database_execution['ex_query'][]=$delete_query_root;

						foreach ($sales_value as $bogo_item_key => $bogo_item_value) {

							/////MAX LINE////

							$query_line = $this->db->query("SELECT MAX(line) AS line,b.receipt_no AS receipt_no FROM ospos_sales_items AS a LEFT JOIN ospos_sales AS b ON a.sale_id=b.sale_id WHERE a.sale_id='".$root_sale_id."'");
							$receipt_no="";
							$next_line=0;
							foreach ($query_line->result() as $row_line) {
								$receipt_no=$row_line->receipt_no;
								$next_line=$row_line->line+1;
							}

							$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);

							$query_root=$this->db->query("SELECT * FROM ospos_sales_items
											WHERE sale_id='".$root_sale_id."' 
											AND stock_id='".$root_stock_id."' 
											AND lot_no='".$root_lot_no."' 
											AND line='".$root_line."' 
											AND quantity_purchased='".$root_quantity_purchased."' 
											AND item_cost_price='".$root_item_cost_price."'");

							$root_item_information=array();

							foreach ($query_root->result() as $row_line) {
								$root_item_information=$row_line;
							}

							$query_root_stock=$this->db->query("SELECT a.description,b.size,c.description AS cat_description
															FROM stock_master AS a
															LEFT JOIN pos_item_sizes AS b ON a.item_size_id=b.id
															LEFT JOIN stock_category AS c ON a.category_id=c.category_id
															WHERE a.stock_id='".$bogo_item_value['new_stock_id']."'");

							$stock_information=array();

							foreach ($query_root_stock->result() as $row_line) {
								$stock_information=$row_line;
							}

							$item_stock_id=$bogo_item_value['new_stock_id'];
							$item_description1=$stock_information->cat_description;
							$item_description2=$stock_information->description." - ".$stock_information->size;
							$item_lot_no=$bogo_item_value['new_lot_no'];
							$item_line=$next_line;


							$item_quantity_purchase=$bogo_item_value['new_quantity_purchased'];
							$item_item_cost_price=$bogo_item_value['new_item_cost_price'];
							$item_discount_percent=0;
							$item_item_unit_price=$bogo_item_value['new_item_cost_price'];
							$item_total_discount=0;
							$item_total_sale_amount=round($item_item_unit_price*$item_quantity_purchase);
							$item_vat_enable_price=round($item_item_cost_price*$item_quantity_purchase);

							$item_vat_percentage=7.5;

							$permission_discount=number_format(($item_vat_enable_price*$bogo_permission_percentage)/100,2,'.','');
							$permission_discount_vat=number_format(($permission_discount*7.5)/100,2,'.','');

							$item_vat_enable_price_after_discount=round($item_vat_enable_price-$permission_discount);

							$item_vat_amount=number_format(($item_vat_enable_price_after_discount*7.5)/100,2,'.','');
							$item_pcr_lot_no=$root_lot_no."#".$root_stock_id."#".$root_item_cost_price;

							$item_sync_permission=0;
							$item_cus_permission=$bogo_permission_percentage;

							$sales_items_data_first="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$root_sale_id."',
								'".$item_stock_id."',
								'".$item_description1."</br>".$item_description2."',
								'".$item_lot_no."',
								'".$item_line."',
								'".$item_quantity_purchase."',
								'".$item_item_cost_price."',
								'".$item_item_unit_price."',
								'".$item_discount_percent."',
								'".$item_total_discount."',
								'".$item_total_sale_amount."',
								'".$item_vat_enable_price."',
								'".$item_vat_percentage."',
								'".$item_vat_amount."',
								'0',
								'".$item_vat_enable_price_after_discount."',
								'".$item_pcr_lot_no."',
								'".$item_sync_permission."',
								'".$item_cus_permission."')";

							$database_execution['ex_query'][]=$sales_items_data_first;

							$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item_stock_id)."' AND a.lot_no='".mysql_real_escape_string($item_lot_no)."' AND a.price='".mysql_real_escape_string($item_item_cost_price)."' GROUP BY a.stock_id,a.lot_no,a.price");

							$stock_moves_lot_data=$query_moves->row();

							if($stock_moves_lot_data->standard_cost==0){
								$stock_moves_lot_data->standard_cost=round(($stock_moves_lot_data->price*52)/100);
							}

							$date_moves_update_first="20".intval(substr($item_lot_no,0,2)-1)."-".substr($item_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

							$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$root_sale_id."',
								'".$item_stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update_first."',
								'".$root_sale_id."',
								'".$item_item_cost_price."',
								'".$force_reference."',
								'".$item_quantity_purchase."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$item_lot_no."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

							$database_execution['ex_query'][]=$stock_moves_data_first;

							$cash_update=round($permission_discount+$permission_discount_vat);

							$database_execution['cash_update']+=$cash_update;
							$database_execution['purchase_discount']+=$permission_discount;

							$stock_moves_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$root_sale_id."',
								'".$bogo_item_value['new_stock_id']."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$root_sale_id."',
								'".$bogo_item_value['new_item_cost_price']."',
								'".$receipt_no."',
								'-".$bogo_item_value['new_quantity_purchased']."',
								'0',
								'".$stock_moves_lot_data->standard_cost."',
								'".$stock_moves_lot_data->visible."',
								'".$bogo_item_value['new_lot_no']."',
								'".$stock_moves_lot_data->is_imported."',
								'".$stock_moves_lot_data->swatch_code."')";

							$database_execution['ex_query'][]=$stock_moves_data;
							$database_execution['ex_sales_discount_permission']+=$bogo_item_value['new_item_cost_price']*$bogo_item_value['new_quantity_purchased'];

						}



						$date_moves_update_root="20".intval(substr($root_lot_no,0,2)-1)."-".substr($root_lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);


						$update_stock_moves_root="UPDATE stock_moves
						SET type='16',tran_date='".$date_moves_update_root."',reference='".$force_reference."'
						WHERE stock_id='".$root_stock_id."'
						AND type='201'
						AND loc_code='".LOCATION_CODE."'
						AND price='".$root_item_cost_price."'
						AND qty=-'".$root_quantity_purchased."'
						AND lot_no='".$root_lot_no."'
						AND reference='".$receipt_no."'";

						$database_execution['ex_query'][]=$update_stock_moves_root;


						if($database_execution['ex_sales_discount_permission']==$root_item_cost_price*$root_quantity_purchased){

							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$root_sale_id."' AND payment_type='Cash' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}

							if($payment_sale_id){

								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($database_execution['cash_update']))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
								$database_execution['ex_query'][]=$update_query_permission;

							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$root_sale_id."',
						'Cash',
						'".round($database_execution['cash_update']*-1)."')";

								$database_execution['ex_query'][]=$insert_sql;
							}

							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$root_sale_id."' AND payment_type='Purchase Discount' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}

							if($payment_sale_id){

								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($database_execution['purchase_discount']))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
								$database_execution['ex_query'][]=$update_query_permission;

							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$root_sale_id."',
						'Purchase Discount',
						'".round($database_execution['purchase_discount'])."')";

								$database_execution['ex_query'][]=$insert_sql;
							}

							$insert_query="
						INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
						)
						VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".LOCATION_CODE."',
						'".$root_sale_id."',
						'".($root_item_cost_price*$root_quantity_purchased)."',
						'".$bogo_permission_percentage."',
						'".round($database_execution['cash_update'])."',
						'".($root_item_cost_price*$root_quantity_purchased)."',
						'".round($database_execution['cash_update'])."',
						'".round($database_execution['cash_update'])."')";

							$database_execution['ex_query'][]=$insert_query;

							$update_sale_sql="UPDATE ospos_sales set clr_sync=1,customer_id='".$bogo_customer_id."' WHERE sale_id='".$root_sale_id."'";
							$database_execution['ex_query'][]=$update_sale_sql;

							foreach ($database_execution['ex_query'] as $query_key => $query_value) {
								$this->db->query($query_value);

							}
							$sales_discount_permission-=round($root_item_cost_price*$root_quantity_purchased);
						}

					}
					$database_execution=array();
				}
				foreach ($final_consider_data as $sales_line_key => $sales_line_value) {

					$sales_line_key_array=explode("#",$sales_line_key);

					$root_sale_id_for_line=$sales_line_key_array[0];

					$sql_stock="SELECT  * FROM ospos_sales_items WHERE sale_id ='".$root_sale_id_for_line."'";
					$query_stock = $this->db->query($sql_stock);

					$line_no=1;
					foreach ($query_stock->result() as $row_stock) {

						$update_sale_line_sql="UPDATE ospos_sales_items
						SET line='".$line_no."',
						vat_amount='".number_format(($row_stock->vat_enable_price_after_discount*$row_stock->vat_percentage)/100,2,'.','')."'

						WHERE sale_id='".$row_stock->sale_id."'
						AND stock_id='".$row_stock->stock_id."'
						AND lot_no='".$row_stock->lot_no."'
						AND line='".$row_stock->line."'
						AND quantity_purchased='".$row_stock->quantity_purchased."'
						AND item_cost_price='".$row_stock->item_cost_price."'
						AND vat_amount='".$row_stock->vat_amount."'
						AND vat_enable_price_after_discount='".$row_stock->vat_enable_price_after_discount."'";

						$this->db->query($update_sale_line_sql);

						$line_no++;
					}
				}
			}

		}
	}




	function do_per_slot_sync($location_code) {

		$this->db->trans_start();

		///user sync//
		$this->db->from('clr_locwise');
		$this->db->where('is_sync',0);
		$employee_data_result= $this->db->get();

		$employee_data=array();
		foreach($employee_data_result->result_array() as $row)
		{
			$employee_data[]=$row;
		}
		$this->db->trans_complete();

		if(count($employee_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);
			if($status==0){
				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['permission_data'] =$employee_data;
				$api_data_final = json_encode($api_data);

				$result = $client->__soapCall('regularSyncClr', array('data' => $api_data_final));

				$json_data=json_decode($result);

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					if(count($json_data->data)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');
						foreach ($json_data->data as $key => $value) {
							$update_query_permission="UPDATE ospos_clr_locwise SET is_sync=1 WHERE id='".$value."'";
							$this->db->query($update_query_permission);
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
					}
					return $success;
				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}


	function do_per_slot_others_sync($location_code) {


		$this->db->trans_start();

		///user sync//
		$this->db->from('clr_locwise_others');
		$this->db->where('is_sync',0);
		$employee_data_result= $this->db->get();


		$employee_data=array();
		foreach($employee_data_result->result_array() as $row)
		{
			$employee_data[]=$row;
		}
		$this->db->trans_complete();


		if(count($employee_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));
				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['permission_data'] =$employee_data;
				$api_data_final = json_encode($api_data);

				$result = $client->__soapCall('regularSyncClrOthers', array('data' => $api_data_final));

				$json_data=json_decode($result);


				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					if(count($json_data->data)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');
						foreach ($json_data->data as $key => $value) {
							$update_query_permission="UPDATE ospos_clr_locwise_others SET is_sync=1 WHERE id='".$value."'";
							$this->db->query($update_query_permission);
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
					}
					return $success;
				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}

	function not_more_than_permission($current_date,$real_adjustment=0,$real_vat_enable_data=array()){

		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}
		////////////////5% VAT ITEMS////////////////

		$stock_id_with_other_vat=array();
		$query = $this->db->query("SELECT stock_id FROM stock_master WHERE tax_type_id!=1");

		foreach ($query->result() as $row) {
			$stock_id_with_other_vat[]=$row->stock_id;
		}

		$stock_id_without_other_vat_str="";
		$stock_id_only_other_vat_str="";
		if(count($stock_id_with_other_vat)){
			$stock_id_str="'".implode("','",$stock_id_with_other_vat)."'";
			$stock_id_without_other_vat_str=" AND stock_id NOT IN (".$stock_id_str.")";
			$stock_id_only_other_vat_str=" AND stock_id IN (".$stock_id_str.")";
		}else{
			$stock_id_without_other_vat_str=" AND stock_id NOT IN ('XXXXXXXX')";
			$stock_id_only_other_vat_str=" AND stock_id IN ('XXXXXXXX')";
		}




		$query_customer = $this->db->query("SELECT id FROM pos_ospos_customers WHERE is_special=1 AND id!=26247");
		$special_customer_ids_array=array();

		foreach ($query_customer->result() as $row_special) {
			$special_customer_ids_array[]=$row_special->id;
		}

		$special_customer_ids_string="";
		if(count($special_customer_ids_array)){
			$special_customer_ids_string_temp="'".implode("','",$special_customer_ids_array)."'";
			$special_customer_ids_string=" AND (customer_id NOT IN(".$special_customer_ids_string_temp.") OR customer_id=0 OR customer_id IS NULL )";

		}
		//$maximum_permission_percentage=(rand(795, 820)/100);//////////////////////SET AS MY WISH
		$maximum_permission_percentage=(rand(855, 875)/100);//////////////////////SET AS MY WISH
		/////////////////////////////////////////////////////////VAT PERCENTAGE 7.5%/////////////////////////////////////////////////////////

		///////////////TOTAL SALES///////////////////

		//////////DISCOUNT SALE IDS////

		/*$discount_sale_ids=array();

		$query = $this->db->query("SELECT sale_id FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) AND acc_location='".LOCATION_CODE."') AND discount_percent>0 AND cus_permission<9 ".$stock_id_without_other_vat_str);

		foreach ($query->result() as $row) {
		$discount_sale_ids[]=$row->sale_id;
		}*/

		$discount_sale_ids_str="";
		$discount_sale_ids_str_permission="";
		/*if(count($discount_sale_ids)){
		$discount_sale_ids_str_temp="'".implode("','",$discount_sale_ids)."'";
		$discount_sale_ids_str=" AND sale_id NOT IN (".$discount_sale_ids_str_temp.")";
		$discount_sale_ids_str_permission=" AND sales_id NOT IN (".$discount_sale_ids_str_temp.")";
		}*/




		$total_sales=0;
		$sale_id_modify=0;

		$sale_ids=array();
		$query = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale,discount_percent,total_discount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string.") ".$discount_sale_ids_str." ".$stock_id_without_other_vat_str);

		foreach ($query->result() as $row) {
			if(intval($row->discount_percent)>0){
				//$total_sales+=round(($row->total_discount*7.5)/100);/////////////////////NEXT CONSIDER
				//$total_sales+=round(($row->total_sale-$row->total_discount));/////////////////////NEXT CONSIDER
				$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
			}else{
				$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
			}
			$sale_id_modify=$row->sale_id;
			$sale_ids[]=$row->sale_id;
		}

		if($total_sales>0){

			//$maximum_permission_percentage_consider=$maximum_permission_percentage+(($maximum_permission_percentage*7.5)/100);///////////////CHECK NEXT TIME
			$maximum_permission_percentage_consider=$maximum_permission_percentage;
			$maximum_purchase_discount=round(($total_sales*$maximum_permission_percentage_consider)/100);

			////////////////////////Additional Discount////////////////////////

			$query_aditional = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale,cus_permission,sync_permission FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') AND (cus_permission>=9 OR sync_permission>=9)");

			$aditional_purchase_discount=0;
			foreach ($query_aditional->result() as $row_aditional) {

				$additional_percentage=0;
				if($row_aditional->cus_permission>$row_aditional->sync_permission){
					$additional_percentage=$row_aditional->cus_permission;
				}else{
					$additional_percentage=$row_aditional->sync_permission;
				}
				$aditional_purchase_discount+=round(($row_aditional->total_sale*$additional_percentage)/100);
			}

			$maximum_purchase_discount=$maximum_purchase_discount+$aditional_purchase_discount;


			//////////////////CURRENT PURCHASE DISCOUNT////////////////////////
			$current_purcahse_discount=0;

			if(count($sale_ids)){
				$sales_id_str="'".implode("','",$sale_ids)."'";
				$query = $this->db->query("SELECT payment_amount AS purchase_discount,branch_name FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') AND  payment_type='Purchase Discount'");
				foreach ($query->result() as $row) {
					$current_purcahse_discount+=intval($row->purchase_discount)-intval($row->branch_name);/////////////////////NEXT CONSIDER
				}
			}


			//////////////////CURRENT CASH////////////////////////
			$current_cash=0;

			$query = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND  payment_type='CASH'");

			foreach ($query->result() as $row) {
				$current_cash=$row->total_cash;/////////////////////NEXT CONSIDER
			}

			///////////////////CURRENT PERMISSION CASH//////////////////////////

			$current_permission_cash=0;

			$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_cash FROM ospos_permissions_relations_customer
						WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' ".$discount_sale_ids_str_permission." AND payment_type!='MRP'");

			foreach ($query->result() as $row) {
				$current_permission_cash=$row->total_cash;
			}

			$difference_product_discount=round($maximum_purchase_discount-$current_purcahse_discount);//////////////////KINTU

			if($difference_product_discount<0){

				$is_full_delete_permission_relation_data=0;
				$difference_product_discount_cal=abs($difference_product_discount);
				$difference_product_discount_in_cash=round($difference_product_discount_cal+(($difference_product_discount_cal*7.5)/100));

				if($difference_product_discount_in_cash>$current_permission_cash){
					$difference_product_discount_cal_consider=round((100*$current_permission_cash)/107.5);
					$is_full_delete_permission_relation_data=1;
				}else{
					$difference_product_discount_cal_consider=$difference_product_discount_cal;
				}

				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}



				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($difference_product_discount_cal_consider))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT
				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'-".round($difference_product_discount_cal_consider)."')";
					$this->db->query($insert_sql);////NEXT
				}

				$cash_update=round($difference_product_discount_cal_consider+(($difference_product_discount_cal_consider*7.5)/100));




				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}
				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update)."')";
					$this->db->query($insert_sql);////NEXT
				}

				////////////////////////SALES ITEMS WILL UPDATE////////////////////////////////
				$sales_item_info=array();
				$sql="SELECT * FROM ospos_sales_items WHERE sale_id ='".$sale_id_modify."' ORDER BY line ASC LIMIT 1";
				$query = $this->db->query($sql);
				foreach ($query->result() as $row) {
					$sales_item_info=$row;
				}
				$vat_increase_decrease=number_format((($difference_product_discount_cal_consider*7.5)/100),2,'.','');

				$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount+'".$vat_increase_decrease."',
						vat_enable_price_after_discount=vat_enable_price_after_discount+'".$difference_product_discount_cal_consider."'
						WHERE sale_id='".$sales_item_info->sale_id."' AND stock_id='".$sales_item_info->stock_id."' AND lot_no='".$sales_item_info->lot_no."' AND line='".$sales_item_info->line."' AND item_cost_price='".$sales_item_info->item_cost_price."'";
				$this->db->query($update_sql);////////////////////////////NEXT


				if($is_full_delete_permission_relation_data==1){

					$query="DELETE FROM ospos_permissions_relations_customer WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' ".$discount_sale_ids_str_permission." AND payment_type!='MRP'";

					$this->db->query($query);////NEXT

				}else{
					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash',
						'".round($sales_item_info->vat_enable_price)."',
						'0',
						'-".round($cash_update)."',
						'-".round($cash_update)."',
						'-".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT

				}
			}elseif($difference_product_discount>0){
				$is_full_delete_permission_relation_data=0;
				$difference_product_discount_cal=abs($difference_product_discount);
				$difference_product_discount_in_cash=round($difference_product_discount_cal+(($difference_product_discount_cal*7.5)/100));

				if($current_cash>=$difference_product_discount_in_cash+129){
					$difference_product_discount_cal_consider=$difference_product_discount_cal;

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($difference_product_discount_cal_consider))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($difference_product_discount_cal_consider)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$cash_update=round($difference_product_discount_cal_consider+(($difference_product_discount_cal_consider*7.5)/100));


					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}
					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'-".round($cash_update)."')";
						$this->db->query($insert_sql);////NEXT
					}

					////////////////////////SALES ITEMS WILL UPDATE////////////////////////////////
					$sales_item_info=array();
					$sql="SELECT * FROM ospos_sales_items WHERE sale_id ='".$sale_id_modify."' ORDER BY line ASC LIMIT 1";
					$query = $this->db->query($sql);
					foreach ($query->result() as $row) {
						$sales_item_info=$row;
					}
					$vat_increase_decrease=number_format((($difference_product_discount_cal_consider*7.5)/100),2,'.','');

					$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_increase_decrease."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$difference_product_discount_cal_consider."'
						WHERE sale_id='".$sales_item_info->sale_id."' AND stock_id='".$sales_item_info->stock_id."' AND lot_no='".$sales_item_info->lot_no."' AND line='".$sales_item_info->line."' AND item_cost_price='".$sales_item_info->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT


					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash',
						'".round($sales_item_info->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}
		}

		/////////////////////////////////////////////////////////VAT PERCENTAGE 5%/////////////////////////////////////////////////////////

		///////////////TOTAL SALES///////////////////
		$total_sales=0;
		$sale_id_modify=0;

		$sale_ids=array();
		$query = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) AND acc_location='".LOCATION_CODE."')".$stock_id_only_other_vat_str);

		foreach ($query->result() as $row) {
			$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
			$sale_id_modify=$row->sale_id;
			$sale_ids[]=$row->sale_id;
		}

		if($total_sales>0){

			$maximum_permission_percentage_consider=$maximum_permission_percentage+(($maximum_permission_percentage*5)/100);
			$maximum_purchase_discount=round(($total_sales*$maximum_permission_percentage_consider)/100);

			//////////////////CURRENT PURCHASE DISCOUNT////////////////////////
			$current_purcahse_discount=0;

			if(count($sale_ids)){
				$sales_id_str="'".implode("','",$sale_ids)."'";
				$query = $this->db->query("SELECT payment_amount AS purchase_discount,branch_name FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') AND  payment_type='Purchase Discount'");
				foreach ($query->result() as $row) {
					$current_purcahse_discount+=intval($row->purchase_discount)-intval($row->branch_name);/////////////////////NEXT CONSIDER
				}
			}

			//////////////////CURRENT CASH////////////////////////
			$current_cash=0;

			$query = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND  payment_type='CASH'");

			foreach ($query->result() as $row) {
				$current_cash=$row->total_cash;/////////////////////NEXT CONSIDER
			}

			///////////////////CURRENT PERMISSION CASH//////////////////////////

			$current_permission_cash=0;

			$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_cash FROM ospos_permissions_relations_customer
						WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' AND payment_type!='MRP'");

			foreach ($query->result() as $row) {
				$current_permission_cash=$row->total_cash;
			}

			$difference_product_discount=round($maximum_purchase_discount-$current_purcahse_discount);


			if($difference_product_discount<0){

				$is_full_delete_permission_relation_data=0;
				$difference_product_discount_cal=abs($difference_product_discount);
				$difference_product_discount_in_cash=round($difference_product_discount_cal+(($difference_product_discount_cal*5)/100));

				if($difference_product_discount_in_cash>$current_permission_cash){
					$difference_product_discount_cal_consider=round((100*$current_permission_cash)/105);
					$is_full_delete_permission_relation_data=1;
				}else{
					$difference_product_discount_cal_consider=$difference_product_discount_cal;
				}

				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}


				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($difference_product_discount_cal_consider))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT
				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'-".round($difference_product_discount_cal_consider)."')";
					$this->db->query($insert_sql);////NEXT
				}

				$cash_update=round($difference_product_discount_cal_consider+(($difference_product_discount_cal_consider*5)/100));


				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}
				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update)."')";
					$this->db->query($insert_sql);////NEXT
				}

				////////////////////////SALES ITEMS WILL UPDATE////////////////////////////////
				$sales_item_info=array();
				$sql="SELECT * FROM ospos_sales_items WHERE sale_id ='".$sale_id_modify."' ORDER BY line ASC LIMIT 1";
				$query = $this->db->query($sql);
				foreach ($query->result() as $row) {
					$sales_item_info=$row;
				}
				$vat_increase_decrease=number_format((($difference_product_discount_cal_consider*5)/100),2,'.','');

				$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount+'".$vat_increase_decrease."',
						vat_enable_price_after_discount=vat_enable_price_after_discount+'".$difference_product_discount_cal_consider."'
						WHERE sale_id='".$sales_item_info->sale_id."' AND stock_id='".$sales_item_info->stock_id."' AND lot_no='".$sales_item_info->lot_no."' AND line='".$sales_item_info->line."' AND item_cost_price='".$sales_item_info->item_cost_price."'";
				$this->db->query($update_sql);////////////////////////////NEXT


				if($is_full_delete_permission_relation_data==1){

					$query="DELETE FROM ospos_permissions_relations_customer WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' AND payment_type!='MRP'";

					$this->db->query($query);////NEXT

				}else{
					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash',
						'".round($sales_item_info->vat_enable_price)."',
						'0',
						'-".round($cash_update)."',
						'-".round($cash_update)."',
						'-".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT

				}
			}elseif($difference_product_discount>0){
				$is_full_delete_permission_relation_data=0;
				$difference_product_discount_cal=abs($difference_product_discount);
				$difference_product_discount_in_cash=round($difference_product_discount_cal+(($difference_product_discount_cal*5)/100));

				if($current_cash>=$difference_product_discount_in_cash+129){
					$difference_product_discount_cal_consider=$difference_product_discount_cal;

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($difference_product_discount_cal_consider))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($difference_product_discount_cal_consider)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$cash_update=round($difference_product_discount_cal_consider+(($difference_product_discount_cal_consider*5)/100));


					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}
					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'-".round($cash_update)."')";
						$this->db->query($insert_sql);////NEXT
					}

					////////////////////////SALES ITEMS WILL UPDATE////////////////////////////////
					$sales_item_info=array();
					$sql="SELECT * FROM ospos_sales_items WHERE sale_id ='".$sale_id_modify."' ORDER BY line ASC LIMIT 1";
					$query = $this->db->query($sql);
					foreach ($query->result() as $row) {
						$sales_item_info=$row;
					}
					$vat_increase_decrease=number_format((($difference_product_discount_cal_consider*5)/100),2,'.','');

					$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_increase_decrease."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$difference_product_discount_cal_consider."'
						WHERE sale_id='".$sales_item_info->sale_id."' AND stock_id='".$sales_item_info->stock_id."' AND lot_no='".$sales_item_info->lot_no."' AND line='".$sales_item_info->line."' AND item_cost_price='".$sales_item_info->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT


					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash',
						'".round($sales_item_info->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}
		}


		/*	VAT ADJUST	CONSIDER VAT 5%*/
		$query = $this->db->query("SELECT vat_amount AS vat_amount,vat_enable_price_after_discount AS vat_enable_price_after_discount,sale_id,stock_id,lot_no,line,item_cost_price  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ".$stock_id_only_other_vat_str);

		$vat_amount=0;
		$vat_enable_price_after_discount=0;
		foreach ($query->result() as $row) {
			$vat_amount=number_format($row->vat_amount,2,'.','');
			$vat_enable_price_after_discount=round($row->vat_enable_price_after_discount);
			$real_vat=number_format((($vat_enable_price_after_discount)*5/100),2,'.','');
			$difference=number_format(($real_vat-$vat_amount),2,'.','');
			if($difference!=0){
				$update_sql="
						UPDATE ospos_sales_items
						SET vat_amount=vat_amount+'".$difference."'
						WHERE sale_id='".$row->sale_id."' AND stock_id='".$row->stock_id."' AND lot_no='".$row->lot_no."' AND line='".$row->line."' AND item_cost_price='".$row->item_cost_price."'";
				$this->db->query($update_sql);
				$total_adjustment+=$difference;
			}
		}

		/*	VAT ADJUST	CONSIDER VAT 7.5%*/

		$total_adjustment=0;
		$query = $this->db->query("SELECT vat_amount AS vat_amount,vat_enable_price_after_discount AS vat_enable_price_after_discount,sale_id,stock_id,lot_no,line,item_cost_price  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ".$stock_id_without_other_vat_str);
		$vat_amount=0;
		$vat_enable_price_after_discount=0;
		foreach ($query->result() as $row) {
			$vat_amount=number_format($row->vat_amount,2,'.','');
			$vat_enable_price_after_discount=round($row->vat_enable_price_after_discount);
			$real_vat=number_format((($vat_enable_price_after_discount)*7.5/100),2,'.','');
			$difference=number_format(($real_vat-$vat_amount),2,'.','');

			if($difference!=0){
				$update_sql="
						UPDATE ospos_sales_items
						SET vat_amount=vat_amount+'".$difference."'
						WHERE sale_id='".$row->sale_id."' AND stock_id='".$row->stock_id."' AND lot_no='".$row->lot_no."' AND line='".$row->line."' AND item_cost_price='".$row->item_cost_price."'";
				$this->db->query($update_sql);////NEXT
				$total_adjustment+=$difference;
			}
		}


		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}
		///////////////RECHECK vat_enable_price_after_discount
		$query = $this->db->query("SELECT sale_id,line,stock_id,SUM(vat_enable_price) AS total_sale,SUM(total_discount) AS total_discount,SUM(vat_enable_price_after_discount) AS vat_enable_price_after_discount,SUM(vat_amount) AS vat_amount  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");
		$sale_amount_recheck=0;
		$discount_amount_recheck=0;
		$vat_enable_price_after_discount_recheck=0;
		$vat_amount_recheck=0;
		$sale_id_recheck=0;
		$line_recheck=0;
		$stock_id_recheck=0;

		foreach ($query->result() as $row) {
			$sale_amount_recheck+=$row->total_sale;
			$discount_amount_recheck+=$row->total_discount;
			$vat_enable_price_after_discount_recheck+=$row->vat_enable_price_after_discount;
			$sale_id_recheck=$row->sale_id;
			$line_recheck=$row->line;
			$stock_id_recheck=$row->stock_id;
		}



		$query = $this->db->query("SELECT payment_amount AS total_discount,branch_name FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND payment_type IN ('Purchase Bonus','Purchase Discount')");
		foreach ($query->result() as $row) {
			$discount_amount_recheck+=intval($row->total_discount);
		}
		$re_check_difference=$sale_amount_recheck-($vat_enable_price_after_discount_recheck+$discount_amount_recheck);



		$update_query_permission_recheck="UPDATE ospos_sales_items SET vat_enable_price_after_discount=vat_enable_price_after_discount+'".$re_check_difference."'
		WHERE sale_id='".$sale_id_recheck."' 
		AND line='".$line_recheck."' 
		AND stock_id='".$stock_id_recheck."'";
		$this->db->query($update_query_permission_recheck);////////////////NEXT

		$update_query_permission_recheck_vat="UPDATE ospos_sales_items
		SET vat_amount=round(((vat_enable_price_after_discount*vat_percentage)/100),2) WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND is_sync=0)";

		$this->db->query($update_query_permission_recheck_vat);////////////////NEXT

		///Addustment with real
		$query = $this->db->query("SELECT SUM(vat_enable_price_after_discount+vat_amount) AS total_sale  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");
		$sale_amount=0;
		foreach ($query->result() as $row) {
			$sale_amount+=$row->total_sale;
		}

		$adjusment_sale_id=0;

		$query = $this->db->query("SELECT sale_id,SUM(payment_amount) AS total_collection FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND payment_type NOT IN ('Purchase Bonus','Purchase Discount')");
		$collect_amount=0;
		foreach ($query->result() as $row) {
			$collect_amount+=$row->total_collection;
			$adjusment_sale_id=$row->sale_id;
		}

		/*

		$query = $this->db->query("SELECT payment_amount,branch_name AS total_collection FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND payment_type='Purchase Discount'");
		$coupon_amount=0;
		foreach ($query->result() as $row) {
		$coupon_amount+=intval($row->payment_amount)-intval($row->total_collection);
		}*/
		//$current_adjutment= number_format((($collect_amount+$coupon_amount)-$sale_amount),2,'.','');
		$current_adjutment= number_format((($collect_amount)-$sale_amount),2,'.','');


		$difference_from_real_adjustment=round($current_adjutment-$real_adjustment);
		if($difference_from_real_adjustment!=0){
			$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$adjusment_sale_id."' AND payment_type='Cash' LIMIT 1";
			$query = $this->db->query($sql);

			$payment_sale_id=0;
			foreach ($query->result() as $row) {
				$payment_sale_id=$row->sale_id;
				$payment_sale_id_amount=$row->payment_amount;
			}
			if($payment_sale_id){
				$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($difference_from_real_adjustment*-1))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
				$this->db->query($update_query_permission);////////////////NEXT

			}else{
				$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($difference_from_real_adjustment*-1)."')";
				$this->db->query($insert_sql);////NEXT
			}

			$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$adjusment_sale_id."',
						'0',
						'0',
						'ADJ_DEF_REAL',
						'".round($difference_from_real_adjustment)."',
						'0',
						'".round($difference_from_real_adjustment)."',
						'".round($difference_from_real_adjustment)."',
						'".round($difference_from_real_adjustment)."',
						'0')";
			$this->db->query($query);////NEXT
		}

		///////////////////////FINAL CHECK//////////////////////////

		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}

		////////////////5% VAT ITEMS////////////////

		$stock_id_with_other_vat=array();
		$query = $this->db->query("SELECT stock_id FROM stock_master WHERE tax_type_id!=1");

		foreach ($query->result() as $row) {
			$stock_id_with_other_vat[]=$row->stock_id;
		}

		$stock_id_without_other_vat_str="";
		$stock_id_only_other_vat_str="";
		if(count($stock_id_with_other_vat)){
			$stock_id_str="'".implode("','",$stock_id_with_other_vat)."'";
			$stock_id_without_other_vat_str=" AND stock_id NOT IN (".$stock_id_str.")";
			$stock_id_only_other_vat_str=" AND stock_id IN (".$stock_id_str.")";
		}else{
			$stock_id_without_other_vat_str=" AND stock_id NOT IN ('XXXXXXXX')";
			$stock_id_only_other_vat_str=" AND stock_id IN ('XXXXXXXX')";
		}


		$query = $this->db->query("SELECT sale_id,SUM(vat_enable_price_after_discount) AS total_sale, SUM(vat_amount) AS total_vat_amount
		FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."')".$stock_id_without_other_vat_str);

		$update_sale_id=0;
		$total_sale_real=0;
		$total_vat_real=0;

		foreach ($query->result() as $row) {
			$update_sale_id=$row->sale_id;
			$total_sale_real=number_format($row->total_sale,2,'.','');
			$total_vat_real=number_format($row->total_vat_amount,2,'.','');
		}
		$check_difference=number_format(number_format((($total_sale_real*7.5)/100),2,'.','')-$total_vat_real,2,'.','');

		if(abs($check_difference)>0.10){
			$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount+'".$check_difference."'
						WHERE sale_id='".$update_sale_id."' LIMIT 1";
			$this->db->query($update_sql);////////////////////////////NEXT
		}

		$query = $this->db->query("SELECT sale_id,SUM(vat_enable_price_after_discount) AS total_sale, SUM(vat_amount) AS total_vat_amount
		FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."')".$stock_id_only_other_vat_str);

		$update_sale_id_5=0;
		$total_sale_real_5=0;
		$total_vat_real_5=0;

		foreach ($query->result() as $row) {
			$update_sale_id_5=$row->sale_id;
			$total_sale_real_5=number_format($row->total_sale,2,'.','');
			$total_vat_real_5=number_format($row->total_vat_amount,2,'.','');
		}
		$check_difference_5=number_format(number_format((($total_sale_real_5*7.5)/100),2,'.','')-$total_vat_real_5,2,'.','');

		if(abs($check_difference_5)>0.10){
			$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount+'".$check_difference_5."'
						WHERE sale_id='".$update_sale_id_5."' LIMIT 1";
			$this->db->query($update_sql);////////////////////////////NEXT
		}




		$update_sale_sql="UPDATE ospos_sales set is_permission=1 WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."'";
		$this->db->query($update_sale_sql);



		if(count($real_vat_enable_data)){


			$real_vat_enable_price_after_discount=$real_vat_enable_data['vat_enable_price_after_discount'];
			$real_vat_amount=$real_vat_enable_data['vat_amount'];

			$after_vat_enable_price_after_discount=0;
			$after_vat_amount=0;

			$query = $this->db->query("SELECT SUM(vat_enable_price_after_discount) AS vat_enable_price_after_discount,SUM(vat_amount) AS vat_amount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");

			foreach ($query->result() as $row) {

				$after_vat_enable_price_after_discount+=$row->vat_enable_price_after_discount;
				$after_vat_amount+=number_format($row->vat_amount,2,'.','');
			}

			if(intval($real_vat_enable_price_after_discount)!=intval($after_vat_enable_price_after_discount)){
				$modify_item_info=array();

				$add_delete_vat_enable_price_after_discount=intval($real_vat_enable_price_after_discount-$after_vat_enable_price_after_discount);
				$add_delete_vat_amount=number_format(($real_vat_amount-$after_vat_amount),2,'.','');



				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");

				foreach ($query->result() as $row) {
					$modify_item_info=$row;
				}


				$update_sql_force="UPDATE ospos_sales_items SET
			vat_enable_price_after_discount='".($modify_item_info->vat_enable_price_after_discount+$add_delete_vat_enable_price_after_discount)."',
			vat_amount='".($modify_item_info->vat_amount+$add_delete_vat_amount)."'
			WHERE sale_id='".$modify_item_info->sale_id."' AND stock_id='".$modify_item_info->stock_id."' AND lot_no='".$modify_item_info->lot_no."' AND line='".$modify_item_info->line."' AND item_cost_price='".$modify_item_info->item_cost_price."' AND quantity_purchased='".$modify_item_info->quantity_purchased."'";

				$this->db->query($update_sql_force);

				$payment_sale_id=0;
				$payment_sale_id_amount=0;
				$sql_cash="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$modify_item_info->sale_id."' AND payment_type='Cash' LIMIT 1";


				$query = $this->db->query($sql_cash);

				foreach ($query->result() as $row_cash) {
					$payment_sale_id=$row_cash->sale_id;
					$payment_sale_id_amount=$row_cash->payment_amount;

				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($add_delete_vat_amount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);
				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$modify_item_info->sale_id."',
					'Cash',
					'".(round($add_delete_vat_amount))."')";
					$this->db->query($insert_sql);
				}

				$insert_query="
					INSERT INTO ospos_clr_locwise(
						sales_time,
						loc_code,
						sale_id,
						total_price,
						previous_clr,
						current_clr,
						previous_sale_price_total,
						clr_amount_total,
						clr_amount
					)
					VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
					'".LOCATION_CODE."',
					'".$modify_item_info->sale_id."',
					'".$add_delete_vat_enable_price_after_discount."',
					'".$modify_item_info->discount_percent."',
					'".(round($add_delete_vat_amount)*-1)."',
					'".(round($add_delete_vat_amount)*-1)."',
					'".(round($add_delete_vat_amount)*-1)."',
					'".(round($add_delete_vat_amount)*-1)."')";
				$this->db->query($insert_query);
			}
		}

		///////////////////////////Coupon/////////////////////////////////
		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}
		$total_sales=0;
		$consider_sale_amount=0;
		$maximum_coupon_discount=0;
		$total_give_coupon=0;
		$not_used_coupon=0;
		$used_coupon=0;
		$sale_ids=array();
		$sale_id_modify=0;





		if($current_date>='2023-03-22' AND $current_date<='2023-04-12'){
			$query = $this->db->query("SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND is_sync=0 LIMIT 1");
			foreach ($query->result() as $row) {
				$sale_id_modify=$row->sale_id;
			}

			if($sale_id_modify>0){
				$query = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale,discount_percent,total_discount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."')");

				foreach ($query->result() as $row) {
					if(intval($row->discount_percent)>0){
						$total_sales+=round(($row->total_discount*7.5)/100);/////////////////////NEXT CONSIDER
					}else{
						$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
					}
					$sale_ids[]=$row->sale_id;
				}

				$additional_amount=0;
				if($current_date>='2024-03-22' AND $current_date<='2024-04-12'){
					$percentage_add=(rand(255, 275)/100);//////////////////////SET AS MY WISH
					//$additional_amount=round(($total_sales*$percentage_add)/100);
				}

				if(count($sale_ids)){
					$sales_id_str="'".implode("','",$sale_ids)."'";

					$query_coupon = $this->db->query("SELECT sum(branch_name) AS total_amount FROM ospos_sales_payments
		WHERE sale_id IN (".$sales_id_str.") AND payment_type='Purchase Discount'");

					foreach ($query_coupon->result() as $row_coupon) {
						$total_give_coupon=intval($row_coupon->total_amount);/////////////////////NEXT CONSIDER
					}
				}



				$query_coupon = $this->db->query("SELECT sum(coupon_value) AS coupon_value FROM pos_ospos_eid_coupon
		WHERE DATE_FORMAT(coupon_date,'%Y-%m-%d')='".$current_date."' AND is_used='0'");

				foreach ($query_coupon->result() as $row_coupon) {
					$not_used_coupon=round((intval($row_coupon->coupon_value)*70)/100);/////////////////////NEXT CONSIDER
				}
				$query_coupon = $this->db->query("SELECT sum(coupon_value) AS coupon_value FROM pos_ospos_eid_coupon
		WHERE DATE_FORMAT(coupon_use_date,'%Y-%m-%d')='".$current_date."' AND is_used='1'");

				foreach ($query_coupon->result() as $row_coupon) {
					$used_coupon=intval($row_coupon->coupon_value);/////////////////////NEXT CONSIDER
				}

				$start_limit=5000;

				if($current_date<='2024-03-26'){
					$start_limit=5000;
					$exclued_from_sale=round((($not_used_coupon*100)/30))+round($used_coupon*1.5);
				}else if($current_date>'2024-03-26' AND $current_date<='2024-03-30'){///3
					$start_limit=3000;
					$exclued_from_sale=round((($not_used_coupon*100)/40))+round($used_coupon*1.5);
				}else if($current_date>'2024-03-30' AND $current_date<='2024-04-12'){//2
					$start_limit=2000;
					$exclued_from_sale=round((($not_used_coupon*100)/60))+round($used_coupon*1.5);
				}else{
					$start_limit=100;
					$exclued_from_sale=round((($not_used_coupon*100)/10))+round($used_coupon*1.5);
				}

				//$exclued_from_sale=round((($not_used_coupon*100)/10))+round($used_coupon*1.5);
				$total_sales=round($total_sales-$exclued_from_sale);//////LOCK SHAWPON
				//$total_sales=round($total_sales);
				//$consider_permission_percentage=(rand(3255, 3575)/100);//////////////////////SET AS MY WISH
				//$consider_sale_amount=round(($total_sales*$consider_permission_percentage)/100);

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

				if($total_sales>=$start_limit){
					$maximum_coupon_discount=rand(302, 399);
					if($total_sales>$start_limit AND $total_sales<25000){
						$temp=round((($total_sales-$start_limit)/1000)*rand(18, 20));
						$maximum_coupon_discount+=rand(($temp-30), $temp);
					}
					elseif($total_sales>=25000 AND $total_sales<40000){
						$maximum_coupon_discount+=rand(202, 299);
						$temp=round((($total_sales-$start_limit)/1000)*rand(18, 20));
						$maximum_coupon_discount+=rand(($temp-30), $temp);
					}
					elseif($total_sales>=40000 AND $total_sales<50000){
						$maximum_coupon_discount+=round((rand(202, 299))*2);
						$temp=round((($total_sales-$start_limit)/1000)*rand(18, 20));
						$maximum_coupon_discount+=rand(($temp-30), $temp);
					}elseif($total_sales>=50000){
						$multiple=round(($total_sales/15000),2);
						$maximum_coupon_discount+=round((rand(202, 299))*$multiple);
						$temp=round((($total_sales-$start_limit)/1000)*rand(18, 20));
						$maximum_coupon_discount+=rand(($temp-30), $temp);
					}
				}
				$maximum_coupon_discount=$maximum_coupon_discount+round((($maximum_coupon_discount*7.5)/100));

				//////////////////$used_coupon card 5% deduct//////////////
				$deduct_card=round(round($used_coupon*1.5)*5/100);
				$maximum_coupon_discount=$maximum_coupon_discount-$deduct_card;

				$not_used_coupon_yet=0;
				$query_coupon = $this->db->query("SELECT sum(coupon_value) AS coupon_value FROM pos_ospos_eid_coupon
												 WHERE DATE_FORMAT(coupon_date,'%Y-%m-%d')>='2024-03-22' AND is_used='0'");

				foreach ($query_coupon->result() as $row_coupon) {
					$not_used_coupon_yet+=round($row_coupon->coupon_value);/////////////////////NEXT CONSIDER
				}


				$not_used_coupon_yet_consider=0;


				if($current_date>'2024-03-22' AND $current_date<='2024-03-31'){
					$not_used_coupon_yet_consider=round((($not_used_coupon_yet*rand(35, 45))/100));
				}else if($current_date>'2024-03-31' AND $current_date<='2024-04-02'){//////////////BIG SALE//////////////////
					$not_used_coupon_yet_consider=round((($not_used_coupon_yet*rand(45, 55))/100));
				}else if($current_date>'2024-04-02' AND $current_date<='2024-04-07'){
					$not_used_coupon_yet_consider=round((($not_used_coupon_yet*rand(50, 60))/100));
				}else{																//////////////BIG SALE//////////////////
					$not_used_coupon_yet_consider=round((($not_used_coupon_yet*rand(80, 90))/100));
				}
				$maximum_coupon_discount=$maximum_coupon_discount+$not_used_coupon_yet_consider;

				//$maximum_coupon_discount+=$not_used_coupon+round(($total_give_coupon*2.75)/100);
				//$maximum_coupon_discount=round(round(($consider_sale_amount*10.75)/100)+$not_used_coupon+round(($total_give_coupon*2.75)/100)+$additional_amount);



				$permission_coupon=0;
				$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_cash FROM ospos_permissions_relations_customer
		WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND  payment_type='COUPON'");

				foreach ($query->result() as $row) {
					$permission_coupon=$row->total_cash;/////////////////////NEXT CONSIDER
				}
				if($permission_coupon>=$maximum_coupon_discount){
					$maximum_coupon_discount=0;
				}else{
					$maximum_coupon_discount=$maximum_coupon_discount-$permission_coupon;
				}

				/////////////////////////HAVE CASH/////////////////////////////////////

				//////////////////CURRENT CASH////////////////////////
				$current_cash=0;

				$query = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND  payment_type='CASH'");

				foreach ($query->result() as $row) {
					$current_cash=$row->total_cash;/////////////////////NEXT CONSIDER
				}
				if($current_cash-$maximum_coupon_discount<=645){
					$maximum_coupon_discount=$current_cash-645;
				}

				if($maximum_coupon_discount>0){


					$sql="SELECT  sale_id,payment_amount,branch_name FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					$payment_sale_id_amount=0;
					$payment_sale_id_amount_coupon=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
						$payment_sale_id_amount_coupon=intval($row->branch_name);
					}

					$coupon_discount_consider_total=0;
					$coupon_discount_consider_vat_total=0;


					$coupon_discount_consider_total=round((($maximum_coupon_discount/107.5)*100));
					$coupon_discount_consider_vat_total=round((($coupon_discount_consider_total*7.5)/100),2);

					$cash_amount_coupon=round($coupon_discount_consider_total+$coupon_discount_consider_vat_total);


					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($coupon_discount_consider_total))."'
		,branch_name='".($payment_sale_id_amount_coupon+round($maximum_coupon_discount))."'
		WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount,branch_name)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($coupon_discount_consider_total)."',
		'".round($maximum_coupon_discount)."')";
						$this->db->query($insert_sql);////NEXT
					}

					//////////////////////////UPDATE SALES DETAILS/////////////////////////////////

					$item_details=array();
					$query_item_details = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$sale_id_modify."' LIMIT 1");

					foreach ($query_item_details->result() as $row_details) {
						$item_details=$row_details;
					}

					$total_sale_amount_suma=round($item_details->vat_enable_price_after_discount)-$coupon_discount_consider_total;
					$vat_amount_real_suma=round($item_details->vat_amount,2)-$coupon_discount_consider_vat_total;

					$query_sales_item="UPDATE ospos_sales_items
                    SET  vat_enable_price_after_discount='".mysql_real_escape_string($total_sale_amount_suma)."'
					,vat_amount='".mysql_real_escape_string($vat_amount_real_suma)."'
                    WHERE sale_id='".mysql_real_escape_string($item_details->sale_id)."' AND line='".mysql_real_escape_string($item_details->line)."' AND stock_id='".mysql_real_escape_string($item_details->stock_id)."' AND lot_no='".mysql_real_escape_string($item_details->lot_no)."' AND vat_enable_price_after_discount='".mysql_real_escape_string($item_details->vat_enable_price_after_discount)."'";
					$this->db->query($query_sales_item);////NEXT


					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);


					$payment_sale_id=0;
					$payment_sale_id_amount=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}
					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_amount_coupon))."'
		WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".round($cash_amount_coupon)."')";
						$this->db->query($insert_sql);////NEXT
					}


					$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'COUPON',
		'".round($consider_sale_amount)."',
		'0',
		'".round($cash_amount_coupon)."',
		'".round($cash_amount_coupon)."',
		'".round($cash_amount_coupon)."',
		'0')";
					$this->db->query($query);////NEXT
				}
			}


			//////////////////////////EID2022////////////////////////////////////////
			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}
			$sale_id_modify=0;
			if($current_date>='2022-05-02' AND $current_date<='2022-05-03'){


				$query = $this->db->query("SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND is_sync=0 LIMIT 1");
				foreach ($query->result() as $row) {
					$sale_id_modify=$row->sale_id;
				}

				if(intval($sale_id_modify)>0){

					$query = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale,discount_percent,total_discount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."')");

					foreach ($query->result() as $row) {
						if(intval($row->discount_percent)>0){
							$total_sales+=round(($row->total_discount*7.5)/100);/////////////////////NEXT CONSIDER
						}else{
							$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
						}
					}

					$percentage_eid_2022=(rand(1010, 1030)/100);//////////////////////SET AS MY WISH

					$eid_2022_consider_amount=round(($total_sales*$percentage_eid_2022)/100);

					$difference_product_discount_cal_consider=0;
					$maximum_coupon_discount=0;
					$difference_product_discount_cal_consider=round(($eid_2022_consider_amount*20)/100);

					$maximum_coupon_discount=round(($eid_2022_consider_amount*8)/100);

					$current_cash=0;

					$query = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND  payment_type='CASH'");

					foreach ($query->result() as $row) {
						$current_cash=$row->total_cash;/////////////////////NEXT CONSIDER
					}
					if($current_cash-($difference_product_discount_cal_consider+$maximum_coupon_discount)<=5000){
						$difference_product_discount_cal_consider=$current_cash-5000;
						$maximum_coupon_discount=0;
					}

					if(($difference_product_discount_cal_consider+$maximum_coupon_discount)>0){

						///////////////////////CHECK IS ALREADY/////////////////////////

						$pemission_product_discount=0;
						$pemission_product_discount_coupon=0;

						$query_permission = $this->db->query("SELECT payment_type, SUM(purchase_discount_my) AS purchase_discount_my
		FROM ospos_permissions_relations_customer 
		WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."'  GROUP BY payment_type");

						foreach ($query_permission->result() as $row_permission) {

							if($row_permission->payment_type=="EID2022"){
								$pemission_product_discount+=round((round($row_permission->purchase_discount_my)*100)/107.5);
							}

							if($row_permission->payment_type=="COUPON_EID2022"){
								$pemission_product_discount_coupon+=round($row_permission->purchase_discount_my);
							}
						}

						if($pemission_product_discount_coupon>=$maximum_coupon_discount){
							$maximum_coupon_discount=0;
						}
						if($pemission_product_discount>=$difference_product_discount_cal_consider){
							$difference_product_discount_cal_consider=0;
						}

						////////////////////////SALES ITEMS WILL UPDATE////////////////////////////////
						$sales_item_info=array();
						$sql="SELECT * FROM ospos_sales_items WHERE sale_id ='".$sale_id_modify."' ORDER BY line ASC LIMIT 1";
						$query = $this->db->query($sql);
						foreach ($query->result() as $row) {
							$sales_item_info=$row;
						}
						if($difference_product_discount_cal_consider+$maximum_coupon_discount>0){

							$difference_product_discount_cal_consider_cash=0;

							if($difference_product_discount_cal_consider>0){
								$vat_increase_decrease=number_format((($difference_product_discount_cal_consider*7.5)/100),2,'.','');
								$update_sql="UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_increase_decrease."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$difference_product_discount_cal_consider."'
						WHERE sale_id='".$sales_item_info->sale_id."' AND stock_id='".$sales_item_info->stock_id."' AND lot_no='".$sales_item_info->lot_no."' AND line='".$sales_item_info->line."' AND item_cost_price='".$sales_item_info->item_cost_price."'";
								$this->db->query($update_sql);////////////////////////////NEXT
								$difference_product_discount_cal_consider_cash=round($difference_product_discount_cal_consider+$vat_increase_decrease);
							}

							$sql="SELECT  sale_id,payment_amount,branch_name FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							$payment_sale_id_amount=0;
							$payment_sale_id_amount_coupon=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
								$payment_sale_id_amount_coupon=intval($row->branch_name);
							}

							if($payment_sale_id){
								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($difference_product_discount_cal_consider)+round($maximum_coupon_discount))."'
		,branch_name='".($payment_sale_id_amount_coupon+round($maximum_coupon_discount))."'
		WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
								$this->db->query($update_query_permission);////////////////NEXT
							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount,branch_name)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".(round($difference_product_discount_cal_consider)+round($maximum_coupon_discount))."',
		'".round($maximum_coupon_discount)."')";
								$this->db->query($insert_sql);////NEXT
							}

							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							$payment_sale_id_amount=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}

							if($payment_sale_id){
								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-(round($maximum_coupon_discount)+round($difference_product_discount_cal_consider_cash)))."'
		WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
								$this->db->query($update_query_permission);////////////////NEXT
							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".(round($maximum_coupon_discount)+round($difference_product_discount_cal_consider_cash))."')";
								$this->db->query($insert_sql);////NEXT
							}

							if($maximum_coupon_discount>0){
								$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'COUPON_EID2022',
		'".round($eid_2022_consider_amount)."',
		'0',
		'".round($maximum_coupon_discount)."',
		'".round($maximum_coupon_discount)."',
		'".round($maximum_coupon_discount)."',
		'0')";
								$this->db->query($query);////NEXT
							}

							if($difference_product_discount_cal_consider_cash>0){
								$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'EID2022',
		'".round($eid_2022_consider_amount)."',
		'0',
		'".round($difference_product_discount_cal_consider_cash)."',
		'".round($difference_product_discount_cal_consider_cash)."',
		'".round($difference_product_discount_cal_consider_cash)."',
		'0')";
								$this->db->query($query);////NEXT
							}

						}
					}
				}
				$update_eid_customer="UPDATE ospos_sales SET customer_id='30079' WHERE sale_id='".$sale_id_modify."'";
				$this->db->query($update_eid_customer);////////////////NEXT

			}
		}

		$update_query_permission_recheck_vat="UPDATE ospos_sales_items
		SET vat_amount=round(((vat_enable_price_after_discount*vat_percentage)/100),2) 
		WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' 
		AND acc_location='".LOCATION_CODE."' AND is_sync=0)";

		$this->db->query($update_query_permission_recheck_vat);////////////////NEXT
		return 1;
	}

	function bogo2022execute($current_date){

		/////////////////////////////////////////////BOGO DATABASE//////////////////////////////////////
		$current_directory = getcwd();

		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_BOGO_ACTIVE']=0;
		}

		if($config_mrp['CORE_BOGO_ACTIVE']==1){

			if($config_mrp['MRP_RAND_END']>=1575){
				$bogo_consider_percentage=number_format((round($config_mrp['MRP_RAND_END']*50/100)/100),2,'.','');
			}else{
				$bogo_consider_percentage=7;
			}

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}


			$bogo_2022_data_price_group=array();
			$bogo_2022_data=array();

			$bogo_price_wise_item_name=array();

			$query_bogo_2022 = $this->db->query("SELECT * FROM bogo_2022 WHERE TRIM(item_name) IN(
		'Male Full Shirt',
		'Male T- Shirt',
		'Three Piece')
		ORDER BY price DESC");


			foreach ($query_bogo_2022->result() as $row_bogo_2022) {
				$permission=1;
				if($row_bogo_2022->item_name=="Male Full Shirt"){
					$price_range=array();

					$price_range[]=650;
					$price_range[]=750;
					$price_range[]=1090;
					$price_range[]=1190;
					$price_range[]=1890;
					$price_range[]=1990;
					$price_range[]=2090;
					$price_range[]=2190;

					$off_location_array=array();
					$off_location_array[]="UTA";

					if(!in_array(LOCATION_CODE,$off_location_array)){////////////////////UTA OFF Three Piece
						$price_range[]=2290;
					}

					if(!in_array($row_bogo_2022->price,$price_range)){////////////////////UTA OFF Three Piece
						$permission=0;
					}
					/*
					if(intval($row_bogo_2022->price)<=1100 AND intval($row_bogo_2022->price)>750){
					$permission=0;
					}*/
				}
				if($row_bogo_2022->item_name=="Male T- Shirt"){
					if(intval($row_bogo_2022->price)<=600){
						$permission=0;
					}
				}
				if($row_bogo_2022->item_name=="Three Piece"){
					if(intval($row_bogo_2022->price)<3000){
						$permission=0;
					}
					if(substr($row_bogo_2022->stock_id,0,3)!='053'){
						$permission=0;
					}
					$off_location_array=array();
					$off_location_array[]="UTA";

					if(in_array(LOCATION_CODE,$off_location_array)){////////////////////UTA OFF Three Piece
						$permission=0;
					}
				}

				if($permission==1){
					$bogo_2022_data[]=$row_bogo_2022;
					$bogo_2022_data_price_group[$row_bogo_2022->price]=$row_bogo_2022->price;
					$bogo_price_wise_item_name[$row_bogo_2022->price][$row_bogo_2022->item_name]=$row_bogo_2022->item_name;
				}
			}


			$current_sales_id=array();
			$current_sales_reference=array();

			$query_current_sales = $this->db->query("SELECT sale_id,receipt_no FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND is_sync=0");
			foreach ($query_current_sales->result() as $row_current_sales) {
				$current_sales_id[]=$row_current_sales->sale_id;
				$current_sales_reference[$row_current_sales->sale_id]=$row_current_sales->receipt_no;
			}

			$current_sales_items=array();
			$current_sales_items_index_wise=array();

			if(count($current_sales_id)){
				$consider_sale_id_string="'".implode("','",$current_sales_id)."'";
				///////////////////////////////MAKE SINGLE ROWS//////////////////////////////////////
				$query_multi = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_string.") AND discount_percent=0 AND quantity_purchased>1");
				foreach ($query_multi->result() as $row_multi) {
					if(fmod($row_multi->quantity_purchased, 1)== 0.00){
						$max_line=1;
						$query_multi_max = $this->db->query("SELECT MAX(line) as line FROM ospos_sales_items WHERE sale_id='".$row_multi->sale_id."'");
						foreach ($query_multi_max->result() as $row_multi_max) {
							$max_line=$row_multi_max->line;
						}

						$mrp_details="";

						if(trim($row_multi->mrp_details)){
							$mrp_details_array_divided=array();
							$mrp_details_array=array();
							$mrp_details_array=explode("NEWMRP",$row_multi->mrp_details);

							foreach ($mrp_details_array as $mrp_key => $mrp_value) {
								$mrp_details_stock_insert_array=array();
								$mrp_details_stock_insert_array=explode("#",$mrp_value);

								$mrp_details_stock_insert_array[4]=$mrp_details_stock_insert_array[4]/$row_multi->quantity_purchased;
								$mrp_details_array_divided[]=implode("#",$mrp_details_stock_insert_array);
							}


							$mrp_details=implode("NEWMRP",$mrp_details_array_divided);
						}


						$real_vat_amount=$row_multi->vat_amount;
						$real_vat_enable_price_after_discount=$row_multi->vat_enable_price_after_discount;


						$individual_vat_amount=number_format(($real_vat_amount/$row_multi->quantity_purchased),2,'.','');
						$new_row_vat_amount_total=number_format($individual_vat_amount*($row_multi->quantity_purchased-1),2,'.','');
						$update_row_vat_amount=number_format($real_vat_amount-$new_row_vat_amount_total,2,'.','');

						$individual_vat_enable_price_after_discount=number_format(($real_vat_enable_price_after_discount/$row_multi->quantity_purchased),2,'.','');
						$new_row_vat_enable_price_after_discount_total=number_format($individual_vat_enable_price_after_discount*($row_multi->quantity_purchased-1),2,'.','');
						$update_row_vat_enable_price_after_discount=number_format($real_vat_enable_price_after_discount-$new_row_vat_enable_price_after_discount_total,2,'.','');

						$modified_data_for_update['total_sale_amount']=number_format($row_multi->total_sale_amount/$row_multi->quantity_purchased,2,'.','');
						$modified_data_for_update['vat_enable_price']=number_format($row_multi->vat_enable_price/$row_multi->quantity_purchased,2,'.','');
						$modified_data_for_update['vat_amount']=$update_row_vat_amount;
						$modified_data_for_update['vat_enable_price_after_discount']=$update_row_vat_enable_price_after_discount;
						$modified_data_for_update['quantity_purchased']=1;
						$modified_data_for_update['mrp_details']=$mrp_details;

						foreach ($row_multi as $ins_key => $ins_value) {
							$modified_data_for_insert[$ins_key]=$ins_value;
						}

						$modified_data_for_insert['total_sale_amount']=number_format($row_multi->total_sale_amount/$row_multi->quantity_purchased,2,'.','');
						$modified_data_for_insert['vat_enable_price']=number_format($row_multi->vat_enable_price/$row_multi->quantity_purchased,2,'.','');
						$modified_data_for_insert['vat_amount']=$individual_vat_amount;
						$modified_data_for_insert['vat_enable_price_after_discount']=$individual_vat_enable_price_after_discount;
						$modified_data_for_insert['quantity_purchased']=1;
						$modified_data_for_insert['mrp_details']=$mrp_details;

						$update_query="UPDATE ospos_sales_items SET ";

						foreach ($modified_data_for_update as $update_key => $update_value) {
							$update_query.="\n".$update_key."='".$update_value."',";
						}

						$update_query=substr($update_query, 0, -1);
						$update_query.=" WHERE sale_id='".$row_multi->sale_id."' AND stock_id='".$row_multi->stock_id."' AND lot_no='".$row_multi->lot_no."' AND line='".$row_multi->line."' LIMIT 1";

						$this->db->query($update_query);

						for($i=1;$i<$row_multi->quantity_purchased;$i++){
							$insert_query="INSERT INTO ospos_sales_items (";
							$values_string="";
							foreach ($modified_data_for_insert as $insert_key => $insert_value) {
								$insert_query.="\n".$insert_key.",";
								if($insert_key=="line"){
									$insert_value=$max_line+1;
									$max_line++;
								}
								$values_string.="\n'".$insert_value."',";
							}
							$insert_query=substr($insert_query, 0, -1)."\n) VALUES(".substr($values_string, 0, -1).")";
							$this->db->query($insert_query);

						}
					}
				}

				/////////////////////////LINE UPDATE/////////////////////////

				foreach ($current_sales_id as $line_key => $line_value) {
					$query_line = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$line_value."' ORDER BY line ASC");

					$line_start=1;
					foreach ($query_line->result() as $row_line) {
						$update_query_line="UPDATE ospos_sales_items SET line='".$line_start."'";
						$update_query_line.=" WHERE sale_id='".$row_line->sale_id."' AND stock_id='".$row_line->stock_id."' AND lot_no='".$row_line->lot_no."' AND line='".$row_line->line."' LIMIT 1";
						$this->db->query($update_query_line);
						$line_start++;
					}
				}
				$current_date_price_group=array();


				$total_non_sync_sale_amount=0;

				$consider_price_string="'".implode("','",$bogo_2022_data_price_group)."'";
				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_string.")
			AND item_cost_price IN (".$consider_price_string.") 
			AND discount_percent=0 AND quantity_purchased>0 ORDER BY item_cost_price DESC");

				foreach ($query->result() as $row) {
					$index=$row->sale_id."#".$row->stock_id."#".$row->lot_no."#".$row->line."#".$row->item_cost_price."#".$row->vat_enable_price_after_discount;
					$current_sales_items[]=$row;
					$current_sales_items_index_wise[$index]=$row;
					$current_date_price_group[intval($row->item_cost_price)]=intval($row->item_cost_price);
					$total_non_sync_sale_amount+=intval($row->item_cost_price)*intval($row->quantity_purchased);
				}



				////////////////////////////////////VVI///////////////////////////////////////////

				/////////////////MINIMIZE $bogo_2022_data////////////////////////

				$bogo_2022_data_by_item=array();
				$bogo_2022_data_by_item_price=array();
				$bogo_2022_data_by_item_price=array();
				$bogo_2022_data_minimum=array();

				shuffle($bogo_2022_data);

				foreach ($bogo_2022_data as $min_key => $min_value) {
					$check_price=intval($min_value->price);
					if(in_array($check_price,$current_date_price_group)){
						$bogo_2022_data_minimum[]=$min_value;
						$bogo_2022_data_by_item[$min_value->item_name][]=$min_value;
						$bogo_2022_data_by_item_price[$min_value->item_name][intval($min_value->price)][]=$min_value;
					}
				}
				shuffle($bogo_2022_data_minimum);
				$match_data=array();
				$match_data_individual=array();

				shuffle($current_sales_items);

				foreach ($current_sales_items as $current_key => $current_value) {
					$index=$current_value->sale_id."#".$current_value->stock_id."#".$current_value->lot_no."#".$current_value->line."#".$current_value->item_cost_price."#".$current_value->vat_enable_price_after_discount;
					$compare_price=intval($current_value->item_cost_price);
					foreach ($bogo_2022_data_minimum as $minmum_key => $minimum_value) {

						if(intval($minimum_value->price)==$compare_price){
							$bogo_selection_all_data=$bogo_2022_data_by_item_price[$minimum_value->item_name][$compare_price];
							shuffle($bogo_selection_all_data);
							$match_data[$minimum_value->item_name][$compare_price]['items']=$bogo_selection_all_data[0];
							$match_data[$minimum_value->item_name][$compare_price]['sales_data']=$index;
							$match_data_individual[$minimum_value->item_name][$index]=$bogo_selection_all_data[0];
						}
					}
				}

				$used_index=array();
				$final_bogo_data=array();
				$final_bogo_data_item_wise=array();

				/////////////////////////////////1st Possible Double Items/////////////
				for($loop=0;$loop<=30;$loop++){
					foreach ($match_data_individual as $individual_key => $individual_value) {

						if(count($individual_value)>=2){
							$counting=1;
							foreach ($individual_value as $sele_key => $sele_value) {
								if($counting<=2){
									if(!in_array($sele_key,$used_index)){
										$final_bogo_data[$sele_key]=$sele_value;
										$final_bogo_data_item_wise[$individual_key][]=$sele_key;
										$used_index[$sele_key]=$sele_key;
										$counting++;
									}
								}
							}
						}
					}
				}


				$free_index=array();
				foreach ($final_bogo_data_item_wise as $refine_key => $refine_value) {
					$has_extra=count($refine_value)%2;
					if($has_extra!=0){
						unset($final_bogo_data_item_wise[$refine_key][end(array_keys($refine_value))]);
						unset($final_bogo_data[$refine_value[end(array_keys($refine_value))]]);
						unset($used_index[$refine_value[end(array_keys($refine_value))]]);
						$free_index[]=$refine_value[end(array_keys($refine_value))];
					}
				}

				/////////////////////////////////Final Possible Double Items/////////////


				$cupple_array=array();

				foreach ($current_sales_items as $sale_key => $sale_value) {
					$index_final=$sale_value->sale_id."#".$sale_value->stock_id."#".$sale_value->lot_no."#".$sale_value->line."#".$sale_value->item_cost_price."#".$sale_value->vat_enable_price_after_discount;
					if(!in_array($index_final,$used_index)){

						foreach ($match_data as $mdi_key => $mdivalue) {
							foreach ($mdivalue as $mdi_price_key => $mdi_price_value) {
								if($mdi_price_value['sales_data']==$index_final){
									$cupple_array[$mdi_key][$index_final]=$mdi_price_value['items'];
								}
							}
						}
					}
				}
				/////////////////////////////////1st Possible Double Items/////////////
				if(count($cupple_array)){
					for($loop=0;$loop<=30;$loop++){
						foreach ($cupple_array as $individual_key => $individual_value) {

							if(count($individual_value)>=2){
								$counting=1;
								foreach ($individual_value as $sele_key => $sele_value) {
									if($counting<=2){
										if(!in_array($sele_key,$used_index)){
											$final_bogo_data[$sele_key]=$sele_value;
											$final_bogo_data_item_wise[$individual_key][]=$sele_key;
											$used_index[$sele_key]=$sele_key;
											$counting++;
										}
									}
								}
							}
						}
					}
				}

				$free_index=array();
				foreach ($final_bogo_data_item_wise as $refine_key => $refine_value) {
					$has_extra=count($refine_value)%2;
					if($has_extra!=0){
						unset($final_bogo_data_item_wise[$refine_key][end(array_keys($refine_value))]);
						unset($final_bogo_data[$refine_value[end(array_keys($refine_value))]]);
						unset($used_index[$refine_value[end(array_keys($refine_value))]]);
						$free_index[]=$refine_value[end(array_keys($refine_value))];
					}
				}


				$today_already_clr=0;


				$query_already_clr = $this->db->query("SELECT SUM(clr_amount) AS clr_amount
			FROM ospos_clr_locwise
			WHERE DATE_FORMAT(sales_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."'");

				$today_already_clr_data=$query_already_clr->row();
				$today_already_clr=intval($today_already_clr_data->clr_amount);

				$today_total_sale=0;

				/*$query_today_sale = $this->db->query("SELECT SUM(vat_enable_price) AS vat_enable_price FROM ospos_sales_items
				WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND location='".LOCATION_CODE."')");
				*/
				$query_today_sale = $this->db->query("SELECT SUM(total_sale_amount) AS vat_enable_price FROM ospos_sales_items
				WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND location='".LOCATION_CODE."')");

				$today_total_sale_data=$query_today_sale->row();
				$today_total_sale=intval($today_total_sale_data->vat_enable_price);

				$bogo_consider_amount=intval($today_total_sale*$bogo_consider_percentage/100)-$today_already_clr;

				if($bogo_consider_amount>0){
					$price_consider_total=0;

					$bogo_consider_index_array=array();

					for($loop=0;$loop<=30;$loop++){
						foreach ($final_bogo_data_item_wise as $consider_key => $consider_value) {
							if($bogo_consider_amount>=100){
								if(count($consider_value)>=2){
									$select_count=0;
									$price_consider=0;
									foreach ($consider_value as $consider_single_key => $consider_single_value) {
										if($select_count<2){
											if(!in_array($consider_single_value,$bogo_consider_index_array)){
												$price_consider+=intval($final_bogo_data[$consider_single_value]->price);
												$select_count++;
												//$bogo_consider_index_array[]=$consider_single_value;
												$bogo_consider_index_array[$consider_single_value]=$consider_single_value;
											}
										}
									}
									$bogo_consider_amount=$bogo_consider_amount-$price_consider;
									$price_consider_total+=$price_consider;
								}
							}
						}
					}
					//////////////////////////////////////////////FINAL DATA SET/////////////////////////////////
					$bogo_final_data_set_array=array();

					$payment_update_array=array();

					$cash_in_hand=0;
					///////////////////////////////////TOTAL CASH IN HAND////////////////////
					$sql_cash_in_hand="SELECT SUM(payment_amount) AS payment_amount FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND location='".LOCATION_CODE."') AND payment_type='Cash'";

					$query_cash_in_hand = $this->db->query($sql_cash_in_hand);

					foreach ($query_cash_in_hand->result() as $row_cash) {
						$cash_in_hand=$row_cash->payment_amount;
					}
					$cash_in_hand=$cash_in_hand;

					$bogo_consider_index_array_approved=array();

					$total_permission_check_amt=0;

					foreach ($bogo_consider_index_array as $key => $value) {

						$total_discount_check=intval(($current_sales_items_index_wise[$value]->item_cost_price*$final_bogo_data[$value]->discount)/100);
						$vat_discount_check=intval((($total_discount_check*$current_sales_items_index_wise[$value]->vat_percentage)/100));
						$total_permission_check=$total_discount_check+$vat_discount_check;

						$total_permission_check_amt+=$total_permission_check;
						if($cash_in_hand>=$total_permission_check){
							$bogo_consider_index_array_approved[$key]=$value;
							$cash_in_hand=$cash_in_hand-$total_permission_check;
						}
					}
					$count_approved=count($bogo_consider_index_array_approved);
					if($count_approved%2!=0){
						unset($bogo_consider_index_array_approved[end(array_keys($bogo_consider_index_array_approved))]);
					}


					if(count($bogo_consider_index_array_approved)>0){

						$payment_data=array();

						foreach ($bogo_consider_index_array_approved as $final_key => $final_value) {
							$bogo_data=$final_bogo_data[$final_value];
							$current_sale_data=$current_sales_items_index_wise[$final_value];

							$current_sale_id=$current_sale_data->sale_id;
							$current_reference=$current_sales_reference[$current_sale_id];

							$force_reference=substr($current_reference,3).substr($current_reference,0,3);

							$date_moves_update="20".substr($current_sale_data->lot_no,0,2)."-".substr($current_sale_data->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

							/////////////////////////////////UPDATE////////////////////////////////

							$update_data_array=array();

							$update_data_array['stock_id']=$bogo_data->stock_id;
							$update_data_array['description']=$bogo_data->category_name."</br>".$bogo_data->item_name." - ".$bogo_data->item_size;
							$update_data_array['lot_no']=$bogo_data->lot_no;
							$update_data_array['discount_percent']=$bogo_data->discount;
							$total_discount=intval(($current_sale_data->item_cost_price*$bogo_data->discount)/100);
							$total_sale_amount=intval($current_sale_data->vat_enable_price-$total_discount);

							$update_data_array['total_discount']=number_format($total_discount,2,'.','');
							$update_data_array['total_sale_amount']=number_format($total_sale_amount,2,'.','');
							$update_data_array['item_unit_price']=number_format(($current_sale_data->item_cost_price-$total_discount),2,'.','');

							$vat_discount=number_format((($total_discount*$current_sale_data->vat_percentage)/100),2,'.','');

							$update_data_array['vat_amount']=number_format(($current_sale_data->vat_amount-$vat_discount),2,'.','');
							$update_data_array['vat_enable_price_after_discount']=number_format(round(($current_sale_data->vat_enable_price_after_discount-$total_discount)),2,'.','');
							$update_data_array['pcr_lot_no']=$bogo_data->lot_no;
							$payment_data[$current_sale_data->sale_id]+=number_format(($total_discount+$vat_discount),2,'.','');

							$mrp_details_array=array();

							if(trim($current_sale_data->mrp_details)){
								$mrp_details_array=explode("NEWMRP",trim($current_sale_data->mrp_details));
							}

							$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($current_sale_data->stock_id)."' AND a.lot_no='".mysql_real_escape_string($current_sale_data->lot_no)."' AND a.price='".mysql_real_escape_string($current_sale_data->item_cost_price)."' AND a.reference='".mysql_real_escape_string($current_sales_reference[$current_sale_data->sale_id])."' AND type='201' GROUP BY a.stock_id,a.lot_no,a.price");

							$stock_moves_current_data=$query_moves->row();


							$standard_cost=0;
							$visible=1;
							$is_imported=0;
							$swatch_code=0;
							if($stock_moves_current_data->standard_cost==0){
								$standard_cost=round(($current_sale_data->item_cost_price*52)/100);
								$stock_moves_current_data->standard_cost=round(($current_sale_data->item_cost_price*52)/100);
							}else{
								$standard_cost=$stock_moves_current_data->standard_cost;
								$visible=$stock_moves_current_data->visible;
								$is_imported=$stock_moves_current_data->is_imported;
								$swatch_code=$stock_moves_current_data->swatch_code;
							}

							$mrp_details_array[]=$current_sale_data->stock_id."#".$date_moves_update."#".$current_sale_data->item_cost_price."#".$force_reference."#-1#".$standard_cost."#".$visible."#".$current_sale_data->lot_no."#".$is_imported."#".$swatch_code;
							$mrp_details_array[]=$bogo_data->stock_id."#".$date_moves_update."#".$bogo_data->price."#".$force_reference."#1#".$bogo_data->standard_cost."#".$visible."#".$bogo_data->lot_no."#".$is_imported."#".$swatch_code;

							if(count($mrp_details_array)){
								$update_data_array['mrp_details']=implode("NEWMRP",$mrp_details_array);
							}
							//////////////////////////////UPDATE SALES ITEM DATA//////////////////////
							$update_query="UPDATE ospos_sales_items SET ";
							foreach ($update_data_array as $update_key => $update_value) {
								$update_query.="\n".$update_key."='".$update_value."',";
							}
							$update_query=substr($update_query, 0, -1);
							$update_query.=" WHERE sale_id='".$current_sale_data->sale_id."' AND stock_id='".$current_sale_data->stock_id."' AND lot_no='".$current_sale_data->lot_no."' AND line='".$current_sale_data->line."' LIMIT 1";
							$this->db->query($update_query);//////////////////////////NEXT

							///////////////////////////////INSERT STOCK MOVES//////////////////////////////////////////////////
							$stock_moves_new_sale_data="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$current_sale_data->sale_id."',
								'".$current_sale_data->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update."',
								'".$current_sale_data->sale_id."',
								'".$current_sale_data->item_cost_price."',
								'".$force_reference."',
								'-1',
								'0',
								'".$standard_cost."',
								'".$visible."',
								'".$current_sale_data->lot_no."',
								'".$is_imported."',
								'".$swatch_code."')";

							$this->db->query($stock_moves_new_sale_data);//////////////////////////NEXT

							$stock_moves_new_sale_data_bogo="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$current_sale_data->sale_id."',
								'".$bogo_data->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update."',
								'".$current_sale_data->sale_id."',
								'".$bogo_data->price."',
								'".$force_reference."',
								'1',
								'0',
								'".$bogo_data->standard_cost."',
								'".$visible."',
								'".$bogo_data->lot_no."',
								'".$is_imported."',
								'".$swatch_code."')";

							$this->db->query($stock_moves_new_sale_data_bogo);//////////////////////////NEXT


							///////////////////////////////UPDATE STOCK MOVES//////////////////////////////////////////////////

							$update_query_stock_moves="UPDATE stock_moves SET
					stock_id='".$update_data_array['stock_id']."',
					discount_percent='".$update_data_array['discount_percent']."',
					standard_cost='".$bogo_data->standard_cost."',
					lot_no='".$update_data_array['lot_no']."'
					WHERE trans_id='".$stock_moves_current_data->trans_id."' 
					AND stock_id='".$stock_moves_current_data->stock_id."'
					AND price='".$stock_moves_current_data->price."'
					AND reference='".$current_reference."'
					AND standard_cost='".$stock_moves_current_data->standard_cost."'
					AND lot_no='".$stock_moves_current_data->lot_no."'
					";
							$this->db->query($update_query_stock_moves);//////////////////////////NEXT

						}

						///////////////////////////////////////////////PAYMENT UPDATE///////////////////////////////////////////////
						foreach ($payment_data as $payment_key => $payment_value) {

							$cash_update_amount=number_format(round($payment_value),2,'.','');

							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$payment_key."' AND payment_type='Cash' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}
							if($payment_sale_id){
								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update_amount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
								$this->db->query($update_query_permission);////////////////NEXT

							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
										VALUES('".$payment_key."',
										'Cash',
										'-".round($cash_update_amount)."')";
								$this->db->query($insert_sql);////NEXT
							}

							$insert_query_clr="
										INSERT INTO ospos_clr_locwise(
										sales_time,
										loc_code,
										sale_id,
										total_price,
										previous_clr,
										current_clr,
										previous_sale_price_total,
										clr_amount_total,
										clr_amount
										)
										VALUES('".date("Y-m-d H:i:s",strtotime($current_date))."',
										'".LOCATION_CODE."',
										'".$payment_key."',
										'".$payment_value."',
										'".$payment_value."',
										'".round($cash_update_amount)."',
										'".$payment_value."',
										'".round($cash_update_amount)."',
										'".round($cash_update_amount)."')";

							$this->db->query($insert_query_clr);////NEXT
						}
					}
				}
			}
		}
		return true;
	}


	function before_sync_adjustment($current_date){

		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}

		$query = $this->db->query("SELECT SUM(vat_enable_price_after_discount+vat_amount) AS total_sale  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");
		$sale_amount=0;
		foreach ($query->result() as $row) {
			$sale_amount+=$row->total_sale;
		}

		$query = $this->db->query("SELECT SUM(payment_amount) AS total_collection FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND payment_type NOT IN ('Purchase Bonus','Purchase Discount')");
		$collect_amount=0;
		foreach ($query->result() as $row) {
			$collect_amount+=$row->total_collection;
		}

		/*
		$query = $this->db->query("SELECT branch_name AS total_collection FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND payment_type='Purchase Discount'");
		$coupon_amount=0;
		foreach ($query->result() as $row) {
		$coupon_amount+=intval($row->total_collection);
		}*/

		//return number_format((($collect_amount+$coupon_amount)-$sale_amount),2,'.','');
		return number_format(($collect_amount-$sale_amount),2,'.','');

	}

	function do_permission_customer($percentage,$current_date){

		$current_directory = getcwd();

		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_CUSTOMER_CARD_DISCOUNT_ACTIVE']=0;
		}

		if($config_mrp['CORE_CUSTOMER_CARD_DISCOUNT_ACTIVE']==1){
			////////////////5% VAT ITEMS////////////////

			$stock_id_with_other_vat=array();
			$query = $this->db->query("SELECT stock_id FROM stock_master WHERE tax_type_id!=1");

			foreach ($query->result() as $row) {
				$stock_id_with_other_vat[]=$row->stock_id;
			}

			$stock_id_without_other_vat_str="";
			$stock_id_only_other_vat_str="";
			if(count($stock_id_with_other_vat)){
				$stock_id_str="'".implode("','",$stock_id_with_other_vat)."'";
				$stock_id_without_other_vat_str=" AND stock_id NOT IN (".$stock_id_str.")";
				$stock_id_only_other_vat_str=" AND stock_id IN (".$stock_id_str.")";
			}else{
				$stock_id_without_other_vat_str=" AND stock_id NOT IN ('XXXXXXXX')";
				$stock_id_only_other_vat_str=" AND stock_id IN ('XXXXXXXX')";
			}

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}


			$query_customer = $this->db->query("SELECT id FROM pos_ospos_customers WHERE is_special=1  AND id!=26247");
			$special_customer_ids_array=array();

			foreach ($query_customer->result() as $row_special) {
				$special_customer_ids_array[]=$row_special->id;
			}

			$special_customer_ids_string="";
			if(count($special_customer_ids_array)){
				$special_customer_ids_string_temp="'".implode("','",$special_customer_ids_array)."'";
				$special_customer_ids_string=" AND (customer_id NOT IN(".$special_customer_ids_string_temp.") OR customer_id=0 OR customer_id IS NULL )";
			}

			////////////////////PCR::CONSIDER VAT 7.5%//////////////////////////////

			$today_sale_amount_without_pcr=0;

			$sales_info_last=array();
			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') ".$stock_id_without_other_vat_str." AND discount_percent>0 AND (pcr_lot_no='' OR pcr_lot_no IS NULL)");

			foreach ($query->result() as $row) {
				$today_sale_amount_without_pcr+=$row->total_discount;/////////////////////NEXT CONSIDER
				$sales_info_last=$row;
			}

			if($today_sale_amount_without_pcr>0){

				$vat_enable_price_after_discount_decrease_2_per=round(($today_sale_amount_without_pcr*7.5)/100);
				$vat_decrease_2_per=number_format((($vat_enable_price_after_discount_decrease_2_per*7.5)/100),2,'.','');

				$cash_in_hand_2_per=0;
				$sql_2_per="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
				$query_2_per = $this->db->query($sql_2_per);

				foreach ($query_2_per->result() as $row) {
					$cash_in_hand_2_per=$row->payment_amoount;
				}

				if(round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per)<=round($cash_in_hand_2_per+129)){

					$update_sql="
						UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_decrease_2_per."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease_2_per."'
						WHERE sale_id='".$sales_info_last->sale_id."' AND stock_id='".$sales_info_last->stock_id."' AND lot_no='".$sales_info_last->lot_no."' AND line='".$sales_info_last->line."' AND item_cost_price='".$sales_info_last->item_cost_price."'";


					$this->db->query($update_sql);////////////////////////////NEXT

					$sale_id_modify=$sales_info_last->sale_id;
					$cash_update=round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per);

					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update*-1)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease_2_per))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($vat_enable_price_after_discount_decrease_2_per)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash_7_5_per_discount',
						'".round($sales_info_last->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}

			////////////////////CONSIDER VAT 5%//////////////////////////////

			$today_sale_amount_without_pcr=0;

			$sales_info_last=array();
			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') ".$stock_id_only_other_vat_str." AND discount_percent>0 AND (pcr_lot_no='' OR pcr_lot_no IS NULL)");

			foreach ($query->result() as $row) {
				$today_sale_amount_without_pcr+=$row->total_discount;/////////////////////NEXT CONSIDER
				$sales_info_last=$row;
			}

			if($today_sale_amount_without_pcr>0){

				$vat_enable_price_after_discount_decrease_2_per=round(($today_sale_amount_without_pcr*5)/100);
				$vat_decrease_2_per=number_format((($vat_enable_price_after_discount_decrease_2_per*5)/100),2,'.','');

				$cash_in_hand_2_per=0;
				$sql_2_per="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
				$query_2_per = $this->db->query($sql_2_per);

				foreach ($query_2_per->result() as $row) {
					$cash_in_hand_2_per=$row->payment_amoount;
				}

				if(round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per)<=round($cash_in_hand_2_per+129)){

					$update_sql="
						UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_decrease_2_per."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease_2_per."'
						WHERE sale_id='".$sales_info_last->sale_id."' AND stock_id='".$sales_info_last->stock_id."' AND lot_no='".$sales_info_last->lot_no."' AND line='".$sales_info_last->line."' AND item_cost_price='".$sales_info_last->item_cost_price."'";


					$this->db->query($update_sql);////////////////////////////NEXT

					$sale_id_modify=$sales_info_last->sale_id;
					$cash_update=round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per);

					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update*-1)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease_2_per))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($vat_enable_price_after_discount_decrease_2_per)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash_5_per_discount',
						'".round($sales_info_last->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}


			////////////////////FIXED::CONSIDER VAT 7.5%//////////////////////////////

			$today_sale_amount=0;
			$sales_info_last=array();
			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') ".$stock_id_without_other_vat_str." AND discount_percent=0");

			foreach ($query->result() as $row) {
				$today_sale_amount+=$row->vat_enable_price;/////////////////////NEXT CONSIDER
				$sales_info_last=$row;
			}


			if($today_sale_amount>0){

				$vat_enable_price_after_discount_decrease_2_per=round(($today_sale_amount*1)/100);
				$vat_decrease_2_per=number_format((($vat_enable_price_after_discount_decrease_2_per*7.5)/100),2,'.','');

				$cash_in_hand_2_per=0;
				$sql_2_per="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
				$query_2_per = $this->db->query($sql_2_per);

				foreach ($query_2_per->result() as $row) {
					$cash_in_hand_2_per=$row->payment_amoount;
				}
				if(round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per)<=round($cash_in_hand_2_per+129)){

					$update_sql="
						UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_decrease_2_per."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease_2_per."'
						WHERE sale_id='".$sales_info_last->sale_id."' AND stock_id='".$sales_info_last->stock_id."' AND lot_no='".$sales_info_last->lot_no."' AND line='".$sales_info_last->line."' AND item_cost_price='".$sales_info_last->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT

					$sale_id_modify=$sales_info_last->sale_id;
					$cash_update=round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per);

					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update*-1)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease_2_per))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($vat_enable_price_after_discount_decrease_2_per)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash_2_per',
						'".round($sales_info_last->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}


			////////////////////FIXED::CONSIDER VAT 5%//////////////////////////////

			$today_sale_amount=0;
			$sales_info_last=array();
			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND payment_type!='' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." AND acc_location='".LOCATION_CODE."') ".$stock_id_only_other_vat_str." AND discount_percent=0");

			foreach ($query->result() as $row) {
				$today_sale_amount+=$row->vat_enable_price;/////////////////////NEXT CONSIDER
				$sales_info_last=$row;
			}


			if($today_sale_amount>0){

				$vat_enable_price_after_discount_decrease_2_per=round(($today_sale_amount*1)/100);
				$vat_decrease_2_per=number_format((($vat_enable_price_after_discount_decrease_2_per*5)/100),2,'.','');

				$cash_in_hand_2_per=0;
				$sql_2_per="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
				$query_2_per = $this->db->query($sql_2_per);

				foreach ($query_2_per->result() as $row) {
					$cash_in_hand_2_per=$row->payment_amoount;
				}
				if(round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per)<=round($cash_in_hand_2_per+129)){

					$update_sql="
						UPDATE ospos_sales_items SET
						vat_amount=vat_amount-'".$vat_decrease_2_per."',
						vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease_2_per."'
						WHERE sale_id='".$sales_info_last->sale_id."' AND stock_id='".$sales_info_last->stock_id."' AND lot_no='".$sales_info_last->lot_no."' AND line='".$sales_info_last->line."' AND item_cost_price='".$sales_info_last->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT

					$sale_id_modify=$sales_info_last->sale_id;
					$cash_update=round($vat_enable_price_after_discount_decrease_2_per+$vat_decrease_2_per);

					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
					$query = $this->db->query($sql);

					$payment_sale_id=0;
					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$this->db->query($update_query_permission);////////////////NEXT

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'".round($cash_update*-1)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$payment_sale_id=0;
					$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$payment_sale_id=$row->sale_id;
						$payment_sale_id_amount=$row->payment_amount;
					}

					if($payment_sale_id){

						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease_2_per))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
						$this->db->query($update_query_permission);////////////////NEXT
					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($vat_enable_price_after_discount_decrease_2_per)."')";
						$this->db->query($insert_sql);////NEXT
					}

					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash_2_per',
						'".round($sales_info_last->vat_enable_price)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
					$this->db->query($query);////NEXT
				}
			}


			/*	ALL Customers	*/
			$query = $this->db->query("SELECT * FROM pos_ospos_customers WHERE gs_card_no!='' AND is_dealer='Retail' AND loc_code!='CST' AND status=2 AND id!='26246' AND id!='26247' ");
			$my_discount_customer_all=array();
			$my_discount_customer=array();
			$my_discount_customer_details=array();

			foreach ($query->result() as $row) {
				$my_discount_customer_all[]=$row->id;
				$my_discount_customer_details[$row->id]=$row->point;
			}

			shuffle($my_discount_customer_all);

			$random_number=-1;
			/*	ALL Customers	Facebook */


			$query = $this->db->query("SELECT * FROM pos_ospos_customers WHERE gs_card_no!='' AND is_dealer='Retail' AND loc_code!='CST' AND facebook_customer=1 AND status=2");
			$my_discount_customer_facebook=array();

			foreach ($query->result() as $row) {
				$my_discount_customer_facebook[]=$row->id;
			}
			shuffle($my_discount_customer_facebook);

			$random_number=(rand(1,3));

			$my_discount_customer_facebook_final=array();

			for($i=0;$i<$random_number;$i++){
				$my_discount_customer_facebook_final[]=$my_discount_customer_facebook[$i];
			}

			foreach ($my_discount_customer_facebook_final as $key => $value) {
				if(intval($value)){
					$my_discount_customer[]=$value;
				}
			}


			foreach ($my_discount_customer_all as $key => $value) {
				if(intval($value)){
					$my_discount_customer[]=$value;
				}
			}
			////////////////////CARD::CONSIDER VAT 7.5%//////////////////////////////

			$sales_all_data_additional_all=array();

			$sales_id_consider_for_purchase_discount=array();

			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." )
		".$stock_id_without_other_vat_str." AND discount_percent=0 ORDER BY sale_id ASC ");

			$sales_all_data_additional_all=array();
			foreach ($query->result() as $row) {
				if(intval($row->cus_permission)==0){
					$sales_all_data_additional_all[]=$row;
				}
				$sales_id_consider_for_purchase_discount[]=$row->sale_id;
			}

			$sales_id_consider_for_purchase_discount_str="";
			if(count($sales_id_consider_for_purchase_discount)){
				$stock_id_str_purchase_discount="'".implode("','",$sales_id_consider_for_purchase_discount)."'";
				$sales_id_consider_for_purchase_discount_str=" AND sale_id IN (".$stock_id_str_purchase_discount.")";
			}


			foreach ($sales_all_data_additional_all as $key => $value) {

				$card_discount_percentage=0;
				$sale_id_modify=$value->sale_id;



				if(intval($value->cus_permission)<7.3){
					$card_discount_percentage=8;
					if(intval($value->cus_permission)>=5){
						$card_discount_percentage=2.5;
					}
				}

				/*
				if(intval($value->cus_permission)<20){
				$card_discount_percentage=8;
				}*/


				if($card_discount_percentage>0){
					$vat_enable_price_after_discount_decrease=round(($value->vat_enable_price*$card_discount_percentage)/100);
					$vat_decrease=number_format((($vat_enable_price_after_discount_decrease*7.5)/100),2,'.','');


					$update_sql="
		UPDATE ospos_sales_items SET
		vat_amount=vat_amount-'".$vat_decrease."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease."',
		cus_permission=cus_permission+'".$card_discount_percentage."'

		WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT

					$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$cash_in_hand=$row->payment_amoount;
					}

					$sale_id_modify=$value->sale_id;

					$cash_update=round($vat_enable_price_after_discount_decrease+$vat_decrease);

					if($cash_in_hand>=round($cash_update+129)){


						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
						$query = $this->db->query($sql);

						$payment_sale_id=0;
						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}

						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
							$this->db->query($update_query_permission);////////////////NEXT

						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'".round($cash_update*-1)."')";
							$this->db->query($insert_sql);////NEXT
						}


						$payment_sale_id=0;
						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
						$query = $this->db->query($sql);

						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}

						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
							$this->db->query($update_query_permission);////////////////NEXT
						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($vat_enable_price_after_discount_decrease)."')";
							$this->db->query($insert_sql);////NEXT
						}


						$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($value->vat_enable_price)."',
		'0',
		'".round($cash_update)."',
		'".round($cash_update)."',
		'".round($cash_update)."',
		'0')";
						$this->db->query($query);////NEXT


						$cutomer_id_index=rand(0,count($my_discount_customer));
						$customer_id=$my_discount_customer[$cutomer_id_index];///////////////////TEMP OFF FOR 20%
						///$customer_id="26246";///////////////////TEMP OFF FOR 20%


						if($card_discount_percentage<=3){
							/*$update_sale_sql="UPDATE ospos_sales set is_permission=1
							WHERE sale_id='".$value->sale_id."'";*/

						}else{
							$update_sale_sql="UPDATE ospos_sales set customer_id='".$customer_id."'
		WHERE sale_id='".$value->sale_id."' AND (customer_id IS NULL OR customer_id='0' OR customer_id NOT IN('27530','27531'))";
						}
						$this->db->query($update_sale_sql);

					}
				}
			}

			$payment_sale_id=0;
			$sql="SELECT sale_id,sum(payment_amount) AS payment_amount FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND (is_permission=0 OR is_permission IS NULL)) ".$sales_id_consider_for_purchase_discount_str." AND payment_type='Purchase Discount'";
			$query = $this->db->query($sql);

			$payment_sale_id_edit=0;
			$payment_sale_id_amount_edit=0;

			foreach ($query->result() as $row) {
				$payment_sale_id_edit=$row->sale_id;
				$payment_sale_id_amount_edit=$row->payment_amount;
			}

			$pur_discount=round(number_format((($payment_sale_id_amount_edit)*7.5/100),2,'.',''));
			$pur_discount_vat=number_format(($pur_discount*7.5)/100,2,'.','');

			$cash_discount=round($pur_discount+$pur_discount_vat);

			if($pur_discount>0){


				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$payment_sale_id_edit."'");

				$dis_value=array();
				foreach ($query->result() as $row) {
					$dis_value=$row;
				}


				$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount-'".$pur_discount_vat."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$pur_discount."'
		WHERE sale_id='".$dis_value->sale_id."' AND stock_id='".$dis_value->stock_id."' AND lot_no='".$dis_value->lot_no."' AND line='".$dis_value->line."' AND item_cost_price='".$dis_value->item_cost_price."'";

				$this->db->query($update_sql);////////////////////////////NEXT


				$sale_id_modify=$dis_value->sale_id;

				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_discount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".round($cash_discount)."')";
					$this->db->query($insert_sql);////NEXT
				}


				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($pur_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT


				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($pur_discount)."')";
					$this->db->query($insert_sql);////NEXT

				}

				$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($dis_value->vat_enable_price)."',
		'0',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'0')";
				$this->db->query($query);////NEXT

			}


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." )
		".$stock_id_without_other_vat_str." AND discount_percent>0 ORDER BY sale_id ASC ");

			$sales_all_data_additional_all_discount=array();
			foreach ($query->result() as $row) {
				if(intval($row->cus_permission)==0){
					$sales_all_data_additional_all_discount[]=$row;
				}
			}

			foreach ($sales_all_data_additional_all_discount as $dis_key => $dis_value) {

				$pur_discount=round(number_format((($dis_value->total_sale_amount)*($dis_value->discount_percent/10)/100),2,'.',''));
				$pur_discount_vat=number_format(($pur_discount*7.5)/100,2,'.','');

				$cash_discount=round($pur_discount+$pur_discount_vat);
				$pur_discount_line=round($pur_discount);

				$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount-'".$pur_discount_vat."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$pur_discount_line."',
		cus_permission='0'
		WHERE sale_id='".$dis_value->sale_id."' AND stock_id='".$dis_value->stock_id."' AND lot_no='".$dis_value->lot_no."' AND line='".$dis_value->line."' AND item_cost_price='".$dis_value->item_cost_price."'";


				$this->db->query($update_sql);////////////////////////////NEXT

				$sale_id_modify=$dis_value->sale_id;

				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_discount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".round($cash_discount)."')";
					$this->db->query($insert_sql);////NEXT
				}


				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}



				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($pur_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT


				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($pur_discount)."')";
					$this->db->query($insert_sql);////NEXT

				}

				$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($dis_value->vat_enable_price)."',
		'0',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'0')";
				$this->db->query($query);////NEXT

			}

			/////////////////YES///////////////

			////////////////////CARD::CONSIDER VAT 5%//////////////////////////////

			$sales_all_data_additional_all=array();

			$sales_id_consider_for_purchase_discount=array();

			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." )
		".$stock_id_only_other_vat_str." AND discount_percent=0 ORDER BY sale_id ASC ");

			$sales_all_data_additional_all=array();
			foreach ($query->result() as $row) {
				if(intval($row->cus_permission)==0){
					$sales_all_data_additional_all[]=$row;
				}
				$sales_id_consider_for_purchase_discount[]=$row->sale_id;
			}

			$sales_id_consider_for_purchase_discount_str="";
			if(count($sales_id_consider_for_purchase_discount)){
				$stock_id_str_purchase_discount="'".implode("','",$sales_id_consider_for_purchase_discount)."'";
				$sales_id_consider_for_purchase_discount_str=" AND sale_id IN (".$stock_id_str_purchase_discount.")";
			}



			foreach ($sales_all_data_additional_all as $key => $value) {

				$card_discount_percentage=0;
				$sale_id_modify=$value->sale_id;



				if(intval($value->cus_permission)<7.3){
					$card_discount_percentage=8;
					if(intval($value->cus_permission)>=5){
						$card_discount_percentage=2.5;
					}
				}

				/*
				if(intval($value->cus_permission)<20){
				$card_discount_percentage=8;
				}*/


				if($card_discount_percentage>0){
					$vat_enable_price_after_discount_decrease=round(($value->vat_enable_price*$card_discount_percentage)/100);
					$vat_decrease=number_format((($vat_enable_price_after_discount_decrease*5)/100),2,'.','');


					$update_sql="
		UPDATE ospos_sales_items SET
		vat_amount=vat_amount-'".$vat_decrease."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$vat_enable_price_after_discount_decrease."',
		cus_permission=cus_permission+'".$card_discount_percentage."'

		WHERE sale_id='".$value->sale_id."' AND stock_id='".$value->stock_id."' AND lot_no='".$value->lot_no."' AND line='".$value->line."' AND item_cost_price='".$value->item_cost_price."'";
					$this->db->query($update_sql);////////////////////////////NEXT

					$sql="SELECT  SUM(payment_amount) AS payment_amoount FROM ospos_sales_payments  WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') AND payment_type='Cash'";
					$query = $this->db->query($sql);

					foreach ($query->result() as $row) {
						$cash_in_hand=$row->payment_amoount;
					}

					$sale_id_modify=$value->sale_id;

					$cash_update=round($vat_enable_price_after_discount_decrease+$vat_decrease);

					if($cash_in_hand>=round($cash_update+129)){


						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
						$query = $this->db->query($sql);

						$payment_sale_id=0;
						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}

						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
							$this->db->query($update_query_permission);////////////////NEXT

						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'".round($cash_update*-1)."')";
							$this->db->query($insert_sql);////NEXT
						}


						$payment_sale_id=0;
						$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
						$query = $this->db->query($sql);

						foreach ($query->result() as $row) {
							$payment_sale_id=$row->sale_id;
							$payment_sale_id_amount=$row->payment_amount;
						}

						if($payment_sale_id){

							$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($vat_enable_price_after_discount_decrease))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
							$this->db->query($update_query_permission);////////////////NEXT
						}else{
							$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($vat_enable_price_after_discount_decrease)."')";
							$this->db->query($insert_sql);////NEXT
						}


						$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($value->vat_enable_price)."',
		'0',
		'".round($cash_update)."',
		'".round($cash_update)."',
		'".round($cash_update)."',
		'0')";
						$this->db->query($query);////NEXT


						$cutomer_id_index=rand(0,count($my_discount_customer));
						$customer_id=$my_discount_customer[$cutomer_id_index];///////////////////TEMP OFF FOR 20%
						///$customer_id="26246";///////////////////TEMP OFF FOR 20%


						if($card_discount_percentage<=3){
							/*$update_sale_sql="UPDATE ospos_sales set is_permission=1
							WHERE sale_id='".$value->sale_id."'";*/

						}else{
							$update_sale_sql="UPDATE ospos_sales set customer_id='".$customer_id."'
		WHERE sale_id='".$value->sale_id."' AND (customer_id IS NULL OR customer_id='0' OR customer_id NOT IN('27530','27531'))";
						}

						$this->db->query($update_sale_sql);

					}
				}
			}


			$payment_sale_id=0;
			$sql="SELECT sale_id,sum(payment_amount) AS payment_amount FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." ) ".$sales_id_consider_for_purchase_discount_str." AND payment_type='Purchase Discount'";
			$query = $this->db->query($sql);

			$payment_sale_id_edit=0;
			$payment_sale_id_amount_edit=0;

			foreach ($query->result() as $row) {
				$payment_sale_id_edit=$row->sale_id;
				$payment_sale_id_amount_edit=$row->payment_amount;
			}

			$pur_discount=round(number_format((($payment_sale_id_amount_edit)*5/100),2,'.',''));
			$pur_discount_vat=number_format(($pur_discount*5)/100,2,'.','');

			$cash_discount=round($pur_discount+$pur_discount_vat);

			if($pur_discount>0){


				$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$payment_sale_id_edit."'");

				$dis_value=array();
				foreach ($query->result() as $row) {
					$dis_value=$row;
				}


				$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount-'".$pur_discount_vat."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$pur_discount."'
		WHERE sale_id='".$dis_value->sale_id."' AND stock_id='".$dis_value->stock_id."' AND lot_no='".$dis_value->lot_no."' AND line='".$dis_value->line."' AND item_cost_price='".$dis_value->item_cost_price."'";

				$this->db->query($update_sql);////////////////////////////NEXT


				$sale_id_modify=$dis_value->sale_id;

				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_discount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".round($cash_discount)."')";
					$this->db->query($insert_sql);////NEXT
				}


				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($pur_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT


				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($pur_discount)."')";
					$this->db->query($insert_sql);////NEXT

				}

				$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($dis_value->vat_enable_price)."',
		'0',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'0')";
				$this->db->query($query);////NEXT

			}


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND (is_permission=0 OR is_permission IS NULL) ".$special_customer_ids_string." )
		".$stock_id_only_other_vat_str." AND discount_percent>0 ORDER BY sale_id ASC ");

			$sales_all_data_additional_all_discount=array();
			foreach ($query->result() as $row) {
				if(intval($row->cus_permission)==0){
					$sales_all_data_additional_all_discount[]=$row;
				}
			}

			foreach ($sales_all_data_additional_all_discount as $dis_key => $dis_value) {

				$pur_discount=round(number_format((($dis_value->total_sale_amount)*5/100),2,'.',''));
				$pur_discount_vat=number_format(($pur_discount*5)/100,2,'.','');

				$cash_discount=round($pur_discount+$pur_discount_vat);
				$pur_discount_line=round($pur_discount);

				$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount-'".$pur_discount_vat."',
		vat_enable_price_after_discount=vat_enable_price_after_discount-'".$pur_discount_line."',
		cus_permission='0'
		WHERE sale_id='".$dis_value->sale_id."' AND stock_id='".$dis_value->stock_id."' AND lot_no='".$dis_value->lot_no."' AND line='".$dis_value->line."' AND item_cost_price='".$dis_value->item_cost_price."'";


				$this->db->query($update_sql);////////////////////////////NEXT

				$sale_id_modify=$dis_value->sale_id;

				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
				$query = $this->db->query($sql);

				$payment_sale_id=0;
				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}

				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_discount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$this->db->query($update_query_permission);////////////////NEXT

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Cash',
		'-".round($cash_discount)."')";
					$this->db->query($insert_sql);////NEXT
				}


				$payment_sale_id=0;
				$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
				$query = $this->db->query($sql);

				foreach ($query->result() as $row) {
					$payment_sale_id=$row->sale_id;
					$payment_sale_id_amount=$row->payment_amount;
				}



				if($payment_sale_id){

					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($pur_discount))."' WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount'";
					$this->db->query($update_query_permission);////////////////NEXT


				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
		VALUES('".$sale_id_modify."',
		'Purchase Discount',
		'".round($pur_discount)."')";
					$this->db->query($insert_sql);////NEXT

				}

				$query = "INSERT INTO ospos_permissions_relations_customer(
		loc_code,
		sale_time,
		sales_id,
		customer_id,
		customer_id_root,
		payment_type,
		cash_amount,
		purchase_discount,
		cash_amount_permission,
		purchase_discount_permission,
		purchase_discount_my,
		is_sync
		)
		VALUES('".LOCATION_CODE."',
		'".date("Y-m-d H:i:s",strtotime($current_date))."',
		'".$sale_id_modify."',
		'0',
		'0',
		'Cash',
		'".round($dis_value->vat_enable_price)."',
		'0',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'".round($cash_discount)."',
		'0')";
				$this->db->query($query);////NEXT

			}


			///$update_sale_sql="UPDATE ospos_sales set is_permission=1 WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."'";

			//$this->db->query($update_sale_sql);

			/*	VAT ADJUST	CONSIDER VAT 7.5%*/

			$total_adjustment=0;
			$query = $this->db->query("SELECT vat_amount AS vat_amount,vat_enable_price_after_discount AS vat_enable_price_after_discount,sale_id,stock_id,lot_no,line,item_cost_price  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ".$stock_id_without_other_vat_str);
			$vat_amount=0;
			$vat_enable_price_after_discount=0;
			foreach ($query->result() as $row) {
				$vat_amount=number_format($row->vat_amount,2,'.','');
				$vat_enable_price_after_discount=round($row->vat_enable_price_after_discount);
				$real_vat=number_format((($vat_enable_price_after_discount)*7.5/100),2,'.','');
				$difference=number_format(($real_vat-$vat_amount),2,'.','');

				if($difference!=0){
					$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount+'".$difference."'
		WHERE sale_id='".$row->sale_id."' AND stock_id='".$row->stock_id."' AND lot_no='".$row->lot_no."' AND line='".$row->line."' AND item_cost_price='".$row->item_cost_price."'";
					$this->db->query($update_sql);////NEXT
					$total_adjustment+=$difference;
				}
			}

			/*	VAT ADJUST	CONSIDER VAT 5%*/
			$query = $this->db->query("SELECT vat_amount AS vat_amount,vat_enable_price_after_discount AS vat_enable_price_after_discount,sale_id,stock_id,lot_no,line,item_cost_price  FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ".$stock_id_only_other_vat_str);

			$vat_amount=0;
			$vat_enable_price_after_discount=0;
			foreach ($query->result() as $row) {
				$vat_amount=number_format($row->vat_amount,2,'.','');
				$vat_enable_price_after_discount=round($row->vat_enable_price_after_discount);
				$real_vat=number_format((($vat_enable_price_after_discount)*5/100),2,'.','');
				$difference=number_format(($real_vat-$vat_amount),2,'.','');
				if($difference!=0){
					$update_sql="
		UPDATE ospos_sales_items
		SET vat_amount=vat_amount+'".$difference."'
		WHERE sale_id='".$row->sale_id."' AND stock_id='".$row->stock_id."' AND lot_no='".$row->lot_no."' AND line='".$row->line."' AND item_cost_price='".$row->item_cost_price."'";
					$this->db->query($update_sql);
					$total_adjustment+=$difference;
				}
			}
		}
		return 1;

	}


	function do_permission_sync_customer($location_code) {


		$this->db->trans_start();

		///user sync//
		$this->db->from('permissions_relations_customer');
		$this->db->where('is_sync',0);
		$employee_data_result= $this->db->get();


		$employee_data=array();
		foreach($employee_data_result->result_array() as $row)
		{
			$employee_data[]=$row;
		}

		$this->db->trans_complete();

		if(count($employee_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){
				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['permission_data'] =$employee_data;
				$api_data_final = json_encode($api_data);


				$result = $client->__soapCall('regularSyncPermissionCustomer', array('data' => $api_data_final));


				$json_data=json_decode($result);

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					if(count($json_data->data)){

						$this->db->trans_start();

						$this->db->set_dbprefix('');
						foreach ($json_data->data as $key => $value) {
							$update_query_permission="UPDATE ospos_permissions_relations_customer SET is_sync=1 WHERE sales_id='".$value."'";
							$this->db->query($update_query_permission);
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
					}
					return $success;
				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}

	function do_regular_sync_stock_moves_break_lastmonths($location_code) {

		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){
			$end_date=date("Y-m-d");
			$start_date= date("Y-m-d", strtotime("-1 month", strtotime($end_date)));

			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data['start_date'] =$start_date;
			$api_data['end_date'] =$end_date;
			$api_data_final = json_encode($api_data);
			$result = $client->__soapCall('regularSyncStockMovesDateWise', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;

			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{
				$json_data=json_decode($result)->data;

				if(trim($json_data)){
					$this->db->trans_start();
					$this->db->set_dbprefix('');
					$this->db->query("DELETE FROM stock_moves WHERE loc_code='".$location_code."' AND DATE_FORMAT(tran_date,'%Y-%m-%d')>='".$start_date."' AND DATE_FORMAT(tran_date,'%Y-%m-%d')<='".$end_date."' AND type!=201");
					$success = $this->db->query($json_data);
					$this->db->set_dbprefix('ospos_');
					$this->db->trans_complete();
					return $success;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}

	function do_regular_sync_stock_moves_break($location_code) {

		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){
			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));
			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data_final = json_encode($api_data);

			$result = $client->__soapCall('regularSyncStockMovesDates', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;
			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{
				$json_data=json_decode($result)->data;


				$start_year = date("Y",strtotime($json_data->min_date));
				$end_year = date("Y",strtotime($json_data->max_date));


				$date_loop=array();

				$loopid=0;
				for($i=$start_year;$i<=$end_year;$i++){

					$date_loop[$loopid]['start_date']=$i."-01-01";
					$date_loop[$loopid]['end_date']=$i."-06-30";
					$loopid++;

					$date_loop[$loopid]['start_date']=$i."-07-01";
					$date_loop[$loopid]['end_date']=$i."-12-31";
					$loopid++;

				}

				$first_loop=1;
				foreach ($date_loop as $key => $value) {
					$api_data = array();
					$api_data['api_user'] = API_USER;
					$api_data['api_password'] = API_PASSWORD;
					$api_data['location_code'] =$location_code;
					$api_data['start_date'] =$value['start_date'];
					$api_data['end_date'] =$value['end_date'];
					$api_data_final = json_encode($api_data);
					$result = $client->__soapCall('regularSyncStockMovesDateWise', array('data' => $api_data_final));

					$error_found=json_decode($result)->error_found;
					$message=json_decode($result)->message;


					if($error_found==1){
						return 4;///Un-authorized Access.
					}else{
						$json_data=json_decode($result)->data;

						if(trim($json_data)){
							$this->db->trans_start();
							$this->db->set_dbprefix('');

							if($first_loop==1){
								$success = $this->db->query("TRUNCATE TABLE stock_moves");
								$first_loop=0;
							}
							$success = $this->db->query($json_data);
							$this->db->set_dbprefix('ospos_');
							$this->db->trans_complete();
						}
					}
				}
				//return $success;

			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}


	function do_regular_sync_stock_moves($location_code) {


		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);



		if($status==0){
			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data_final = json_encode($api_data);

			$result = $client->__soapCall('regularSyncStockMoves', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;
			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{
				$json_data=json_decode($result)->data;

				if(trim($json_data)){

					$this->db->trans_start();
					$this->db->set_dbprefix('');
					$success = $this->db->query("TRUNCATE TABLE stock_moves");
					$success = $this->db->query($json_data);
					$this->db->set_dbprefix('ospos_');
					$this->db->trans_complete();
					return $success;

				}else{
					return true;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}

	function do_regular_sync_customer_add($location_code) {


		$this->db->trans_start();
		///user sync//
		$this->db->from('people');
		$this->db->where(array('is_customer'=>1,'is_sync'=>0));
		$people_data_result= $this->db->get();


		$people_data=array();
		foreach($people_data_result->result_array() as $row)
		{
			$people_data[]=$row;
		}



		$this->db->trans_complete();

		if(count($people_data)){

			$ip = LIVE_SERVER_IP;

			exec("ping -n 1 $ip", $output, $status);



			if($status==0){



				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));



				$api_data = array();

				$api_data['api_user'] = API_USER;

				$api_data['api_password'] = API_PASSWORD;

				$api_data['location_code'] =$location_code;

				$api_data['new_customer'] =$people_data;

				$api_data_final = json_encode($api_data);



				$result = $client->__soapCall('regularSyncCustomerAdd', array('data' => $api_data_final));



				$error_found=json_decode($result)->error_found;

				$message=json_decode($result)->message;




				echo "<pre>==============================================";
				print_r($json_data);
				echo "</pre>";

				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data->added_people_id;

					if(count($json_data)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');

						foreach ($json_data as $p_key => $p_value) {

							$this->db->query("UPDATE ospos_sales SET customer_id='".$p_key."' WHERE customer_id='".$p_value."' AND is_sync=0");
							$success = $this->db->query("DELETE FROM ospos_people WHERE person_id='".$p_value."'");
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						return $success;

					}else{
						return true;
					}
				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}

	function do_regular_sync_customer_card_update($location_code) {

		///////////////////////////////////////COUPON/////////////////////////////////////////////
		$this->db->trans_start();
		///user sync//

		$sql = "SELECT id,state,updated_by FROM pos_ospos_customers WHERE state !=''";

		$query = $this->db->query($sql);

		$people_data=array();

		foreach ($query->result() as $row) {
			$people_data[]=$row;
		}

		$this->db->trans_complete();

		if(count($people_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['new_customer'] =$people_data;
				$api_data_final = json_encode($api_data);

				$result = $client->__soapCall('regularSyncCustomerCardUpdate', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data->added_people_id;
					if(count($json_data)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');
						foreach ($json_data as $p_key => $p_value) {
							$success =$this->db->query("UPDATE pos_ospos_customers SET state='' WHERE id='".$p_value."'");
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						return $success;

					}else{
						return true;
					}
				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}

	function do_regular_sync_customer($location_code) {
		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){

			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;
			$api_data_final = json_encode($api_data);


			$result = $client->__soapCall('regularSyncCustomer', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;

			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{
				$data=json_decode($result)->data;

				if(count($data)){
					$this->db->trans_start();
					foreach ($data->drop_tables as $drop_tables_key => $drop_tables_value) {
						$drop_tables_value_decode=base64_decode($drop_tables_value);

						$this->db->set_dbprefix('');
						$success = $this->db->query($drop_tables_value_decode);
						$this->db->set_dbprefix('ospos_');
					}

					foreach ($data->insert_data as $insert_data_key => $insert_data_value) {
						$insert_data_value_decode=base64_decode($insert_data_value);
						$this->db->set_dbprefix('');
						$success = $this->db->query($insert_data_value_decode);
						$this->db->set_dbprefix('ospos_');
					}
					$this->db->trans_complete();

					return $success;
				}else{
					return true;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}


	function do_regular_sync_local_sale($location_code) {

		$this->db->trans_start();
		$this->db->set_dbprefix('ospos_');

		$this->db->from('sales');
		$this->db->where(array('is_sync'=>0));
		$ospos_sales_result= $this->db->get();

		$ospos_sales_data=array();
		$ospos_sales_items_data=array();
		$ospos_sales_payments_data=array();


		foreach($ospos_sales_result->result_array() as $row){
			$ospos_sales_data[$row['sale_id']]=$row;


			$this->db->from('sales_items');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_items_result= $this->db->get();

			foreach($ospos_sales_items_result->result_array() as $item_row){
				$ospos_sales_items_data[$row['sale_id']][]=$item_row;
			}
			$this->db->from('sales_payments');
			$this->db->where(array('sale_id'=>$row['sale_id']));
			$ospos_sales_payments_result= $this->db->get();

			foreach($ospos_sales_payments_result->result_array() as $payment_row){
				$ospos_sales_payments_data[$row['sale_id']][]=$payment_row;
			}
		}

		$this->db->trans_complete();

		if(count($ospos_sales_data)){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['ospos_sales'] =$ospos_sales_data;
				$api_data['ospos_sales_items'] =$ospos_sales_items_data;
				$api_data['ospos_sales_payments'] =$ospos_sales_payments_data;

				$api_data_final = json_encode($api_data);
				$result = $client->__soapCall('regularSyncSalesAdd', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data;

					if(count($json_data->added_receipt_no)){
						$this->db->trans_start();
						$this->db->set_dbprefix('');

						foreach ($json_data->added_receipt_no as $r_key => $r_value) {

							$update_query="UPDATE ospos_sales SET is_sync=1 WHERE receipt_no='".$r_value."'";
							$success = $this->db->query($update_query);
						}

						if(count($json_data->customer_data_update)){
							foreach ($json_data->customer_data_update as $c_key => $c_value) {

								$update_customer="UPDATE pos_ospos_customers SET point=point+'".$c_value->point."', previous_due='".$c_value->previous_due."' WHERE id=".$c_value->customer_id;
								$success = $this->db->query($update_customer);
							}
						}
						$this->db->set_dbprefix('ospos_');
						$this->db->trans_complete();
						return $success;
					}else{
						return true;
					}
				}


			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}


	function do_regular_sync_global_sale($location_code) {

		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){
			$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));
			$api_data = array();
			$api_data['api_user'] = API_USER;
			$api_data['api_password'] = API_PASSWORD;
			$api_data['location_code'] =$location_code;

			$api_data_final = json_encode($api_data);
			$result = $client->__soapCall('regularSyncGlobalAdd', array('data' => $api_data_final));

			$error_found=json_decode($result)->error_found;
			$message=json_decode($result)->message;
			if($error_found==1){
				return 4;///Un-authorized Access.
			}else{

				$json_data=json_decode($result)->data;

				if(count($json_data->receipt_no)){

					$receipt_no_str="'".implode("','",$json_data->receipt_no)."'";

					$sql = "SELECT receipt_no FROM ospos_sales WHERE receipt_no IN (".$receipt_no_str.")";

					$query = $this->db->query($sql);

					$receipt_no_exist=array();

					foreach ($query->result() as $row) {
						$receipt_no_exist[]=$row->receipt_no;
					}

					foreach ($json_data->ospos_sales as $s_key => $s_value) {

						if(!in_array($s_value->receipt_no,$receipt_no_exist)){

							$this->db->trans_start();
							$this->db->set_dbprefix('');
							$insert_query="INSERT INTO ospos_sales(sale_time,
		customer_id,
		employee_id,
		comment,
		receive_location,
		payment_type,
		location,
		is_sync,
		receipt_no,
		acc_location,
		is_global,
		is_delivered,
		is_sync_golbal_flag,
		bag_big,
		bag_medium,
		bag_small,
		is_global_delivery_sync) VALUES("
							."'".$s_value->sale_time."',"
							."'".$s_value->customer_id."',"
							."'".$s_value->employee_id."',"
							."'".$s_value->comment."',"
							."'".$s_value->receive_location."',"
							."'".$s_value->payment_type."',"
							."'".$s_value->location."',"
							."'1',"
							."'".$s_value->receipt_no."',"
							."'".$s_value->acc_location."',"
							."'".$s_value->is_global."',"
							."'".$s_value->is_delivered."',"
							."'".$s_value->is_sync_golbal_flag."',"
							."'".$s_value->bag_big."',"
							."'".$s_value->bag_medium."',"
							."'".$s_value->bag_small."',"
							."'".$s_value->is_global_delivery_sync."')";

							if($this->db->query($insert_query)){
								$last_inserted_id = $this->db->insert_id();

								foreach ($json_data->ospos_sales_items as $si_key => $si_value) {
									if($si_key==$s_value->sale_id){
										foreach ($si_value as $si_each_key => $si_each_value) {
											$insert_query_item="INSERT INTO ospos_sales_items(sale_id,
		stock_id,
		description,
		lot_no,
		line,
		quantity_purchased,
		item_cost_price,
		item_unit_price,
		discount_percent,
		total_discount,
		total_sale_amount,
		vat_enable_price,
		vat_percentage,

		vat_amount) VALUES("
											."'".$last_inserted_id."',"
											."'".$si_each_value->stock_id."',"
											."'".$si_each_value->description."',"
											."'".$si_each_value->lot_no."',"
											."'".$si_each_value->line."',"
											."'".$si_each_value->quantity_purchased."',"
											."'".$si_each_value->item_cost_price."',"
											."'".$si_each_value->item_unit_price."',"
											."'".$si_each_value->discount_percent."',"
											."'".$si_each_value->total_discount."',"
											."'".$si_each_value->total_sale_amount."',"
											."'".$si_each_value->vat_enable_price."',"
											."'".$si_each_value->vat_percentage."',"
											."'".$si_each_value->vat_amount."')";

											$success=$this->db->query($insert_query_item);
										}
									}
								}
								foreach ($json_data->ospos_sales_payments as $sp_key => $sp_value) {
									if($sp_key==$s_value->sale_id){

										foreach ($sp_value as $sp_each_key => $sp_each_value) {
											$insert_query_payment="INSERT INTO ospos_sales_payments(sale_id,
		payment_type,
		payment_amount,
		bank_id,
		branch_name,
		account_holder_name,
		account_no,
		card_no,
		check_no,
		check_date,
		credit_card_expire_month,
		credit_card_expire_year) VALUES("
											."'".$last_inserted_id."',"
											."'".$sp_each_value->payment_type."',"
											."'".$sp_each_value->payment_amount."',"
											."'".$sp_each_value->bank_id."',"
											."'".$sp_each_value->branch_name."',"
											."'".$sp_each_value->account_holder_name."',"
											."'".$sp_each_value->account_no."',"
											."'".$sp_each_value->card_no."',"
											."'".$sp_each_value->check_no."',"
											."'".$sp_each_value->check_date."',"
											."'".$sp_each_value->credit_card_expire_month."',"
											."'".$sp_each_value->credit_card_expire_year."')";
											$success=$this->db->query($insert_query_payment);
										}
									}
								}
							}
							$this->db->set_dbprefix('ospos_');
							$this->db->trans_complete();
						}
					}
					return $success;
				}else{
					return true;
				}
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}

	function do_regular_sync_global_sale_delivery($location_code) {

		$ip = LIVE_SERVER_IP;
		exec("ping -n 1 $ip", $output, $status);

		if($status==0){



			$this->db->trans_start();
			$this->db->set_dbprefix('ospos_');

			$this->db->from('sales');
			$this->db->where(array('is_global'=>1,'is_delivered'=>1,'is_global_delivery_sync'=>0));
			$ospos_sales_result= $this->db->get();
			foreach($ospos_sales_result->result_array() as $row){
				$ospos_sales_data[$row['receipt_no']]['bag_big']=$row['bag_big'];
				$ospos_sales_data[$row['receipt_no']]['bag_medium']=$row['bag_medium'];
				$ospos_sales_data[$row['receipt_no']]['bag_small']=$row['bag_small'];
			}

			$this->db->trans_complete();

			if(count($ospos_sales_data)){

				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));
				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =$location_code;
				$api_data['data'] =$ospos_sales_data;

				$api_data_final = json_encode($api_data);
				$result = $client->__soapCall('regularSyncGlobalUpdate', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{

					$json_data=json_decode($result)->data;
					if(count($json_data)){
						foreach ($json_data as $key => $value) {
							$this->db->trans_start();
							$this->db->set_dbprefix('');

							$update_flag="UPDATE ospos_sales SET is_global_delivery_sync=1 WHERE receipt_no='".$value."'";
							$success = $this->db->query($update_flag);
							$this->db->set_dbprefix('ospos_');
							$this->db->trans_complete();
						}
						return $success;
					}else{
						return true;
					}
				}
			}else{
				return true;
			}
		}else{
			return 3;///Server not found. please check internet connection.
		}
	}



	function do_sales_adjustment() {

		$current_date=date("Y-m-d");

		$sale_id_all_array=array();
		$sale_id_array=array();

		$query = $this->db->query("SELECT sale_time,sale_id,customer_id,receipt_no FROM ospos_sales AS a WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND is_sync=0 AND acc_location='".LOCATION_CODE."' ORDER BY sale_id ASC ");

		foreach ($query->result() as $row) {
			if(intval($row->customer_id)){
				$sale_id_all_array[$row->sale_id]=$row;
				$sale_id_array[]=$row->sale_id;
			}
		}

		if(count($sale_id_array)){
			$sale_id_all_str="'".implode("','",$sale_id_array)."'";

			$query = $this->db->query("SELECT sale_id,SUM(vat_enable_price) AS vat_enable_price, SUM(vat_enable_price_after_discount) AS vat_enable_price_after_discount FROM ospos_sales_items WHERE sale_id IN(".$sale_id_all_str.") AND discount_percent=0 GROUP BY sale_id ");

			$sale_details_sale_ids=array();
			$total_sale=0;

			foreach ($query->result() as $row) {

				$percentage=floor(($row->vat_enable_price-$row->vat_enable_price_after_discount)*100/$row->vat_enable_price);

				if($percentage>7 AND $percentage<9){
					$sale_details_sale_ids[]=$row->sale_id;
				}
				$total_sale+=$row->vat_enable_price;
			}

			if(count($sale_details_sale_ids)){

				$payment_sale_id_str="'".implode("','",$sale_id_array)."'";

				$query = $this->db->query("SELECT sale_id,payment_type,payment_amount FROM ospos_sales_payments WHERE sale_id IN(".$payment_sale_id_str.")");


				$sale_payment_details=array();
				$total_cash_hand=0;
				$sale_payment_sale_ids=array();
				$sale_payment_sale_ids_cash=array();

				foreach ($query->result() as $row) {
					$sale_payment_details[$row->sale_id][]=$row;
					if($row->payment_type=="Cash"){
						$total_cash_hand+=$row->payment_amount;
					}
				}
				/*	only cash */
				foreach ($sale_details_sale_ids as $key => $value) {

					$payment_array=$sale_payment_details[$value];

					$only_cash=1;
					$cash_amount=0;
					foreach ($payment_array as $pkey => $pvalue) {
						if($pvalue->payment_type!="Purchase Discount"){
							if($pvalue->payment_type!="Cash"){
								$only_cash=0;
							}
						}

						if($pvalue->payment_type=="Cash"){
							$cash_amount=$pvalue->payment_amount;
						}
					}
					if($only_cash==1){
						$sale_payment_sale_ids[]=$value;
						$sale_payment_sale_ids_cash[$value]=$cash_amount;
					}
				}
			}
		}

		$cash_be_consider_percentage=60;//////////////////Will be change
		$minimum_sale_invoice_should_remain=2;//////////////////Will be change




		if($total_sale>=20000){
			$can_be_consider_percentage=30;//////////////////Will be change
		}elseif($total_sale>=15000 AND $total_sale<20000){
			$can_be_consider_percentage=25;//////////////////Will be change
		}elseif($total_sale>=10000 AND $total_sale<15000){
			$can_be_consider_percentage=20;//////////////////Will be change
		}elseif($total_sale>=5000 AND $total_sale<10000){
			$can_be_consider_percentage=10;//////////////////Will be change
		}else{
			$can_be_consider_percentage=0;
		}

		if($can_be_consider_percentage>0){

			$can_be_consider_amount=round(($total_sale*$can_be_consider_percentage)/100);
			$can_be_consider_cash=round(($total_cash_hand*$cash_be_consider_percentage)/100);

			if($can_be_consider_amount>$can_be_consider_cash){
				$can_be_consider_amount=$can_be_consider_cash;
			}

			//////////////////WHICH SALE WILL BE DELETE////////////

			$delete_sale_id=array();

			$total_invoice=count($sale_id_array);

			foreach ($sale_payment_sale_ids as $key => $value) {
				if($can_be_consider_amount>0){
					if($total_invoice>$minimum_sale_invoice_should_remain){
						$can_be_consider_amount-=$sale_payment_sale_ids_cash[$value];
						$delete_sale_id[]=$value;
					}
				}
			}

			/*	Record*/

			if(count($delete_sale_id)){
				foreach ($delete_sale_id as $key => $value) {
					$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id ='".$value."'");
					$sale_details_sale_ids=array();
					$total_sale=0;

					foreach ($query->result() as $row) {

						$insert_sql="INSERT INTO ospos_sales_items_adjustment(
		sale_id,
		stock_id,
		description,
		lot_no,
		line,
		quantity_purchased,
		item_cost_price,
		item_unit_price,
		discount_percent,
		total_discount,
		total_sale_amount,
		vat_enable_price,
		vat_percentage,
		vat_amount,
		vat_enable_price_after_discount,
		loc_code,
		sale_time,
		receipt_no
		)
		VALUES('".$row->sale_id."',
		'".$row->stock_id."',
		'".$row->description."',
		'".$row->lot_no."',
		'".$row->line."',
		'".$row->quantity_purchased."',
		'".$row->item_cost_price."',
		'".$row->item_unit_price."',
		'".$row->discount_percent."',
		'".$row->total_discount."',
		'".$row->total_sale_amount."',
		'".$row->vat_enable_price."',
		'".$row->vat_percentage."',
		'".$row->vat_amount."',
		'".$row->vat_enable_price_after_discount."',
		'".LOCATION_CODE."',
		'".$sale_id_all_array[$row->sale_id]->sale_time."',
		'".$sale_id_all_array[$row->sale_id]->receipt_no."')";

						$this->db->query($insert_sql);
					}

					///Delete stock moves////
					$this->db->query("DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$sale_id_all_array[$value]->receipt_no."'");

					///Delete payment////
					$this->db->query("DELETE FROM ospos_sales_payments WHERE sale_id='".$value."'");

					///Delete sale_items////
					$this->db->query("DELETE FROM ospos_sales_items WHERE sale_id='".$value."'");

					///Delete sale////
					$this->db->query("DELETE FROM ospos_sales WHERE sale_id='".$value."' AND receipt_no='".$sale_id_all_array[$value]->receipt_no."' AND acc_location='".LOCATION_CODE."'");
				}
			}
		}
		return 1;
	}

	function do_sales_adjustment_sync() {

		$this->db->trans_start();
		$this->db->set_dbprefix('ospos_');

		$this->db->from('sales_items_adjustment');
		$this->db->where(array('is_sync'=>0));
		$ospos_sales_result= $this->db->get();

		$ospos_sales_items_data=array();

		foreach($ospos_sales_result->result_array() as $row){
			$ospos_sales_items_data[]=$row;
		}

		$this->db->trans_complete();

		if(count($ospos_sales_items_data)){
			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);


			if($status==0){


				$client = new SoapClient(LIVE_SERVER_PATH.'/services/services.php?wsdl', array('trace' => 1, 'exceptions' => 0));

				$api_data = array();
				$api_data['api_user'] = API_USER;
				$api_data['api_password'] = API_PASSWORD;
				$api_data['location_code'] =LOCATION_CODE;
				$api_data['ospos_sales_items_adjustment'] =$ospos_sales_items_data;

				$api_data_final = json_encode($api_data);
				$result = $client->__soapCall('regularSyncSalesItemAdjustment', array('data' => $api_data_final));

				$error_found=json_decode($result)->error_found;
				$message=json_decode($result)->message;
				if($error_found==1){
					return 4;///Un-authorized Access.
				}else{
					$json_data=json_decode($result)->data;


					if(count($json_data)){
						foreach ($json_data as $key => $value) {
							$update_query="UPDATE ospos_sales_items_adjustment SET is_sync=1 WHERE sale_id='".$key."'";
							$success = $this->db->query($update_query);
						}
						return $success;
					}else{
						return true;
					}

				}

			}else{
				return 3;///Server not found. please check internet connection.
			}
		}else{
			return true;
		}
	}


	function do_invoice_update($invoice){

		$query = $this->db->query("SELECT * FROM ospos_sales WHERE receipt_no='".$invoice."' AND DATE_FORMAT(sale_time,'%Y-%m-%d')='".date("Y-m-d")."' AND is_sync=0");

		$sale_id=0;
		$sale_time="";
		$receipt_no="";

		foreach ($query->result() as $row) {

			$sale_id=$row->sale_id;
			$sale_time=$row->sale_time;
			$receipt_no=$row->receipt_no;
		}

		$query = $this->db->query("SELECT * FROM ospos_sales_payments WHERE sale_id='".$sale_id."' AND payment_type!='Cash' AND payment_type!='Purchase Discount'");


		$has_without_cash=0;

		foreach ($query->result() as $row) {
			$has_without_cash=1;
		}

		if($has_without_cash==1){

			echo "<pre>";
			print_r("<font style='color:#FF0000; font-weight:bold;font-size:18px;'>Invoice payment mode must be cash.</font>");
			echo "</pre>";

			return 0;
		}
		if($sale_id==0){

			echo "<pre>";
			print_r("<font style='color:#FF0000; font-weight:bold;font-size:18px;'>Invoice already sync OR It is not today's invoice</font>");
			echo "</pre>";

			return 0;
		}

		if(intval($sale_id)AND intval($has_without_cash)==0){


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$sale_id."'");
			$sale_details_sale_ids=array();
			$total_sale=0;

			$details_sales=array();
			$total_sale_amount=0;
			$total_vatenable_amount=0;

			foreach ($query->result() as $row) {

				$details_sales[]=$row;

				$total_sale_amount+=$row->vat_enable_price;
				$total_vatenable_amount+=$row->vat_enable_price_after_discount;

			}

			$percentage=ceil((($total_sale_amount-$total_vatenable_amount)/$total_sale_amount)*100);

			$our_total=0;

			if($percentage<8){

				foreach ($details_sales as $details_key => $details_value) {


					$new_vat_enable_price_after_discount=$details_value->vat_enable_price-round(($details_value->vat_enable_price*8)/100);
					$new_vat_amount= number_format(($new_vat_enable_price_after_discount*$details_value->vat_percentage)/100, 2, '.', '');

					$our_total+=($details_value->vat_enable_price_after_discount-$new_vat_enable_price_after_discount)+($details_value->vat_amount-$new_vat_amount);

					/* Update items details*/

					$update_sql="UPDATE ospos_sales_items SET vat_amount='".number_format($new_vat_amount, 2, '.', '')."',vat_enable_price_after_discount='".number_format($new_vat_enable_price_after_discount, 2, '.', '')."'
                    WHERE sale_id='".$details_value->sale_id."' AND
                    stock_id='".$details_value->stock_id."' AND
                    lot_no='".$details_value->lot_no."' AND
                    line='".$details_value->line."' AND
                    quantity_purchased='".$details_value->quantity_purchased."' AND
                    item_unit_price='".$details_value->item_unit_price."'";
					$this->db->query($update_sql);

				}
				if($our_total>0){
					$query = $this->db->query("
					INSERT INTO ospos_permissions_relations_customer(
					loc_code,
					sale_time,
					sales_id,
					customer_id,
					customer_id_root,
					payment_type,
					cash_amount,
					purchase_discount,
					cash_amount_permission,
					purchase_discount_permission,
					purchase_discount_my,
					is_sync
					)
					VALUES('".LOCATION_CODE."',
					'".date("Y-m-d H:i:s")."',
					'".$sale_id."',
					'0',
					'0',
					'Cash',
					'".$total_sale_amount."',
					'0',
					'".round($our_total)."',
					'".round($our_total)."',
					'".round($our_total)."',
					'0')");

				}
			}


			$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$sale_id."'");
			$sale_details_sale_ids=array();
			$total_sale=0;

			foreach ($query->result() as $row) {



				$insert_sql="INSERT INTO ospos_sales_items_adjustment(
						sale_id,
						stock_id,
						description,
						lot_no,
						line,
						quantity_purchased,
						item_cost_price,
						item_unit_price,
						discount_percent,
						total_discount,
						total_sale_amount,
						vat_enable_price,
						vat_percentage,
						vat_amount,
						vat_enable_price_after_discount,
						loc_code,
						sale_time,
						receipt_no
					)
					VALUES('".$row->sale_id."',
					'".$row->stock_id."',
					'".$row->description."',
					'".$row->lot_no."',
					'".$row->line."',
					'".$row->quantity_purchased."',
					'".$row->item_cost_price."',
					'".$row->item_unit_price."',
					'".$row->discount_percent."',
					'".$row->total_discount."',
					'".$row->total_sale_amount."',
					'".$row->vat_enable_price."',
					'".$row->vat_percentage."',
					'".$row->vat_amount."',
					'".$row->vat_enable_price_after_discount."',
					'".LOCATION_CODE."',
					'".$sale_time."',
					'".$receipt_no."')";

				$this->db->query($insert_sql);

			}

			///Delete stock moves////
			$this->db->query("DELETE FROM stock_moves WHERE loc_code='".LOCATION_CODE."' AND reference='".$receipt_no."'");

			///Delete payment////
			$this->db->query("DELETE FROM ospos_sales_payments WHERE sale_id='".$sale_id."'");

			///Delete sale_items////
			$this->db->query("DELETE FROM ospos_sales_items WHERE sale_id='".$sale_id."'");

			///Delete sale////
			$this->db->query("DELETE FROM ospos_sales WHERE sale_id='".$sale_id."' AND receipt_no='".$receipt_no."' AND acc_location='".LOCATION_CODE."'");
			return 1;

		}else{
			return 0;
		}
	}
	function runtime_file_upload_for_monitoring(){


		$unique_date=array();
		$query_date = $this->db->query("SELECT DATE_FORMAT(sale_time,'%Y-%m-%d') AS sale_date_unique,sale_time FROM ospos_sales WHERE is_sync=0 AND acc_location='".LOCATION_CODE."' ORDER BY sale_id DESC ");
		foreach ($query_date->result() as $row_date) {

			if(!array_key_exists($row_date->sale_date_unique,$unique_date)){
				$unique_date[$row_date->sale_date_unique]=$row_date->sale_time;
			}
		}

		if(count($unique_date)){

			foreach ($unique_date as $date_key => $date_value) {
				/////////////////////////////Monitor////////////////////////////////////////////
				$data_execute=array();
				$data_execute['ext']=$date_value;
				$data_execute['loc']=LOCATION_CODE;

				$data_execute['rsale']=0;
				$data_execute['rpd']=0;

				$data_execute['gcsale']=0;
				$data_execute['gcpd']=0;

				$data_execute['rcrd']=0;
				$data_execute['gccrd']=0;

				$data_execute['pmrp']=0;
				$data_execute['pcrd']=0;
				$data_execute['pclr']=0;

				$data_execute['rpay']['Cash']=0;
				$data_execute['gcpay']['Cash']=0;

				$current_date=date("Y-m-d",strtotime($date_key));

				$query_count = $this->db->query("SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."'");
				$consider_sale_id_monitor=array();
				foreach ($query_count->result() as $row_count) {
					$consider_sale_id_monitor[]=$row_count->sale_id;
				}

				if(count($consider_sale_id_monitor)){
					$consider_sale_id_monitor_string="'".implode("','",$consider_sale_id_monitor)."'";

					$query = $this->db->query("SELECT SUM(vat_enable_price) AS vat_enable_price, SUM(total_discount) AS total_discount
		FROM ospos_sales_items_reprint WHERE sale_id IN (".$consider_sale_id_monitor_string.")");

					foreach ($query->result() as $row) {
						$data_execute['rsale']=$row->vat_enable_price;
						$data_execute['rpd']=$row->total_discount;
					}

					$query = $this->db->query("SELECT SUM(vat_enable_price) AS vat_enable_price, SUM(total_discount) AS total_discount
		FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_monitor_string.")");

					foreach ($query->result() as $row) {
						$data_execute['gcsale']=$row->vat_enable_price;
						$data_execute['gcpd']=$row->total_discount;
					}

					$sql_payment="SELECT  payment_type,SUM(payment_amount) AS payment_amount FROM ospos_sales_payments_reprint  WHERE sale_id IN (".$consider_sale_id_monitor_string.") GROUP BY payment_type";
					$query_payment = $this->db->query($sql_payment);
					foreach ($query_payment->result() as $row_payment) {

						if($row_payment->payment_type=="Purchase Discount"){
							$data_execute['rcrd']=$row_payment->payment_amount;
						}else{
							$data_execute['rpay'][$row_payment->payment_type]=$row_payment->payment_amount;

						}
					}

					$sql_payment="SELECT  payment_type,SUM(payment_amount) AS payment_amount FROM ospos_sales_payments  WHERE sale_id IN (".$consider_sale_id_monitor_string.") GROUP BY payment_type";
					$query_payment = $this->db->query($sql_payment);
					foreach ($query_payment->result() as $row_payment) {
						if($row_payment->payment_type=="Purchase Discount"){
							$data_execute['gccrd']=$row_payment->payment_amount;
						}else{
							$data_execute['gcpay'][$row_payment->payment_type]=$row_payment->payment_amount;
						}
					}

					$query = $this->db->query("SELECT payment_type, SUM(purchase_discount_my) AS purchase_discount_my,purchase_discount
		FROM ospos_permissions_relations_customer 
		WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' GROUP BY payment_type,purchase_discount ");

					foreach ($query->result() as $row) {
						if($row->payment_type=="MRP"){
							$data_execute['pmrp']+=$row->purchase_discount_my;
							if($row->purchase_discount>0){
								$data_execute['pdmr']+=$row->purchase_discount_my;
							}
						}else{
							$data_execute['pcrd']+=$row->purchase_discount_my;
						}
					}

					$query = $this->db->query("SELECT SUM(clr_amount) AS clr_amount
		FROM ospos_clr_locwise 
		WHERE DATE_FORMAT(sales_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."'");

					foreach ($query->result() as $row) {
						$data_execute['pclr']+=$row->clr_amount;
					}
				}
				$data_execute_serialze=base64_encode(serialize($data_execute));
				//$file_content_live=file_get_contents("http://localhost/shamogree/admin/monitoring_mrp/monitoring_mrp.php?data=".$data_execute_serialze);
				$file_content_live=file_get_contents("https://pharma.santisirmdc.org/admin/monitoring_mrp/monitoring_mrp.php?data=".$data_execute_serialze);

			}
		}


		return true;
	}

	function runtime_file_upload_for_monitoring_gcpaysync(){
		$unique_date=array();
		$query_date = $this->db->query("SELECT DATE_FORMAT(sale_time,'%Y-%m-%d') AS sale_date_unique,sale_time FROM ospos_sales WHERE is_sync=0 AND acc_location='".LOCATION_CODE."' ORDER BY sale_id DESC ");
		foreach ($query_date->result() as $row_date) {

			if(!array_key_exists($row_date->sale_date_unique,$unique_date)){
				$unique_date[$row_date->sale_date_unique]=$row_date->sale_time;
			}
		}

		$unique_date[date("Y-m-d")]=date("Y-m-d");
		$one_day_ago=date('Y-m-d', strtotime(date("Y-m-d") . ' -1 day'));
		$two_day_ago=date('Y-m-d', strtotime(date("Y-m-d") . ' -2 days'));

		$unique_date[$one_day_ago]=$one_day_ago;
		$unique_date[$two_day_ago]=$two_day_ago;


		if(count($unique_date)){

			foreach ($unique_date as $date_key => $date_value) {
				$data_execute=array();
				$data_execute['ext']=$date_value;
				$data_execute['loc']=LOCATION_CODE;
				$data_execute_serialze_return=base64_encode(serialize($data_execute));

				$previous_file_data=file_get_contents("https://pharma.santisirmdc.org/admin/monitoring_mrp/monitoring_mrp_return.php?data=".$data_execute_serialze_return);

				$file_data=unserialize($previous_file_data);


				$current_date=date("Y-m-d",strtotime($date_key));

				$query_count = $this->db->query("SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."'");
				$consider_sale_id_monitor=array();
				foreach ($query_count->result() as $row_count) {
					$consider_sale_id_monitor[]=$row_count->sale_id;
				}

				if(count($consider_sale_id_monitor)){
					$consider_sale_id_monitor_string="'".implode("','",$consider_sale_id_monitor)."'";
					$sql_payment="SELECT  payment_type,SUM(payment_amount) AS payment_amount FROM ospos_sales_payments  WHERE sale_id IN (".$consider_sale_id_monitor_string.") GROUP BY payment_type";
					$query_payment = $this->db->query($sql_payment);
					foreach ($query_payment->result() as $row_payment) {
						$file_data['gcpaysync'][$row_payment->payment_type]=$row_payment->payment_amount;
					}
				}
				$data_execute_serialze=base64_encode(serialize($file_data));
				//$file_content_live=file_get_contents("http://localhost/shamogree/admin/monitoring_mrp/monitoring_mrp.php?data=".$data_execute_serialze);
				$file_content_live=file_get_contents("https://pharma.santisirmdc.org/admin/monitoring_mrp/monitoring_mrp.php?data=".$data_execute_serialze);
			}
		}
		return true;


	}



	function real_vat_enable_price_after_discount($current_date){

		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}
		$real_vat_enable_price_after_discount=0;
		$real_vat_amount=0;

		$query = $this->db->query("SELECT SUM(vat_enable_price_after_discount) AS vat_enable_price_after_discount,SUM(vat_amount) AS vat_amount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') ");

		foreach ($query->result() as $row) {

			$real_vat_enable_price_after_discount+=$row->vat_enable_price_after_discount;
			$real_vat_amount+=number_format($row->vat_amount,2,'.','');
		}

		$return_array['vat_enable_price_after_discount']=$real_vat_enable_price_after_discount;
		$return_array['vat_amount']=$real_vat_amount;
		return $return_array;
	}

	function adjust_special_customer_for_bogo2022($current_date,$percentage){

		$current_directory = getcwd();

		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');
		}else{
			$config_mrp['CORE_CUSTOMER_CARD_DISCOUNT_ACTIVE']=0;
		}

		if($config_mrp['CORE_CUSTOMER_CARD_DISCOUNT_ACTIVE']==1){

			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}


			$total_card_discount_permit=0;
			$all_sales_id=array();

			$query_customer = $this->db->query("SELECT id,special_percentage FROM pos_ospos_customers WHERE is_special=1");//////////////UPDATE 2022-09-09
			$special_customer_ids_array=array();
			$special_customer_ids_percentage_array=array();

			foreach ($query_customer->result() as $row_special) {
				$special_customer_ids_array[]=$row_special->id;
				$special_customer_ids_percentage_array[$row_special->id]=$row_special->special_percentage;
			}
			$special_customer_ids_string="";
			$only_special_customer_ids_string="";

			if(count($special_customer_ids_array)){
				$special_customer_ids_string_temp="'".implode("','",$special_customer_ids_array)."'";
				$special_customer_ids_string=" AND (customer_id NOT IN(".$special_customer_ids_string_temp.") OR customer_id=0 OR customer_id IS NULL )";
				$only_special_customer_ids_string=" AND customer_id IN(".$special_customer_ids_string_temp.")";

			}


			/////////////////////////////SPECIAL SALES////////////////////////////////////////

			$special_sale_ids=array();
			$special_sale_info=array();
			$total_special_sale=0;
			$query = $this->db->query("SELECT sale_id,SUM(vat_enable_price) AS total_sale FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' ".$only_special_customer_ids_string.") GROUP BY sale_id");
			foreach ($query->result() as $row) {
				$special_sale_info[$row->sale_id]=$row->total_sale;/////////////////////NEXT CONSIDER
				$special_sale_ids[]=$row->sale_id;
				$all_sales_id[]=$row->sale_id;
				$sale_id_modify=$row->sale_id;
				$total_special_sale+=$row->total_sale;
			}

			if(count($special_sale_ids)){
				$special_sales_ids_string="'".implode("','",$special_sale_ids)."'";

				$query_special_dis = $this->db->query("SELECT a.sale_id,b.special_percentage FROM ospos_sales AS a
									   LEFT JOIN pos_ospos_customers AS b ON a.customer_id=b.id
									   WHERE sale_id IN(".$special_sales_ids_string.")");

				foreach ($query_special_dis->result() as $row_special_dis){

					if($row_special_dis->special_percentage<15){
						$row_special_dis->special_percentage=40;
					}
					$permission=round(($special_sale_info[$row_special_dis->sale_id]*$row_special_dis->special_percentage)/100);
					//$permission_vat=number_format((($permission*3.75)/100),2,'.','');
					$permission_vat=0;
					$total_card_discount_permit+=round($permission+$permission_vat);
				}
			}
			/////////////////////////NON Special Sale AMOUNT/////////////////////////////////

			$query = $this->db->query("SELECT sale_id,vat_enable_price AS total_sale,discount_percent,total_discount FROM ospos_sales_items WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' ".$special_customer_ids_string.") ");

			foreach ($query->result() as $row) {
				$total_sales+=$row->total_sale;/////////////////////NEXT CONSIDER
				$sale_id_modify=$row->sale_id;
				$sale_ids[]=$row->sale_id;
				$all_sales_id[$row->sale_id]=$row->sale_id;
			}

			if(round($total_sales)>0){
				$permission=round(($total_sales*8)/100);
				$permission_vat=number_format((($permission*7.5)/100),2,'.','');
				$total_card_discount_permit+=round($permission+$permission_vat);
				$total_card_discount_permit+=$permission+$permission_vat;
			}


			$database_product_discount=0;

			if(count($all_sales_id)){
				$all_sales_id_string="'".implode("','",$all_sales_id)."'";
				$sql_product_discount="SELECT SUM(payment_amount) AS payment_amount
							   FROM ospos_sales_payments 
							   WHERE sale_id IN(".$all_sales_id_string.") AND payment_type='Purchase Discount'";

				$query_product_discount = $this->db->query($sql_product_discount);

				foreach ($query_product_discount->result() as $row_product_discount) {
					$database_product_discount+=$row_product_discount->payment_amount;
				}
			}


			$current_permission_cash=0;
			$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_cash FROM ospos_permissions_relations_customer
						WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' AND payment_type!='MRP'");

			foreach ($query->result() as $row) {
				$current_permission_cash=$row->total_cash;
				$current_permission_cash=round(($current_permission_cash*100)/107.5);
			}
			$adjusted_product_discount=0;

			if(abs($database_product_discount-$total_card_discount_permit)>=1){
				$adjusted_product_discount=$total_card_discount_permit-$database_product_discount;
			}

			if($adjusted_product_discount<0){
				if(abs($adjusted_product_discount)>$current_permission_cash){
					$adjusted_product_discount=$current_permission_cash*-1;
				}
			}
			if($adjusted_product_discount!=0){
				$current_cash=0;
				$query = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (SELECT sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."') AND  payment_type='CASH'");
				foreach ($query->result() as $row) {
					$current_cash=$row->total_cash;/////////////////////NEXT CONSIDER
				}

				$add_delete_vat_enable_price_after_discount=intval($adjusted_product_discount);
				$add_delete_vat_amount=number_format(($adjusted_product_discount*7.5)/100,2,'.','');

				$cash_update=number_format(round($add_delete_vat_enable_price_after_discount+$add_delete_vat_amount),2,'.','');



				if($cash_update!=0){
					if($current_cash-$cash_update>=538){

						$sql="SELECT *
FROM ospos_sales_items AS s
WHERE  s.sale_id IN(SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."' AND (is_sync=0 OR is_sync IS NULL)) AND quantity_purchased>0 LIMIT 1 ";

						$query_modified_info = $this->db->query($sql);

						$sale_id_modify=0;
						foreach ($query_modified_info->result() as $row_modified) {
							$modify_item_info=$row_modified;
							$sale_id_modify=$row_modified->sale_id;
						}
						if(intval($sale_id_modify)){

							$update_sql_force="UPDATE ospos_sales_items SET
			vat_enable_price_after_discount='".($modify_item_info->vat_enable_price_after_discount-$add_delete_vat_enable_price_after_discount)."',
			vat_amount='".($modify_item_info->vat_amount-$add_delete_vat_amount)."'
			WHERE sale_id='".$modify_item_info->sale_id."' AND stock_id='".$modify_item_info->stock_id."' 
			AND lot_no='".$modify_item_info->lot_no."' AND line='".$modify_item_info->line."' 
			AND item_cost_price='".$modify_item_info->item_cost_price."' AND quantity_purchased='".$modify_item_info->quantity_purchased."' LIMIT 1";

							$this->db->query($update_sql_force);//////////////////NEXT



							$payment_sale_id=0;
							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id='".$sale_id_modify."' AND payment_type='Purchase Discount' LIMIT 1";
							$query = $this->db->query($sql);

							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}


							if(intval($payment_sale_id)){
								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($add_delete_vat_enable_price_after_discount))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
								$this->db->query($update_query_permission);////////////////NEXT
							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Purchase Discount',
						'".round($add_delete_vat_enable_price_after_discount)."')";
								$this->db->query($insert_sql);////NEXT
							}

							$sql="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".$sale_id_modify."' AND payment_type='Cash' LIMIT 1";
							$query = $this->db->query($sql);

							$payment_sale_id=0;
							foreach ($query->result() as $row) {
								$payment_sale_id=$row->sale_id;
								$payment_sale_id_amount=$row->payment_amount;
							}
							if(intval($payment_sale_id)){
								$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($cash_update))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
								$this->db->query($update_query_permission);////////////////NEXT

							}else{
								$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
						VALUES('".$sale_id_modify."',
						'Cash',
						'-".round($cash_update)."')";
								$this->db->query($insert_sql);////NEXT
							}

							$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$sale_id_modify."',
						'0',
						'0',
						'Cash',
						'".round($cash_update)."',
						'0',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'".round($cash_update)."',
						'0')";
							$this->db->query($query);////NEXT

						}
					}
				}
			}

		}
		return true;
	}

	function adjust_special_customer_for_40_precentage_without_lot_change($current_date){

		/////////////////////QC PASS///////////////////////
		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}

		/////////////////SPECIAL DISCOUNT//////////////////////
		$special_customer_id=array();
		$query_special = $this->db->query("SELECT id FROM pos_ospos_customers
					WHERE is_special=1 AND special_percentage>0 ");

		foreach ($query_special->result() as $row_special) {
			$special_customer_id[]=$row_special->id;
		}

		$consider_sale_id=array();
		$consider_sale_id_information=array();

		$default_sales_information=array();
		$default_sales_information_max_line=1;

		/////////////////SPECIAL DISCOUNT//////////////////////
		$query_all_sale = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' 
					AND a.acc_location='".LOCATION_CODE."' AND a.payment_type!='' 
					AND (a.is_sync = 0 OR a.is_sync IS NULL)");


		foreach ($query_all_sale->result() as $row_all) {

			if(intval($row_all->customer_id)!=0){
				if (!in_array(intval($row_all->customer_id), $special_customer_id)){
					$consider_sale_id[]=$row_all->sale_id;
					$consider_sale_id_information[$row_all->sale_id]=$row_all;
				}else{
					/////////////////////////DEFAULT 40 Percentage Customer Sales ID///////////////////

					if(intval($row_all->customer_id)==31451){
						if(count($default_sales_information)==0){
							$query_default_items = $this->db->query("SELECT MAX(line) As max_line FROM ospos_sales_items WHERE sale_id='".$row_all->sale_id."'");
							foreach ($query_default_items->result() as $row_default_line) {
								$default_sales_information_max_line=intval($row_default_line->max_line)+1;
								$default_sales_information=$row_all;
							}
						}
					}
				}
			}else{
				$consider_sale_id[]=$row_all->sale_id;
				$consider_sale_id_information[$row_all->sale_id]=$row_all;
			}
		}




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

		$description_wise_minimum=array();
		$category_wise_minimum=array();
		$stock_id_filter=array();

		$description_wise_minimum['Lungi']=200000;

		$description_wise_minimum['Maxi']=200000;

		$description_wise_minimum['Gamcha Fabric']=20000;
		$description_wise_minimum['Gamcha']=200000;

		$description_wise_minimum['Boy Trowzer']=200000;
		$description_wise_minimum['Female Trowzer']=200000;
		$description_wise_minimum['Male Trowzer']=200000;

		$description_wise_minimum['Male Three Quarter']=200000;

		$description_wise_minimum['Boy Sleeping Dress']=200000;
		$description_wise_minimum['Girl Sleeping Dress']=200000;
		$description_wise_minimum['Male Full Sleeping Dress']=200000;
		$description_wise_minimum['Male Sleeping Dress']=200000;

		$description_wise_minimum['Aligar Pazama']=200000;
		$description_wise_minimum['Boy Aligar Pazama']=200000;
		$description_wise_minimum['Boy Pazama']=200000;
		$description_wise_minimum['Male Pazama']=200000;

		$description_wise_minimum['Girl&#039;s Tank Tops']=200000;
		$description_wise_minimum['Men&#039;s Tank Tops']=200000;

		$description_wise_minimum['Men&#039;s Under Wear']=200000;


		$description_wise_minimum['Bed Sheet']=200000;
		$description_wise_minimum['Bed Sheet Aplic']=200000;
		$description_wise_minimum['Bed Sheet Block Print']=200000;
		$description_wise_minimum['Bed Sheet Dubble']=200000;
		$description_wise_minimum['Bed Sheet Dubble-Manufactured']=200000;
		$description_wise_minimum['Bed Sheet Nokshi']=200000;
		$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=200000;
		$description_wise_minimum['Bed Sheet Semi-Dubble']=200000;
		$description_wise_minimum['Bed Sheet Single']=200000;
		$description_wise_minimum['Bed Sheet Single-Manufactured']=200000;

		$description_wise_minimum['Baby Nokshi Katha']=200000;
		$description_wise_minimum['Nokshi Baby Katha']=200000;
		$description_wise_minimum['Nokshi Katha']=200000;

		$category_wise_minimum['56']=200000;////Handicraft


		if(count($description_wise_minimum)){
			$clause_string="";
			$where_string_description=array();
			foreach ($description_wise_minimum as $clause_key => $clause_value) {
				$clause_string.=" WHEN description = '".$clause_key."' THEN ".$clause_value." ";
				$where_string_description[]=$clause_key;
			}
			$where_string_description_string="'".implode("','",$where_string_description)."'";

			$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where description IN(".$where_string_description_string.")");


			foreach ($query_filter->result() as $row_filter) {
				if(intval($row_filter->price)){
					$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
				}
			}
		}

		if(count($category_wise_minimum)){
			$clause_string="";
			$where_string_description=array();
			foreach ($category_wise_minimum as $clause_key => $clause_value) {
				$clause_string.=" WHEN category_id = '".$clause_key."' THEN ".$clause_value." ";
				$where_string_description[]=$clause_key;
			}
			$where_string_description_string="'".implode("','",$where_string_description)."'";

			$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where category_id IN(".$where_string_description_string.")");


			foreach ($query_filter->result() as $row_filter) {
				if(intval($row_filter->price)){
					$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
				}
			}

		}

		$sharee_array[]="02927013";
		$sharee_array[]="02928014";
		$sharee_array[]="02929015";
		$sharee_array[]="02930016";
		$sharee_array[]="02931017";
		$sharee_array[]="02939001";
		$sharee_array[]="02939002";
		$sharee_array[]="02939003";
		$sharee_array[]="02939006";
		$sharee_array[]="02939007";
		$sharee_array[]="02939008";
		$sharee_array[]="02939009";
		$sharee_array[]="02939010";
		$sharee_array[]="02939011";
		$sharee_array[]="02939012";
		$sharee_array[]="02939018";
		$sharee_array[]="02939019";
		$sharee_array[]="02939020";
		$sharee_array[]="02939021";
		$sharee_array[]="05939002";
		$sharee_array[]="06139022";
		$sharee_array[]="06739011";


		$consider_sale_id_string="";
		$consider_sale_id_string="''";
		if(count($consider_sale_id)){



			$current_cash=0;
			$query_cash = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments
							WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') 
							AND  payment_type='CASH'");

			foreach ($query_cash->result() as $row_cash) {
				$current_cash=$row_cash->total_cash;/////////////////////NEXT CONSIDER
			}



			$total_sale_amount_for_consider=0;

			$purchase_discount_deduct=0;
			$purchase_discount_vat_deduct=0;
			$purchase_discount_cash_deduct=0;
			$sales_items_previous_vatable_added=0;
			$sales_items_previous_vatable_vat_added=0;

			$execute_array=array();

			$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";

			$query = $this->db->query("SELECT * FROM ospos_sales_items
			WHERE sale_id IN (".$consider_sale_id_string.") 
			AND quantity_purchased>0 AND lot_no<'210700'
			ORDER BY item_cost_price DESC,vat_enable_price_after_discount DESC, quantity_purchased ASC ");

			$first_row=1;
			foreach ($query->result() as $row) {
				///////////////////////////////////STOCK MOVES/////////////////////
				$can_consider=0;
				if(!array_key_exists ( $row->stock_id, $stock_id_filter)){
					if(in_array($row->stock_id,$sharee_array)){
						if($row->lot_no<200000){
							$can_consider=1;
						}
					}else{
						$can_consider=1;
					}
				}
				if($can_consider==1){
					$consider_discount_percenege=40;///////////////////////////////////////////FLAT_40P
					if(intval($consider_sale_id_information[$row->sale_id]->customer_id)!=0){
						$consider_discount_percenege=($consider_discount_percenege-8)+(($consider_discount_percenege-8)*7.5/100);
					}
					$sale_price=$row->item_cost_price*$row->quantity_purchased;
					$purchase_discount_sale=round(($sale_price*$consider_discount_percenege)/100);
					$purchase_discount_sale_vat=number_format(($purchase_discount_sale*$row->vat_percentage/100), 2, '.', '');

					$total_sale_amount_for_consider+=round($sale_price);
					$purchase_discount_deduct+=($purchase_discount_sale);
					$purchase_discount_vat_deduct+=$purchase_discount_sale_vat;
					$purchase_discount_cash_deduct+=($purchase_discount_sale+$purchase_discount_sale_vat);

					if($current_cash>538){
						$current_cash-=round(($purchase_discount_sale+$purchase_discount_sale_vat));

						if($first_row==1){

							///////////////////////////CHECK DEFAULT SALE INFO//////////////
							if(count($default_sales_information)==0){
								$insert_query="
								INSERT INTO ospos_sales
						            (sale_time,
						             customer_id,
						             employee_id,
						             comment,
						             receive_location,
						             payment_type,
						             location,
						             is_sync,
						             receipt_no,
						             acc_location,
						             is_global,
						             is_delivered,
						             is_sync_golbal_flag,
						             bag_big,
						             bag_medium,
						             bag_small,
						             is_global_delivery_sync)

						             VALUES ('".date("Y-m-d H:i:s")."',
									        '31451',
									        '1',
									        '0',
									        NULL,
									        '',
									        '".LOCATION_CODE."',
									        '0',
									        '".LOCATION_CODE.date("ymdHis")."',
									        '".LOCATION_CODE."',
									        '0',
									        '0',
									        '0',
									        NULL,
									        NULL,
									        NULL,
									        '0')";

								$this->db->query($insert_query); /////////////////////NEXT


								$query_default_sale_dummy = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' 
					AND a.acc_location='".LOCATION_CODE."' AND customer_id='31451' 
					AND (a.is_sync = 0 OR a.is_sync IS NULL) LIMIT 1");

								foreach ($query_default_sale_dummy->result() as $row_default_dummy) {
									if(intval($row_default_dummy->customer_id)==31451){
										$default_sales_information=$row_default_dummy;
										$default_sales_information_max_line=1;
									}
								}
								$first_row=0;
							}

						}
						if(count($default_sales_information)){
							$query="UPDATE ospos_sales_items
						SET sale_id='".$default_sales_information->sale_id."',
						line='".$default_sales_information_max_line."'
						WHERE sale_id='".$row->sale_id."' 
						AND stock_id='".$row->stock_id."' 
						AND lot_no='".$row->lot_no."' 
						AND line='".$row->line."' 
						AND item_cost_price='".$row->item_cost_price."' 
						AND quantity_purchased='".$row->quantity_purchased."'
						LIMIT 1";

							$execute_array[]=$query;

							$default_sales_information_max_line++;

							$query="UPDATE stock_moves SET
								reference='".$default_sales_information->receipt_no."'
								WHERE stock_id='".$row->stock_id."'
								AND type='201'
								AND loc_code='".LOCATION_CODE."'
								AND price='".$row->item_cost_price."'
								AND qty='".($row->quantity_purchased*-1)."'
								AND reference ='".$consider_sale_id_information[$row->sale_id]->receipt_no."'
								AND lot_no ='".$row->lot_no."'
								LIMIT 1
								";
							$execute_array[]=$query;
						}else{
							exit();
						}
					}else{
						break;
					}
				}
			}

			if(count($execute_array)){
				//////////////////////////////EXECUTE///////////////////////
				foreach ($execute_array as $ex_key => $execution_query) {
					$this->db->query($execution_query); /////////////////////NEXT
				}

				$execute_array=array();
				$execute_array_default=array();

				$default_sales_information_max_line_details=array();

				$query_default_items = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$default_sales_information->sale_id."' ORDER BY line ASC");

				foreach ($query_default_items->result() as $row_default_line) {
					$default_sales_information_max_line_details=$row_default_line;
					break;
				}


				$update_vat_amount=number_format(($default_sales_information_max_line_details->vat_amount-$purchase_discount_vat_deduct), 2, '.', '');
				$update_vat_enable_price_after_discount=round($default_sales_information_max_line_details->vat_enable_price_after_discount)-round($purchase_discount_deduct);


				$update_sql="
			UPDATE ospos_sales_items SET
			vat_amount='".$update_vat_amount."',
			vat_enable_price_after_discount='".$update_vat_enable_price_after_discount."'
			
			WHERE sale_id='".$default_sales_information_max_line_details->sale_id."' 
			AND stock_id='".$default_sales_information_max_line_details->stock_id."' 
			AND lot_no='".$default_sales_information_max_line_details->lot_no."' 
			AND line='".$default_sales_information_max_line_details->line."' 
			AND item_cost_price='".$default_sales_information_max_line_details->item_cost_price."' LIMIT 1";


				$execute_array_default[]=$update_sql;



				$payment_sale_id=0;
				$payment_sale_id_amount=0;
				$sql_cash="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".intval($default_sales_information->sale_id)."' AND payment_type='Cash' LIMIT 1";


				$result_cash = $this->db->query($sql_cash);
				foreach ($result_cash->result() as $row_cash) {
					$row_cash=(object)$row_cash;
					$payment_sale_id=$row_cash->sale_id;
					$payment_sale_id_amount=$row_cash->payment_amount;
				}





				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($purchase_discount_cash_deduct))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
					$execute_array_default[]=$update_query_permission;

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".intval($default_sales_information->sale_id)."',
					'Cash',
					'-".round($purchase_discount_cash_deduct)."')";
					$execute_array_default[]=$insert_sql;
				}


				$payment_sale_id=0;
				$payment_sale_id_amount=0;
				$sql_cash="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".intval($default_sales_information->sale_id)."' AND payment_type='Purchase Discount' LIMIT 1";

				$result_cash = $this->db->query($sql_cash);
				foreach ($result_cash->result() as $row_cash) {
					$row_cash=(object)$row_cash;
					$payment_sale_id=$row_cash->sale_id;
					$payment_sale_id_amount=$row_cash->payment_amount;
				}

				if($payment_sale_id){
					$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($purchase_discount_deduct))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
					$execute_array_default[]=$update_query_permission;

				}else{
					$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".intval($default_sales_information->sale_id)."',
					'Purchase Discount',
					'".round($purchase_discount_deduct)."')";
					$execute_array_default[]=$insert_sql;
				}
				//////////////////////////////EXECUTE///////////////////////
				foreach ($execute_array_default as $ex_key => $execution_query) {
					$this->db->query($execution_query); /////////////////////NEXT
				}
				$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$default_sales_information->sale_id."',
						'0',
						'0',
						'Cash',
						'".round($total_sale_amount_for_consider)."',
						'0',
						'".round($purchase_discount_cash_deduct)."',
						'".round($purchase_discount_cash_deduct)."',
						'".round($purchase_discount_cash_deduct)."',
						'0')";
				$this->db->query($query);////NEXT
			}
		}
		return true;

	}

	function adjust_special_customer_for_40_precentage_with_lot_change($current_date){

		///////////////////////QC PASS///////////////////////////////
		if(trim($current_date)==""){
			$current_date=date("Y-m-d");
		}
		////////////////////////////////WITH LOT CHANGE///////////////////////////////////
		$consider_percentage_of_total_sale=30;//////////////////////% OF NEW PRODUCT SALE

		/////////////////SPECIAL DISCOUNT//////////////////////
		$special_customer_id=array();
		$query_special = $this->db->query("SELECT id FROM pos_ospos_customers
					WHERE is_special=1 AND special_percentage>0 ");

		foreach ($query_special->result() as $row_special) {
			$special_customer_id[]=$row_special->id;
		}

		$consider_sale_id=array();
		$consider_sale_id_information=array();

		$default_sales_information=array();
		$default_sales_information_max_line=1;

		/////////////////SPECIAL DISCOUNT//////////////////////
		$query_all_sale = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' 
					AND a.acc_location='".LOCATION_CODE."' AND a.payment_type!='' 
					AND (a.is_sync = 0 OR a.is_sync IS NULL)");


		foreach ($query_all_sale->result() as $row_all) {

			if(intval($row_all->customer_id)!=0){
				if (!in_array(intval($row_all->customer_id), $special_customer_id)){
					$consider_sale_id[]=$row_all->sale_id;
					$consider_sale_id_information[$row_all->sale_id]=$row_all;
				}else{
					/////////////////////////DEFAULT 40 Percentage Customer Sales ID///////////////////

					if(intval($row_all->customer_id)==31451){
						if(count($default_sales_information)==0){
							$query_default_items = $this->db->query("SELECT MAX(line) As max_line FROM ospos_sales_items WHERE sale_id='".$row_all->sale_id."'");
							foreach ($query_default_items->result() as $row_default_line) {
								$default_sales_information_max_line=intval($row_default_line->max_line)+1;
								$default_sales_information=$row_all;
							}
						}
					}
				}
			}else{
				$consider_sale_id[]=$row_all->sale_id;
				$consider_sale_id_information[$row_all->sale_id]=$row_all;
			}
		}

		$consider_total_pcr=0;

		if(count($consider_sale_id)){
			$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";

			$query_total_sale = $this->db->query("SELECT SUM(vat_enable_price) AS vat_enable_price
			FROM ospos_sales_items
			WHERE sale_id IN (".$consider_sale_id_string.")");

			foreach ($query_total_sale->result() as $row_total_sale) {
				$consider_total_pcr=intval((intval($row_total_sale->vat_enable_price)*$consider_percentage_of_total_sale/100)*40/100);///////////////////////////////////////////FLAT_40P

			}
		}
		if($consider_total_pcr>0){

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

			$description_wise_minimum=array();
			$category_wise_minimum=array();
			$stock_id_filter=array();

			$description_wise_minimum['Lungi']=200000;

			$description_wise_minimum['Maxi']=200000;

			$description_wise_minimum['Gamcha Fabric']=20000;
			$description_wise_minimum['Gamcha']=200000;

			$description_wise_minimum['Boy Trowzer']=200000;
			$description_wise_minimum['Female Trowzer']=200000;
			$description_wise_minimum['Male Trowzer']=200000;

			$description_wise_minimum['Male Three Quarter']=200000;

			$description_wise_minimum['Boy Sleeping Dress']=200000;
			$description_wise_minimum['Girl Sleeping Dress']=200000;
			$description_wise_minimum['Male Full Sleeping Dress']=200000;
			$description_wise_minimum['Male Sleeping Dress']=200000;

			$description_wise_minimum['Aligar Pazama']=200000;
			$description_wise_minimum['Boy Aligar Pazama']=200000;
			$description_wise_minimum['Boy Pazama']=200000;
			$description_wise_minimum['Male Pazama']=200000;

			$description_wise_minimum['Girl&#039;s Tank Tops']=200000;
			$description_wise_minimum['Men&#039;s Tank Tops']=200000;

			$description_wise_minimum['Men&#039;s Under Wear']=200000;


			$description_wise_minimum['Bed Sheet']=200000;
			$description_wise_minimum['Bed Sheet Aplic']=200000;
			$description_wise_minimum['Bed Sheet Block Print']=200000;
			$description_wise_minimum['Bed Sheet Dubble']=200000;
			$description_wise_minimum['Bed Sheet Dubble-Manufactured']=200000;
			$description_wise_minimum['Bed Sheet Nokshi']=200000;
			$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=200000;
			$description_wise_minimum['Bed Sheet Semi-Dubble']=200000;
			$description_wise_minimum['Bed Sheet Single']=200000;
			$description_wise_minimum['Bed Sheet Single-Manufactured']=200000;

			$description_wise_minimum['Baby Nokshi Katha']=200000;
			$description_wise_minimum['Nokshi Baby Katha']=200000;
			$description_wise_minimum['Nokshi Katha']=200000;

			$category_wise_minimum['56']=200000;////Handicraft


			if(count($description_wise_minimum)){
				$clause_string="";
				$where_string_description=array();
				foreach ($description_wise_minimum as $clause_key => $clause_value) {
					$clause_string.=" WHEN description = '".$clause_key."' THEN ".$clause_value." ";
					$where_string_description[]=$clause_key;
				}
				$where_string_description_string="'".implode("','",$where_string_description)."'";

				$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where description IN(".$where_string_description_string.")");


				foreach ($query_filter->result() as $row_filter) {
					if(intval($row_filter->price)){
						$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
					}
				}
			}

			if(count($category_wise_minimum)){
				$clause_string="";
				$where_string_description=array();
				foreach ($category_wise_minimum as $clause_key => $clause_value) {
					$clause_string.=" WHEN category_id = '".$clause_key."' THEN ".$clause_value." ";
					$where_string_description[]=$clause_key;
				}
				$where_string_description_string="'".implode("','",$where_string_description)."'";

				$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where category_id IN(".$where_string_description_string.")");


				foreach ($query_filter->result() as $row_filter) {
					if(intval($row_filter->price)){
						$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
					}
				}

			}

			$sharee_array[]="02927013";
			$sharee_array[]="02928014";
			$sharee_array[]="02929015";
			$sharee_array[]="02930016";
			$sharee_array[]="02931017";
			$sharee_array[]="02939001";
			$sharee_array[]="02939002";
			$sharee_array[]="02939003";
			$sharee_array[]="02939006";
			$sharee_array[]="02939007";
			$sharee_array[]="02939008";
			$sharee_array[]="02939009";
			$sharee_array[]="02939010";
			$sharee_array[]="02939011";
			$sharee_array[]="02939012";
			$sharee_array[]="02939018";
			$sharee_array[]="02939019";
			$sharee_array[]="02939020";
			$sharee_array[]="02939021";
			$sharee_array[]="05939002";
			$sharee_array[]="06139022";
			$sharee_array[]="06739011";


			$consider_sale_id_string="";
			$consider_sale_id_string="''";
			if(count($consider_sale_id)){
				$current_cash=0;
				$query_cash = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments
							WHERE sale_id IN (SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."') 
							AND  payment_type='CASH'");

				foreach ($query_cash->result() as $row_cash) {
					$current_cash=$row_cash->total_cash;/////////////////////NEXT CONSIDER
				}

				$total_sale_amount_for_consider=0;

				$purchase_discount_deduct=0;
				$purchase_discount_vat_deduct=0;
				$purchase_discount_cash_deduct=0;
				$sales_items_previous_vatable_added=0;
				$sales_items_previous_vatable_vat_added=0;

				$execute_array=array();

				$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";

				$query = $this->db->query("SELECT * FROM ospos_sales_items
			WHERE sale_id IN (".$consider_sale_id_string.") 
			AND quantity_purchased>0 AND lot_no>='210700'
			ORDER BY item_cost_price DESC,vat_enable_price_after_discount DESC, quantity_purchased ASC ");

				$first_row=1;
				foreach ($query->result() as $row) {

					$can_consider=0;

					if(!array_key_exists ( $row->stock_id, $stock_id_filter)){
						if(in_array($row->stock_id,$sharee_array)){
							/////////////////////////HAS LOT///////////////////////
							$found_lot_array=array();
							$new_lot_array=array();
							$query_lot_search = $this->db->query("SELECT * FROM stock_moves_pcr_no
			WHERE stock_id='".$row->stock_id."'
			AND price='".$row->item_cost_price."' AND lot_no!='".$row->lot_no."' AND lot_no<'200000'
			ORDER BY lot_no ASC");
							foreach ($query_lot_search->result() as $row_lot) {
								$found_lot_array[]=$row_lot;
							}
							if($found_lot_array){
								$rand_keys=array_rand($found_lot_array);
								$new_lot_array=$found_lot_array[$rand_keys];
							}
							if(count($new_lot_array)){
								$can_consider=1;
							}
						}else{
							/////////////////////////HAS LOT///////////////////////
							$found_lot_array=array();
							$new_lot_array=array();
							$query_lot_search = $this->db->query("SELECT * FROM stock_moves_pcr_no
			WHERE stock_id='".$row->stock_id."'
			AND price='".$row->item_cost_price."' AND lot_no!='".$row->lot_no."' AND lot_no<'210700'
			ORDER BY lot_no ASC");
							foreach ($query_lot_search->result() as $row_lot) {
								$found_lot_array[]=$row_lot;
							}
							if($found_lot_array){
								$rand_keys=array_rand($found_lot_array);
								$new_lot_array=$found_lot_array[$rand_keys];
							}
							if(count($new_lot_array)){
								$can_consider=1;
							}
						}
					}


					if($can_consider==1){

						$consider_discount_percenege=40;///////////////////////////////////////////FLAT_40P

						if(intval($consider_sale_id_information[$row->sale_id]->customer_id)!=0){
							$consider_discount_percenege=($consider_discount_percenege-8)+(($consider_discount_percenege-8)*7.5/100);
						}

						$sale_price=$row->item_cost_price*$row->quantity_purchased;
						$purchase_discount_sale=round(($sale_price*$consider_discount_percenege)/100);
						$purchase_discount_sale_vat=number_format(($purchase_discount_sale*$row->vat_percentage/100), 2, '.', '');
						$total_sale_amount_for_consider+=round($sale_price);


						$purchase_discount_deduct+=($purchase_discount_sale);
						$purchase_discount_vat_deduct+=$purchase_discount_sale_vat;
						$purchase_discount_cash_deduct+=($purchase_discount_sale+$purchase_discount_sale_vat);

						if($consider_total_pcr>$purchase_discount_sale){
							if($current_cash>538){
								$consider_total_pcr-=$purchase_discount_sale;
								$current_cash-=round(($purchase_discount_sale+$purchase_discount_sale_vat));


								if($first_row==1){

									///////////////////////////CHECK DEFAULT SALE INFO//////////////
									if(count($default_sales_information)==0){
										$insert_query="
								INSERT INTO ospos_sales
						            (sale_time,
						             customer_id,
						             employee_id,
						             comment,
						             receive_location,
						             payment_type,
						             location,
						             is_sync,
						             receipt_no,
						             acc_location,
						             is_global,
						             is_delivered,
						             is_sync_golbal_flag,
						             bag_big,
						             bag_medium,
						             bag_small,
						             is_global_delivery_sync)

						             VALUES ('".date("Y-m-d H:i:s")."',
									        '31451',
									        '1',
									        '0',
									        NULL,
									        '',
									        '".LOCATION_CODE."',
									        '0',
									        '".LOCATION_CODE.date("ymdHis")."',
									        '".LOCATION_CODE."',
									        '0',
									        '0',
									        '0',
									        NULL,
									        NULL,
									        NULL,
									        '0')";

										$this->db->query($insert_query); /////////////////////NEXT


										$query_default_sale_dummy = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' 
					AND a.acc_location='".LOCATION_CODE."' AND customer_id='31451' 
					AND (a.is_sync = 0 OR a.is_sync IS NULL) LIMIT 1");

										foreach ($query_default_sale_dummy->result() as $row_default_dummy) {
											if(intval($row_default_dummy->customer_id)==31451){
												$default_sales_information=$row_default_dummy;
												$default_sales_information_max_line=1;
											}
										}
										$first_row=0;
									}

								}

								/////////////EXISITING SALES Standard Cost///////////////////////

								$standard_cost_current_item=number_format(($row->item_cost_price*55)/100, 2, '.', '');

								$query_moves = $this->db->query("SELECT standard_cost FROM stock_moves
									WHERE stock_id='".$row->stock_id."'
									AND price='".$row->item_cost_price."' AND lot_no='".$row->lot_no."' AND standard_cost>1 ORDER BY standard_cost ASC");

								foreach ($query_moves->result() as $row_st) {
									$standard_cost_current_item=$row_st->standard_cost;
								}
								$mrp_details_array=array();
								if(trim($row->mrp_details)){
									$mrp_details_array=explode("NEWMRP",trim($row->mrp_details));
								}

								$receipt_no=$default_sales_information->receipt_no;
								$force_reference=substr($receipt_no,3).substr($receipt_no,0,3);

								$date_moves_update="20".substr($row->lot_no,0,2)."-".substr($row->lot_no,2,2)."-".str_pad(rand(1,28),2,"0",STR_PAD_LEFT);

								$new_lot_standard_cost=$standard_cost_current_item;
								if(doubleval($new_lot_array->standard_cost)!=0){
									$new_lot_standard_cost=$new_lot_array->standard_cost;
								}

								$mrp_details_array[]=$row->stock_id."#".$date_moves_update."#".$row->item_cost_price."#".$force_reference."#".($row->quantity_purchased*-1)."#".$standard_cost_current_item."#1#".$row->lot_no."#0#0";
								$mrp_details_array[]=$new_lot_array->stock_id."#".$date_moves_update."#".$new_lot_array->price."#".$force_reference."#".$row->quantity_purchased."#".$new_lot_standard_cost."#1#".$new_lot_array->lot_no."#0#0";


								$stock_moves_data_first="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$default_sales_information->sale_id."',
								'".$row->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update."',
								'".$default_sales_information->sale_id."',
								'".$row->item_cost_price."',
								'".$force_reference."',
								'".($row->quantity_purchased*-1)."',
								'0',
								'".$standard_cost_current_item."',
								'1',
								'".$row->lot_no."',
								'0',
								'0')";
								$execute_array[]=$stock_moves_data_first;



								$stock_moves_data_second="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$default_sales_information->sale_id."',
								'".$new_lot_array->stock_id."',
								'16',
								'".LOCATION_CODE."',
								'".$date_moves_update."',
								'".$default_sales_information->sale_id."',
								'".$new_lot_array->price."',
								'".$force_reference."',
								'".$row->quantity_purchased."',
								'0',
								'".$new_lot_standard_cost."',
								'1',
								'".$new_lot_array->lot_no."',
								'0',
								'0')";
								$execute_array[]=$stock_moves_data_second;

								$mrp_details="";
								if(count($mrp_details_array)){
									$mrp_details=implode("NEWMRP",$mrp_details_array);

								}

								$query="UPDATE ospos_sales_items
						SET sale_id='".$default_sales_information->sale_id."',
						line='".$default_sales_information_max_line."',
						lot_no='".$new_lot_array->lot_no."',
						mrp_details='".$mrp_details."'
						WHERE sale_id='".$row->sale_id."' 
						AND stock_id='".$row->stock_id."' 
						AND lot_no='".$row->lot_no."' 
						AND line='".$row->line."' 
						AND item_cost_price='".$row->item_cost_price."' 
						AND quantity_purchased='".$row->quantity_purchased."'
						LIMIT 1";

								$execute_array[]=$query;

								$default_sales_information_max_line++;


								$query="UPDATE stock_moves SET
								reference='".$default_sales_information->receipt_no."',
								standard_cost='".$new_lot_standard_cost."',
								lot_no='".$new_lot_array->lot_no."'
															
								WHERE stock_id='".$row->stock_id."'
								AND type='201'
								AND loc_code='".LOCATION_CODE."'
								AND price='".$row->item_cost_price."'
								AND qty='".($row->quantity_purchased*-1)."'
								AND reference ='".$consider_sale_id_information[$row->sale_id]->receipt_no."'
								AND lot_no ='".$row->lot_no."'
								LIMIT 1
								";
								$execute_array[]=$query;

							}else{
								break;
							}
						}else{
							break;
						}
					}
				}

				if(count($execute_array)){

					//////////////////////////////EXECUTE///////////////////////
					foreach ($execute_array as $ex_key => $execution_query) {
						$this->db->query($execution_query); /////////////////////NEXT
					}
					$execute_array=array();
					$execute_array_default=array();

					$default_sales_information_max_line_details=array();

					$query_default_items = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id='".$default_sales_information->sale_id."' ORDER BY line ASC");

					foreach ($query_default_items->result() as $row_default_line) {
						$default_sales_information_max_line_details=$row_default_line;
						break;
					}


					$update_vat_amount=number_format(($default_sales_information_max_line_details->vat_amount-$purchase_discount_vat_deduct), 2, '.', '');
					$update_vat_enable_price_after_discount=round($default_sales_information_max_line_details->vat_enable_price_after_discount)-round($purchase_discount_deduct);


					$update_sql="
			UPDATE ospos_sales_items SET
			vat_amount='".$update_vat_amount."',
			vat_enable_price_after_discount='".$update_vat_enable_price_after_discount."'
			
			WHERE sale_id='".$default_sales_information_max_line_details->sale_id."' 
			AND stock_id='".$default_sales_information_max_line_details->stock_id."' 
			AND lot_no='".$default_sales_information_max_line_details->lot_no."' 
			AND line='".$default_sales_information_max_line_details->line."' 
			AND item_cost_price='".$default_sales_information_max_line_details->item_cost_price."' LIMIT 1";

					$execute_array_default[]=$update_sql;



					$payment_sale_id=0;
					$payment_sale_id_amount=0;
					$sql_cash="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".intval($default_sales_information_max_line_details->sale_id)."' AND payment_type='Cash' LIMIT 1";


					$result_cash = $this->db->query($sql_cash);
					foreach ($result_cash->result() as $row_cash) {
						$row_cash=(object)$row_cash;
						$payment_sale_id=$row_cash->sale_id;
						$payment_sale_id_amount=$row_cash->payment_amount;
					}

					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount-round($purchase_discount_cash_deduct))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Cash'";
						$execute_array_default[]=$update_query_permission;

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".intval($default_sales_information_max_line_details->sale_id)."',
					'Cash',
					'-".round($purchase_discount_cash_deduct)."')";
						$execute_array_default[]=$insert_sql;
					}

					$payment_sale_id=0;
					$payment_sale_id_amount=0;
					$sql_cash="SELECT  sale_id,payment_amount FROM ospos_sales_payments WHERE sale_id ='".intval($default_sales_information_max_line_details->sale_id)."' AND payment_type='Purchase Discount' LIMIT 1";

					$result_cash = $this->db->query($sql_cash);
					foreach ($result_cash->result() as $row_cash) {
						$row_cash=(object)$row_cash;
						$payment_sale_id=$row_cash->sale_id;
						$payment_sale_id_amount=$row_cash->payment_amount;
					}

					if($payment_sale_id){
						$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($payment_sale_id_amount+round($purchase_discount_deduct))."' WHERE sale_id='".$payment_sale_id."' AND payment_type='Purchase Discount'";
						$execute_array_default[]=$update_query_permission;

					}else{
						$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".intval($default_sales_information_max_line_details->sale_id)."',
					'Purchase Discount',
					'".round($purchase_discount_deduct)."')";
						$execute_array_default[]=$insert_sql;
					}

					//////////////////////////////EXECUTE///////////////////////
					foreach ($execute_array_default as $ex_key => $execution_query) {
						$this->db->query($execution_query); /////////////////////NEXT
					}

					$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$default_sales_information_max_line_details->sale_id."',
						'0',
						'0',
						'Cash',
						'".round($total_sale_amount_for_consider)."',
						'0',
						'".round($purchase_discount_cash_deduct)."',
						'".round($purchase_discount_cash_deduct)."',
						'".round($purchase_discount_cash_deduct)."',
						'0')";
					$this->db->query($query);////NEXT

				}
			}
		}
		return true;

	}
}
?>