<?php

require_once ("secure_area.php");

class Sales extends Secure_area {

	function __construct() {
		parent::__construct('sales');
		$this->load->library('sale_lib');
		//$this->output->enable_profiler(TRUE);
	}

	function index() {

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		if(!$pageWasRefreshed){
			$this->sale_lib->clear_all();
		}
		$this->_reload();
	}

	function item_search() {
		$suggestions = array();


		if ($this->sale_lib->get_mode() == 'return' || $this->sale_lib->get_mode() == 'global_delivery') {

			$this->sale_lib->is_valid_receipt_shawpon(str_replace('#', '', $this->input->post('q'))) && $suggestions[] = $this->input->post('q');
		}

		if ($this->sale_lib->get_mode() == 'global') {
			$suggestions = array_merge($suggestions, $this->Item->get_item_search_suggestions_global($this->input->post('q'), 500));
		}else{
			$suggestions = array_merge($suggestions, $this->Item->get_item_search_suggestions($this->input->post('q'), $this->input->post('limit')));
		}
		echo implode("\n", $suggestions);
	}

	function customer_search() {
		$suggestions = $this->Customer->get_customer_search_suggestions_shawpon($this->input->post('q'), $this->input->post('limit'));
		echo implode("\n", $suggestions);
	}

	function select_customer() {
		$data = array();

		$data['coupon_card_discout'] = $_REQUEST['coupon_card_discout'];
		$data['coupon_card_maximum_discout'] = $_REQUEST['coupon_card_maximum_discout'];
		$data['coupon_card_number'] = $_REQUEST['coupon_card_number'];

		if(strlen($this->input->post("customer"))>=9){
			$query = $this->db->query("
                    SELECT id
                    FROM pos_ospos_customers 
                    WHERE gs_card_no ='".mysql_real_escape_string(trim($this->input->post("customer")))."'");
			$customer_id = $query->row()->id;

		}else{
			$customer_id = $this->input->post("customer");
		}
		$this->sale_lib->set_customer($customer_id);
		$this->_reload($data);
	}

	function change_mode() {

		$mode = $this->input->post("mode");
		$previous_mode = $this->session->userdata('sale_mode');

		if ($mode == "global") {
			$this->sale_lib->clear_all();
		} elseif ($mode == "sale" && $previous_mode == "global") {
			$this->sale_lib->clear_all();
		} elseif ($mode == "return" && $previous_mode == "global") {
			$this->sale_lib->clear_all();
		}

		$this->sale_lib->set_mode($mode);
		$this->_reload();
	}

	function set_comment() {
		$this->sale_lib->set_comment($this->input->post('comment'));
	}

	function set_receive_location() {
		$this->sale_lib->set_receive_location($this->input->post('receive_location'));
	}

	function set_email_receipt() {
		$this->sale_lib->set_email_receipt($this->input->post('email_receipt'));
	}

	//Alain Multiple Payments
	function add_payment() {
		$data = array();

		$data['facebook_customer_otp_correct'] = $_REQUEST['facebook_customer_otp_correct'];
		$data['coupon_card_discout'] = $_REQUEST['coupon_card_discout'];
		$data['coupon_card_maximum_discout'] = $_REQUEST['coupon_card_maximum_discout'];
		$data['coupon_card_number'] = $_REQUEST['coupon_card_number'];


		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){

			$payment_type = $this->input->post('payment_type');
			///////////////CHECK BIN////////////////////////
			$customer_id_check = $this->sale_lib->get_customer();
			$found_bin="";
			if($customer_id_check=="28946"){

				if($payment_type!="Purchase Bonus"){
					$bin_found=0;
					$bank_name_shawpon_bin['AB Bank Limited'][]="524525";
					$bank_name_shawpon_bin['AB Bank Limited'][]="559545";
					$bank_name_shawpon_bin['AB Bank Limited'][]="545739";

					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="541250";
					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="540244";
					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="540644";
					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="544119";
					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="543947";
					$bank_name_shawpon_bin['Al-Arafah Islami Bank Limited'][]="540017";

					$bank_name_shawpon_bin['Bank Asia Limited'][]="517253";
					$bank_name_shawpon_bin['Bank Asia Limited'][]="515780";
					$bank_name_shawpon_bin['Bank Asia Limited'][]="222704";
					$bank_name_shawpon_bin['Bank Asia Limited'][]="222705";
					$bank_name_shawpon_bin['Bank Asia Limited'][]="541173";

					$bank_name_shawpon_bin['BRAC Bank Limited'][]="548895";
					$bank_name_shawpon_bin['BRAC Bank Limited'][]="545538";
					$bank_name_shawpon_bin['BRAC Bank Limited'][]="545610";
					$bank_name_shawpon_bin['BRAC Bank Limited'][]="539932";
					$bank_name_shawpon_bin['BRAC Bank Limited'][]="536141";

					$bank_name_shawpon_bin['Dhaka Bank Limited'][]="513466";

					$bank_name_shawpon_bin['Dutch-Bangla Bank Limited'][]="557667";
					$bank_name_shawpon_bin['Dutch-Bangla Bank Limited'][]="524526";
					$bank_name_shawpon_bin['Dutch-Bangla Bank Limited'][]="530865";
					$bank_name_shawpon_bin['Dutch-Bangla Bank Limited'][]="542128";

					$bank_name_shawpon_bin['Eastern Bank Limited'][]="537683";
					$bank_name_shawpon_bin['Eastern Bank Limited'][]="539280";
					$bank_name_shawpon_bin['Eastern Bank Limited'][]="554028";
					$bank_name_shawpon_bin['Eastern Bank Limited'][]="559581";
					$bank_name_shawpon_bin['Eastern Bank Limited'][]="546008";
					$bank_name_shawpon_bin['Eastern Bank Limited'][]="540715";

					$bank_name_shawpon_bin['Islami Bank Bangladesh Ltd'][]="519025";
					$bank_name_shawpon_bin['Islami Bank Bangladesh Ltd'][]="519155";
					$bank_name_shawpon_bin['Islami Bank Bangladesh Ltd'][]="519029";

					$bank_name_shawpon_bin['LankaBangla Finance'][]="530505";
					$bank_name_shawpon_bin['LankaBangla Finance'][]="525680";
					$bank_name_shawpon_bin['LankaBangla Finance'][]="534273";
					$bank_name_shawpon_bin['LankaBangla Finance'][]="528173";

					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="541532";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="541487";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="512778";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="536310";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="549601";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="536798";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="559878";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="511629";
					$bank_name_shawpon_bin['Mutual Trust Bank Limited'][]="550843";

					$bank_name_shawpon_bin['National Bank Limited'][]="530216";
					$bank_name_shawpon_bin['National Bank Limited'][]="530218";
					$bank_name_shawpon_bin['National Bank Limited'][]="548867";
					$bank_name_shawpon_bin['National Bank Limited'][]="548868";
					$bank_name_shawpon_bin['National Bank Limited'][]="548195";
					$bank_name_shawpon_bin['National Bank Limited'][]="548196";

					$bank_name_shawpon_bin['Premier Bank Limited'][]="537025";
					$bank_name_shawpon_bin['Premier Bank Limited'][]="546592";
					$bank_name_shawpon_bin['Premier Bank Limited'][]="532754";
					$bank_name_shawpon_bin['Premier Bank Limited'][]="530342";
					$bank_name_shawpon_bin['Premier Bank Limited'][]="521948";

					$bank_name_shawpon_bin['Prime Bank Ltd'][]="512929";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="550586";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="559573";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="554793";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="554867";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="554777";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="554957";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="557660";
					$bank_name_shawpon_bin['Prime Bank Ltd'][]="515585";

					$bank_name_shawpon_bin['Pubali Bank Limited'][]="539949";
					$bank_name_shawpon_bin['Pubali Bank Limited'][]="548044";

					$bank_name_shawpon_bin['Southeast Bank Limited'][]="521623";
					$bank_name_shawpon_bin['Southeast Bank Limited'][]="537650";
					$bank_name_shawpon_bin['Southeast Bank Limited'][]="552421";
					$bank_name_shawpon_bin['Southeast Bank Limited'][]="543983";
					$bank_name_shawpon_bin['Southeast Bank Limited'][]="537682";
					$bank_name_shawpon_bin['Southeast Bank Limited'][]="537647";

					$bank_name_shawpon_bin['Standard Chartered Bank'][]="512760";
					$bank_name_shawpon_bin['Standard Chartered Bank'][]="51281500";///////////////8 DIGIT
					$bank_name_shawpon_bin['Standard Chartered Bank'][]="51281510";///////////////8 DIGIT
					$bank_name_shawpon_bin['Standard Chartered Bank'][]="524360";

					$bank_name_shawpon_bin['The City Bank Ltd'][]="517555";
					$bank_name_shawpon_bin['The City Bank Ltd'][]="519625";
					$bank_name_shawpon_bin['The City Bank Ltd'][]="528631";
					$bank_name_shawpon_bin['The City Bank Ltd'][]="519507";

					$bank_name_shawpon_bin['United Commercial Bank Limited'][]="521392";
					$bank_name_shawpon_bin['United Commercial Bank Limited'][]="526238";
					$bank_name_shawpon_bin['United Commercial Bank Limited'][]="530003";
					$bank_name_shawpon_bin['United Commercial Bank Limited'][]="548321";





					//////////////////////////////////////////////////////////////////////////
					$check_bin_full_card_no="";
					$check_bin_bank_name="";

					if($payment_type=="Credit Card"){
						$check_bin_full_card_no = $this->input->post('card_no_credit_shawpon');
						$check_bin_bank_name = $this->input->post('bank_name_credit_shawpon');
					}elseif($payment_type=="AMEX Card"){
						$check_bin_full_card_no = $this->input->post('card_no_amex_shawpon');
						$check_bin_bank_name = $this->input->post('bank_name_amex_shawpon');
					}elseif($payment_type=="Debit Card"){
						$check_bin_full_card_no = $this->input->post('card_no_debit_shawpon');
						$check_bin_bank_name = $this->input->post('bank_name_debit_shawpon');
					}

					if(trim($check_bin_bank_name)==""){
						$data['error'] = 'Please select Bank Name and try again!';
					}elseif(trim($check_bin_full_card_no)==""){
						$data['error'] = 'Please input Card No and try again!';
					}else{
						$bin_length_array=array();

						foreach ($bank_name_shawpon_bin[$check_bin_bank_name] as $key => $value) {
							$bin_length_array[strlen($value)]=strlen($value);
						}


						krsort($bin_length_array);
						$check_bin_full_card_no=preg_replace('/[^0-9]/', '', trim($check_bin_full_card_no));

						foreach ($bin_length_array as $bin_key => $bin_length) {
							$check_bin_no=substr($check_bin_full_card_no,0,$bin_length);
							foreach ($bank_name_shawpon_bin[$check_bin_bank_name] as $bank_key => $bank_value) {
								if(trim($check_bin_no)==trim($bank_value)){
									$bin_found=1;
									$found_bin=trim($bank_value);
									$ac_no_check =trim($bank_value);

									break;
								}
							}
						}

						$bin_found=1;
						
						
						if($bin_found==0){

							ksort($bin_length_array);

							$bin_length_str=implode("/",$bin_length_array);
							$bin_array=$bank_name_shawpon_bin[$check_bin_bank_name];
							sort($bin_array);
							$bin_array_show=array();
							foreach ($bin_array as $bin_key_show => $bin_value_show) {
								$bin_array_show[]="<font style='background-color:#F7FF0E;padding: 4px;color:#000000;'>".$bin_value_show."</font>";
							}
							$supported_bin_str=implode(" ",$bin_array_show);

							if($payment_type=="Credit Card"){
								$_POST['card_no_credit_shawpon'] = $this->input->post('card_no_credit_shawpon');
								$_POST['bank_name_credit_shawpon'] = $this->input->post('bank_name_credit_shawpon');
							}elseif($payment_type=="AMEX Card"){
								$_POST['card_no_amex_shawpon'] = $this->input->post('card_no_amex_shawpon');
								$_POST['bank_name_amex_shawpon'] = $this->input->post('bank_name_amex_shawpon');
							}elseif($payment_type=="Debit Card"){
								$_POST['card_no_debit_shawpon'] = $this->input->post('card_no_debit_shawpon');
								$_POST['bank_name_debit_shawpon'] = $this->input->post('bank_name_debit_shawpon');
							}
							$data['error'] = "<p style='pointer-events: none;padding-top:3px;'>Error BIN [First ".$bin_length_str." digits of card no]! Supported BIN for <font style='background-color:#2B2883;padding: 4px;color:#22F82A;'>".$check_bin_bank_name." </font>are: </p><p style='pointer-events: none;padding-top:10px;padding-bottom:3px;'>".$supported_bin_str."</p>";
						}

					}
				}else {
					$bin_found=1;
					$ac_no_check = $this->input->post('ac_no_check');

				}
			}else{
				$bin_found=1;
				$ac_no_check = $this->input->post('ac_no_check');

			}

			$amount_tendered = $this->input->post('amount_tendered');
			$check_name = $this->input->post('check_name');



			if($payment_type=="Credit Card"){
				$bank_name_credit = $this->input->post('bank_name_credit_shawpon');
				$branch_name_check = $this->input->post('bank_name_credit_shawpon');
				$card_no_credit = preg_replace('/[^0-9]/', '', trim($this->input->post('card_no_credit_shawpon')));
				$holder_name_credit = $this->input->post('holder_name_credit_shawpon');
				$card_expire_month = $this->input->post('card_expire_month_shawpon');
				$card_expire_year = $this->input->post('card_expire_year_shawpon');
				$bank_name_debit = "";
				$card_no_debit = "";
				$holder_name_debit = "";

			}elseif($payment_type=="AMEX Card"){
				$bank_name_credit = $this->input->post('bank_name_amex_shawpon');
				$branch_name_check = $this->input->post('bank_name_amex_shawpon');
				$card_no_credit = preg_replace('/[^0-9]/', '', trim($this->input->post('card_no_amex_shawpon')));
				$holder_name_credit = $this->input->post('holder_name_amex_shawpon');
				$card_expire_month = $this->input->post('amex_expire_month_shawpon');
				$card_expire_year = $this->input->post('amex_expire_year_shawpon');
				$bank_name_debit = "";
				$card_no_debit = "";
				$holder_name_debit = "";

			}elseif($payment_type=="Debit Card"){
				$bank_name_credit = "";
				$card_no_credit = "";
				$holder_name_credit = "";
				$card_expire_year = "";
				$card_expire_month = "";

				$bank_name_debit = $this->input->post('bank_name_debit_shawpon');
				$branch_name_check = $this->input->post('bank_name_debit_shawpon');
				$card_no_debit = preg_replace('/[^0-9]/', '', trim($this->input->post('card_no_debit_shawpon')));
				$holder_name_debit = $this->input->post('holder_name_debit_shawpon');
			}else{
				$bank_name_credit = "";
				$card_no_credit = "";
				$holder_name_credit = "";
				$card_expire_year = "";
				$card_expire_month = "";
				$bank_name_debit = "";
				$card_no_debit = "";
				$holder_name_debit = "";
				$branch_name_check = $this->input->post('branch_name_check');
			}
			$holder_name_check = $this->input->post('holder_name_check');
			$bank_name_check = $this->input->post('bank_name_check');

			$check_date = $this->input->post('check_date');
			$transaction_payment_id_cod= $this->input->post('transaction_payment_id_cod');
			$transaction_payment_id_ssl= $this->input->post('transaction_payment_id_ssl');

			$transaction_phone_no_bkash=$this->input->post('transaction_phone_no_bkash');
			$transaction_payment_id_bkash=$this->input->post('transaction_payment_id_bkash');

			$check_date = date('Y-m-d', strtotime($check_date));

			$customer_id = $this->sale_lib->get_customer();
			if ($customer_id != -1) {
				$user_point = $this->input->post('user_point');
				$total = $this->sale_lib->get_total();
				$perPointCost = $this->Sale->getPointCost();
				$maxUse = floor($total / $perPointCost->value) + 1;

				$user_points = $this->Customer->get_user_points($customer_id);
				if (!empty($this->sale_lib->get_user_points())) {
					$usable_points = $user_points->point - $this->sale_lib->get_user_points();
				} else {
					$usable_points = $user_points->point;
				}
				//echo $user_point;exit;

				if ($maxUse >= $usable_points)
				$maxUse = $usable_points + 1;

				//echo $maxUse;exit;

				$this->form_validation->set_rules('user_point', 'User Point', "is_natural|less_than[$maxUse]");
			}


			$this->form_validation->set_rules('amount_tendered', 'lang:sales_amount_tendered', 'numeric');
			$this->form_validation->set_rules('ac_no', 'lang:ac_no', 'numeric');


			if ($this->form_validation->run() == FALSE) {
				if ($this->input->post('payment_type') == $this->lang->line('sales_gift_card'))
				$data['error'] = $this->lang->line('sales_must_enter_numeric_giftcard');
				else
				$data['error'] = $this->lang->line('sales_must_enter_numeric');

				if ($this->input->post('ac_no') == '')
				$data['error'] = $this->lang->line('sales_must_enter_ac_no');

				if (!empty($this->input->post('user_point')))
				$maxUse = $maxUse - 1;
				$data['error'] = 'Maximum usable point:' . $maxUse;

				$this->_reload($data);
				return;
			}

			if (!empty($user_point)) {
				$this->sale_lib->set_user_points($user_point);
			}

			$payment_type = $this->input->post('payment_type');
			if ($payment_type == $this->lang->line('sales_giftcard')) {
				$payments = $this->sale_lib->get_payments();
				$payment_type = $this->input->post('payment_type') . ':' . $payment_amount = $this->input->post('amount_tendered');
				$current_payments_with_giftcard = isset($payments[$payment_type]) ? $payments[$payment_type]['payment_amount'] : 0;
				$cur_giftcard_value = $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')) - $current_payments_with_giftcard;


				if ($cur_giftcard_value <= 0) {
					$data['error'] = 'Giftcard balance is ' . to_currency($this->Giftcard->get_giftcard_value($this->input->post('amount_tendered'))) . ' !';
					$this->_reload($data);
					return;
				}

				$new_giftcard_value = $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')) - $this->sale_lib->get_amount_due();
				$new_giftcard_value = ( $new_giftcard_value >= 0 ) ? $new_giftcard_value : 0;
				$data['warning'] = 'Giftcard ' . $this->input->post('amount_tendered') . ' balance is ' . to_currency($new_giftcard_value) . ' !';
				$payment_amount = min($this->sale_lib->get_amount_due(), $this->Giftcard->get_giftcard_value($this->input->post('amount_tendered')));
			} else {
				$payment_amount = $this->input->post('amount_tendered');
			}

			if($bin_found==1){
				if($this->input->post('payment_type')=="BKash"){
					if (!$this->sale_lib->add_payment($payment_type, $amount_tendered, $ac_no_check, $check_name, $holder_name_credit, $holder_name_debit, $holder_name_check, $bank_name_check, $bank_name_credit, $bank_name_debit, $branch_name_check, $check_date, $card_expire_year, $card_expire_month, $card_no_credit, $card_no_debit,null,$transaction_payment_id_cod,$transaction_payment_id_ssl,$transaction_phone_no_bkash,$transaction_payment_id_bkash)) {
						$data['error'] = 'Unable to Add Payment! Please try again!';
					}
				}else{
					if (!$this->sale_lib->add_payment($payment_type, $amount_tendered, $ac_no_check, $check_name, $holder_name_credit, $holder_name_debit, $holder_name_check, $bank_name_check, $bank_name_credit, $bank_name_debit, $branch_name_check, $check_date, $card_expire_year, $card_expire_month, $card_no_credit, $card_no_debit,null,$transaction_payment_id_cod,$transaction_payment_id_ssl)) {
						$data['error'] = 'Unable to Add Payment! Please try again!';
					}
				}
			}
		}
		$this->_reload($data);
	}

	//function global search

	function globalsearch($product_code) {
		//		$product_code ="20";
		//              $payment_amount = $this->input->post( 'item' );
		////////////////CALL TO API//////////////

		$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;

		$checkMode = strpos($product_code, '@');
		if (!empty($checkMode)) {
			// manual add
			$selection = explode('@', $product_code);
			$product_code = $selection[0];
			$itemCode = $this->Sale->get_value('stock_id', 'stock_master', array('stock_id' => $product_code));
			$api_data['product_code'] = $itemCode->stock_id;
		} else {
			// add from bad code
			$lot = substr($this->input->post("item"), 8);
			$itemId = str_replace($lot, '', $product_code);
			$api_data['product_code'] = $itemId;
		}

		$api_data_final = json_encode($api_data);

		$result = $client->__soapCall('productSearchList', array('data' => $api_data_final));
		//        echo '<pre>';
		//        print_r(json_decode($result));exit;
		$data = array();

		$data['golbal_products'] = json_decode($result);

		$this->load->view('sales/globalsearch', $data);
	}

	function global_delivery($recept_id){
		$data['sale_items'] = $this->Sale->get_global_items_shawpon($recept_id);

		$this->db->set_dbprefix('ospos_');
		$data['receive_location'] = LOCATION_NAME;
		$this->load->view('sales/global_delivery', $data);
	}

	function confirm_global_delivery($recept_id){

		/*
		if(!empty($this->input->post('delivered'))){
		$this->Sale->update_data('sales', ['is_delivered' => 1], ['sale_id' => $recept_id]);
		}*/
		$this->_reload();
	}

	function confirm_delivery($recept_id){
		if(!empty($this->input->post('delivered'))){
			$this->Sale->update_data('sales', ['is_delivered' => 1], ['sale_id' => $recept_id]);
		}
		$this->_reload();
	}

	//Alain Multiple Payments
	function delete_payment($payment_id,$safe_string_to_store,$coupon_card_discout,$coupon_card_maximum_discout,$coupon_card_number) {

		$data = array();
		$data['coupon_card_discout'] = $coupon_card_discout;
		$data['coupon_card_maximum_discout'] = $coupon_card_maximum_discout;
		$data['coupon_card_number'] = $coupon_card_number;


		if($safe_string_to_store=="C4CA4238A0B923820DCC509A6F75849B"){
			$_REQUEST['facebook_customer_otp_correct'] = 1;
		}elseif($safe_string_to_store=="C4CA4238A0B923820DCC509A6F75849B"){
			$_REQUEST['facebook_customer_otp_correct'] = 0;
		}


		$this->sale_lib->delete_payment($payment_id);

		//$this->sale_lib->clear_user_points();
		$this->_reload($data);
	}

	function add() {
		$data = array();
		$data['coupon_card_discout'] = $_REQUEST['coupon_card_discout'];
		$data['coupon_card_maximum_discout'] = $_REQUEST['coupon_card_maximum_discout'];
		$data['coupon_card_number'] = $_REQUEST['coupon_card_number'];
		$mode = $this->sale_lib->get_mode();

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){

			//START::22-12-2018
			include('application/config/config.php');
			if(strlen($this->input->post("item"))==9){
				foreach ($this->session->userdata['cart'] as $session_key => $session_value) {
					if(trim($session_value['serialnumber'])==""){

						if($employee_code[$this->input->post("item")]['short_name']){
							$this->session->userdata['cart'][$session_key]['serialnumber']=$this->input->post("item");
						}
					}
				}
			}
			//END::22-12-2018
			$checkMode = strpos($this->input->post("item"), '@');
			$invoice = strpos($this->input->post("item"), '#');
			if (!empty($checkMode)) {
				// manual add
				// item_id - lot_no
				$selection = explode('@', $this->input->post("item"));
				$item_id_or_number_or_item_kit_or_receipt = $selection[0];
				$lot = $selection[1];
			} else if ($invoice != 0) {
				// sale id for reurn
				$item_id_or_number_or_item_kit_or_receipt = str_replace('#', '', $this->input->post("item"));
				$this->db->set_dbprefix('');
				$stockMove = $this->Sale->get_value('lot_no', 'stock_moves', ['trans_no' => $item_id_or_number_or_item_kit_or_receipt]);
				$this->db->set_dbprefix('ospos_');
				$lot = $stockMove->lot_no;
			} else {
				// add from bad code

				if($mode=='return'){

					if(is_numeric($this->input->post("item"))){
						$lot = substr($this->input->post("item"), 8);
						$item_id_or_number_or_item_kit_or_receipt = str_replace($lot, '', $this->input->post("item"));
					}else{
						$item_id_or_number_or_item_kit_or_receipt=$this->input->post("item");
					}
				}else{
					$lot = substr($this->input->post("item"), 8);
					$item_id_or_number_or_item_kit_or_receipt = str_replace($lot, '', $this->input->post("item"));
				}
			}

			$first_two= substr($lot, 0,2);
			if(intval($first_two)<=10){
				$lot=($first_two+10).substr($lot,2);
			}

			$quantity = $mode == "sale" ? 1 : -1;

			if ($this->sale_lib->is_valid_receipt_shawpon($item_id_or_number_or_item_kit_or_receipt) && $mode == 'return') {


				$this->sale_lib->return_entire_sale_shawpon($item_id_or_number_or_item_kit_or_receipt);
				//print_r($this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt));
				//exit;
			} elseif ($this->sale_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt)) {

				$this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt);
			}
			else if (!$this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt, $quantity, '', $lot,$mode)) {


				if(LOCATION_CODE=="BNK"){
					//START::22-12-2018
					if(strlen($this->input->post("item"))==9){
						if(trim($employee_code[$this->input->post("item")]['short_name'])!=""){
							$data['error'] = "<font style='color:#FEF323;'>Sales added to : ".$employee_code[$this->input->post("item")]['full_name']."</font>";
						}else{

							$data['sales_unable_to_add_item_flag'] = 1;
							$data['error'] = $this->lang->line('sales_unable_to_add_item');
						}
					}else{
						$data['sales_unable_to_add_item_flag'] = 1;
						$data['error'] = $this->lang->line('sales_unable_to_add_item');
					}
				}else{
					$data['sales_unable_to_add_item_flag'] = 1;
					$data['error'] = $this->lang->line('sales_unable_to_add_item');
				}
				//END::22-12-2018
			}


			if ($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt,$lot)) {

				$query = $this->db->query("
                    SELECT COUNT(trans_id) As count_row
                    FROM stock_moves 
                    WHERE stock_id ='".trim($item_id_or_number_or_item_kit_or_receipt)."' AND lot_no ='".trim($lot)."'");
				$has_lot = intval($query->row()->count_row);

				if($has_lot==0){
					$data['sales_unable_to_add_item_flag'] =1;
				}else{
					$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
				}
			}





			foreach ($this->session->userdata['cart'] as $session_key => $session_value) {

				if($session_value['lot_no']>=211100){
					$this->session->userdata['cart'][$session_key]['vat_amount']=((round($session_value['price'])*$session_value['vat_rate'])/100);
					$this->session->userdata['cart'][$session_key]['price_with_vat']=round(round($session_value['price'])+round((round($session_value['price'])*$session_value['vat_rate'])/100));

				}else{

					$this->session->userdata['cart'][$session_key]['vat_amount']=0;
					$this->session->userdata['cart'][$session_key]['price_with_vat']=round($session_value['price']);
				}
				if(doubleval($session_value['price'])==0){
					$this->sale_lib->delete_item($session_key);
					$data['price_error']="Price is zero. Please search product manually used by item code";
				}
			}



			//        if ($mode == 'return' && $this->sale_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt)) {
			//            echo 1;
			//            $this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
			//        } else if ($this->sale_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt)) {
			//            echo 2;
			//            $this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt, $item_location);
			//        } else if (!$this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt, $quantity, '', $lot)) {
			//            echo 3;
			//            $data['error'] = $this->lang->line('sales_unable_to_add_item');
			//        }
			//
			//        if ($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt)) {
			//            echo 4;
			//            $data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
			//        }
			//        exit;



		}
		$this->_reload($data);
	}

	function edit_item($line) {
		$data['coupon_card_discout'] = $_REQUEST['coupon_card_discout'];
		$data['coupon_card_maximum_discout'] = $_REQUEST['coupon_card_maximum_discout'];
		$data['coupon_card_number'] = $_REQUEST['coupon_card_number'];

		$this->form_validation->set_rules('price', 'lang:items_price', 'required|numeric');
		$this->form_validation->set_rules('quantity', 'lang:items_quantity', 'required|numeric');

		$description = $this->input->post("description");
		$serialnumber = $this->input->post("serialnumber");
		$price = $this->input->post("price");
		$quantity = $this->input->post("quantity");
		$discount = $this->input->post("discount");

		$mode = $this->sale_lib->get_mode();

		if ($this->form_validation->run() != FALSE) {
			if ($this->sale_lib->edit_item_qty_check($line,$quantity) == FALSE) {
				$data['error'] = "Submitted quantity is  not valid.";
				$data['error_alert_qty'] =1;
			}else{
				$this->sale_lib->edit_item($line, $description, $serialnumber, $quantity, $discount, $price);
			}
		} else {
			$data['error'] = $this->lang->line('sales_error_editing_item');
		}

		if ($this->sale_lib->out_of_stock($this->sale_lib->get_item_id($line),$this->sale_lib->get_lot_no($line),$price)) {
			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
		}

		$has_discount_any=0;
		foreach ($data['cart'] as $discount_key => $discount_value) {
			if($discount_value['discount']>0){
				$has_discount_any=1;
			}
		}
		////////////////////DISCOUNT CUSTOMER/////
		if($has_discount_any==1){
			$this->sale_lib->remove_customer();
		}



		$this->_reload($data);
	}

	function delete_item($item_number,$safe_string_to_store,$coupon_card_discout,$coupon_card_maximum_discout,$coupon_card_number) {
		$data = array();
		$data['coupon_card_discout'] = $coupon_card_discout;
		$data['coupon_card_maximum_discout'] = $coupon_card_maximum_discout;
		$data['coupon_card_number'] = $coupon_card_number;

		if($safe_string_to_store=="C4CA4238A0B923820DCC509A6F75849B"){
			$_REQUEST['facebook_customer_otp_correct'] = 1;
		}elseif($safe_string_to_store=="C4CA4238A0B923820DCC509A6F75849B"){
			$_REQUEST['facebook_customer_otp_correct'] = 0;
		}

		$this->sale_lib->delete_item($item_number);
		$this->_reload($data);
	}

	function remove_customer($coupon_card_discout,$coupon_card_maximum_discout,$coupon_card_number) {
		$data = array();
		$data['coupon_card_discout'] = $coupon_card_discout;
		$data['coupon_card_maximum_discout'] = $coupon_card_maximum_discout;
		$data['coupon_card_number'] = $coupon_card_number;

		$this->sale_lib->remove_customer();
		$this->_reload($data);
	}

	function new_card(){
		$data = array();
		$data['coupon_card_discout'] = $_REQUEST['coupon_card_discout'];
		$data['coupon_card_maximum_discout'] = $_REQUEST['coupon_card_maximum_discout'];
		$data['coupon_card_number'] = $_REQUEST['coupon_card_number'];

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		if(!$pageWasRefreshed){
			$this->Sale->update_card();
		}
		$this->_reload($data);
	}

	function add_coupon(){

		//$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		//if(!$pageWasRefreshed){
		$query = $this->db->query("
                    SELECT *
                    FROM pos_ospos_eid_coupon 
                    WHERE coupon_code ='".mysql_real_escape_string(trim($this->input->post("new_coupon_number")))."'");
		$coupon_id = $query->row()->id;
		$coupon_value = $query->row()->coupon_value;
		$coupon_date = $query->row()->coupon_date;
		$coupon_use_date = $query->row()->coupon_use_date;
		$is_used = $query->row()->is_used;
		$coupon_code = $query->row()->coupon_code;


		if(intval($coupon_id)==0){
			$data['error_message_coupon'] = "Invalid gift card information.";
			$data['coupon_card_maximum_discout']="";
			$data['coupon_card_number']="";
		}elseif(intval($is_used)==1){
			$data['error_message_coupon'] = "Gift card already used.";
			$data['coupon_card_maximum_discout']="";
			$data['coupon_card_number']="";
		}elseif(intval($coupon_value)==0){
			$data['error_message_coupon'] = "No amount in this gift card.";
			$data['coupon_card_maximum_discout']="";
			$data['coupon_card_number']="";
		}else{
			$data['coupon_card_maximum_discout']=intval($coupon_value);
			$data['coupon_card_number']=$coupon_code;
		}
		//}

		$this->_reload($data);
	}
	function remove_coupon_card(){

		//$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		//if(!$pageWasRefreshed){

		$data['coupon_card_maximum_discout']="";
		$data['coupon_card_discout']="";
		$data['coupon_card_number']="";

		//}

		$this->_reload($data);
	}
	function complete() {

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){

			if(intval($this->input->post('global_delivery_shawpon'))==1 AND trim($this->input->post('global_delivery_receipt_no'))){

				$success = $this->Sale->update_delivery_global($this->input->post('global_delivery_receipt_no'),$this->input->post('bag_big'),$this->input->post('bag_medium'),$this->input->post('bag_small'));

				if($success==true){

					$this->_reload(array('success' => $this->lang->line('sales_successfully_delivered_global')));
				}else{
					$this->_reload(array('error_message' => $this->lang->line('sales_unsuccessfully_delivered_global')));

				}

			}else{

				$data['cart'] = $this->sale_lib->get_cart();

				$data["mode"] = $this->sale_lib->get_mode();


				if($data['mode']=="global"){
					$selected_location = $data['cart'][1]['location'];

				}else{
					if($data['cart'][1]['location'] == LOCATION_CODE){
						$selected_location = LOCATION_CODE;
					}else{
						$this->db->set_dbprefix('');
						$select_location = $this->Sale->get_value('loc_code', 'locations', ['location_name' => $data['cart'][1]['location']]);
						$selected_location = $select_location->loc_code;
						$this->db->set_dbprefix('ospos_');
					}
				}

				$location = $data['cart'][1]['location'];

				//$purchase_discount_amount=$this->input->post('purchase_discount_amount');
				$purchase_discount_amount=$this->sale_lib->get_purchase_discount_amount_total();

				if ($data['cart']) {
					foreach ($data['cart'] as $c) {
						$tax = $this->Item->get_item_tax($c['item_id']);
						$data['item_tax'][$c['item_id']] = $tax->percent;
					}
					unset($c);
				}

				//$data['customer_info'] = $this->sale_lib->get_customer();


				//$data['taxes'] = $this->sale_lib->get_taxes();
				$data['total'] = $this->sale_lib->get_total()-$purchase_discount_amount;

				$data['receipt_title'] = $this->lang->line('sales_receipt');
				$data['transaction_time'] = date('m/d/Y h:i:s a');
				$customer_id = $this->sale_lib->get_customer();
				$employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
				$comment = $this->sale_lib->get_comment();
				$receive_location = $this->sale_lib->get_receive_location();

				if(trim($receive_location)==""){
					$data['receive_location'] = LOCATION_CODE;
				}else{
					$data['receive_location'] = $this->sale_lib->get_receive_location();
				}

				$emp_info = $this->Employee->get_info($employee_id);
				$data['payments'] = $this->sale_lib->get_payments();
				$data['amount_change'] = to_currency(($this->sale_lib->get_amount_due()-$purchase_discount_amount) * -1);
				$data['purchase_discount_amount'] = $purchase_discount_amount;
				$data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

				$data['cart_point'] = $this->sale_lib->get_user_points();
				$pointCost = $this->Sale->getPointCost();
				$data['cart_point_value'] = $pointCost->value;
				$data['cart_point_cost'] = $pointCost->value * $data['cart_point'];


				/////////////////////////////////////////////////////////////////////
				////previous due///

				if(($this->sale_lib->get_amount_due()-$purchase_discount_amount)==0){
					$data['previous_due'] = ($this->sale_lib->get_amount_due()-$purchase_discount_amount);
				}else{
					$data['previous_due'] = ($this->sale_lib->get_amount_due()-$purchase_discount_amount) * -1;
				}


				$data['previous_due'] = ($this->sale_lib->get_amount_due()-$purchase_discount_amount) * -1;
				/////Grand Total///
				$data['grand_total'] = $this->sale_lib->get_total() + $data['previous_due']-$purchase_discount_amount;


				$total_item_amount = $this->sale_lib->get_total();
				$previous_due = $this->Customer->customer_previous_due($customer_id);
				$previous_due_shawpon = $previous_due;
				$previous_due_advance = $previous_due;

				$remain_item_amount = $total_item_amount;

				$data['final_due'] = $previous_due;

				if ($customer_id != -1) {
					$cust_info = $this->Customer->get_info($customer_id);
					$data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name;
					$data['customerID'] = $customer_id;

					$data['customer_card_no'] = $cust_info->gs_card_no;
					$_REQUEST['mobile_no'] = $cust_info->phone_number;
					$mobile_no = $cust_info->phone_number;

					if(trim($data['customer_card_no'])==""){

						if( trim($this->input->post('new_card_number'))){
							$data['customer_card_no']=trim($this->input->post('new_card_number'));
						}
					}
				}

				$data['item_tax']=array();////////////////////FORCE Clean//////
				$data['refund_amount']=round($this->input->post('amount_due_for_post_submit'));////////////////////FORCE Clean//////
				$data['card_discount_total_with_vat_for_interface']=round($this->input->post('card_discount_total_with_vat_for_interface'));////////////////////FORCE Clean//////
				$data['coupon_card_discout']=round($this->input->post('coupon_card_discout'));////////////////////
				$data['coupon_card_maximum_discout']=round($this->input->post('coupon_card_maximum_discout'));////////////////////
				$data['coupon_card_number']=round($this->input->post('coupon_card_number'));////////////////////


				//SAVE sale to database
				$data_return = $this->Sale->save($data['cart'], $customer_id, $employee_id, $comment, $data['payments'], NULL, $receive_location, $selected_location,$data);


				$data['sale_id']=$data_return['sale_id'];
				$data['receipt_no']=$data_return['receipt_no'];

				if ($data['sale_id'] == '-1') {
					$data['error_message'] = $this->lang->line('sales_transaction_failed');
				}
				$data['complete'] = "complete";

				/*			Update OTP  */
				if ($customer_id != -1) {

					$query_otp = $this->db->query("UPDATE pos_ospos_customer_otp SET use_status=1 , use_date='".mysql_real_escape_string(date("Y-m-d"))."', need_to_sync=1
					WHERE facebook_customer_id='".mysql_real_escape_string($_REQUEST['facebook_customer_id'])
					."' AND mobile_no='".mysql_real_escape_string($mobile_no)
					."' AND otp='".mysql_real_escape_string($_REQUEST['facebook_otp'])
					."' AND use_status='".mysql_real_escape_string(0)
					."' AND is_sms='".mysql_real_escape_string(1)."'");

				}



				$data['subtotal'] = $this->sale_lib->get_subtotal();
				$data['taxes'] = $this->sale_lib->get_taxes_receipt($data,$purchase_discount_amount);
				$data['amount_due'] = $this->sale_lib->get_amount_due($data);
				$data['get_payments_total'] = $this->sale_lib->get_payments_total();


				$previous_tax=0;
				foreach ($data['taxes'] as $key => $value) {
					$previous_tax+=$value;
				}
				$prevous_sales_total=round($previous_tax+$data['total']);
				$prevous_payment_total=round($data['get_payments_total']);
				$data['previous_amount_due']=round($prevous_sales_total-$prevous_payment_total);
				$data['amount_due_for_post_submit_reload']=doubleval($this->input->post('amount_due_for_post_submit'));
				$data['previous_sales_total']=round($prevous_sales_total);
				$data['previous_coupon_card_discout']=intval($data['coupon_card_discout']);

				$data['purchase_discount_amount']=round($this->input->post('card_discount_total_with_vat_for_interface'));



				//////////////////////COUPON////////////////////////////////
				$data['coupon_code']="";
				$data['coupon_value']=0;


				$current_date=date("Y-m-d");

				if($current_date<='2022-05-05'){

					$coupon_code_length = 10;
					$total_product_price_consider=5000;
					$coupon_value_percentage=10;

					$total_product_price=0;

					foreach ($data['cart'] as $product_key => $product_value) {
						$total_product_price+=$product_value['price']*$product_value['quantity'];
					}

					if($total_product_price>=$total_product_price_consider){

						$microsec=str_pad(gettimeofday()['usec'],6,"0",STR_PAD_LEFT);
						$coupon_code=rand(1000,9999).$microsec;
						$coupon_code=substr($coupon_code, 0, $coupon_code_length);
						$data['coupon_code']=$coupon_code;
						$data['coupon_value']=intval(round(($total_product_price*$coupon_value_percentage)/100));


						$insert_query="INSERT INTO pos_ospos_eid_coupon (
									    loc_code,
										coupon_code,
										coupon_value,
										coupon_date,
										coupon_use_date,
										is_used)
					VALUES('".LOCATION_CODE."',
					'".$data['coupon_code']."',
					'".$data['coupon_value']."',
					'".date("Y-m-d H:i:s")."',
					'0000-00-00 00:00:00',
					'0')";
						$query = $this->db->query($insert_query);
					}
				}
				//////////////////////COUPON////////////////////////////////



				$data['sale_time'] = date('Y-m-d H:i:s');
				$this->load->view("sales/receipt", $data);
				// $this->load->view("sales/register",$data);


				$_POST['coupon_card_maximum_discout']="";
				$_POST['coupon_card_number']="";
				$_POST['coupon_card_discout']="";
				$_REQUEST['coupon_card_maximum_discout']="";
				$_REQUEST['coupon_card_number']="";
				$_REQUEST['coupon_card_discout']="";

				$data['coupon_card_maximum_discout']="";
				$data['coupon_card_number']="";
				$data['coupon_card_discout']="";

				$this->sale_lib->clear_all();
				$this->sale_lib->set_mode("sale");

				$this->_reload($data);

			}
		}else{
			$this->sale_lib->set_mode("sale");
			$this->_reload();
		}
	}


	function receipt_reprint($receipt_no){

		$this->sale_lib->empty_payments();

		$sale_info = $this->Sale->get_info_reprint($this->Sale->get_sale_by_invoice_number_shawpon_local_reprint($receipt_no)->row()->sale_id)->row_array();

		$this->sale_lib->copy_entire_sale_shawpon_reprint($sale_info['sale_id'],1);
		$data['cart'] = $this->sale_lib->get_cart();

		if($data['cart'][1]['location'] == LOCATION_CODE){
			$selected_location = LOCATION_CODE;
		}else{
			$this->db->set_dbprefix('');
			$select_location = $this->Sale->get_value('loc_code', 'locations', ['location_name' => $data['cart'][1]['location']]);
			$selected_location = $select_location->loc_code;
			$this->db->set_dbprefix('ospos_');
		}

		if ($data['cart']) {
			foreach ($data['cart'] as $c) {
				$tax = $this->Item->get_item_tax($c['item_id']);
				$data['item_tax'][$c['item_id']] = $tax->percent;
			}
			unset($c);
		}



		//$data['customer_info'] = $this->sale_lib->get_customer();
		$location = $data['cart'][1]['location'];
		$data["mode"] = $this->sale_lib->get_mode();

		$data['taxes'] = $this->sale_lib->get_taxes();


		$data['receipt_title'] = $this->lang->line('sales_receipt');
		$data['transaction_time'] = date('m/d/Y h:i:s a');
		//$customer_id = $this->sale_lib->get_customer();
		$customer_id = $sale_info['customer_id'];

		$employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->sale_lib->get_comment();
		$receive_location = $this->sale_lib->get_receive_location();

		if(trim($receive_location)==""){
			$data['receive_location']=$sale_info['receive_location'];
		}else{
			$data['receive_location'] = $receive_location;
		}

		if(intval($sale_info['is_global'])>0){
			$data["mode"]="global";
		}


		if ($customer_id != -1) {
			$cust_info = $this->Customer->get_info($customer_id);
			$data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name;
			$data['customer_card_no'] = $cust_info->gs_card_no;
			$data['customerID'] = $customer_id;
		}


		$emp_info = $this->Employee->get_info($employee_id);
		//$data['payments'] = $this->sale_lib->get_payments();

		$data['purchase_discount_amount']=0;



		$query_payment = $this->db->query("SELECT * FROM ospos_sales_payments_reprint where sale_id='".intval($sale_info['sale_id'])."'");
		$payment_details=array();
		foreach ($query_payment->result() as $row_payment) {

			$temp_array=array();
			foreach ($row_payment as $tmp_key => $tmp_value) {
				$temp_array[$tmp_key]=$tmp_value;
			}

			$payment_details[$row_payment->payment_type]=$temp_array;
		}


		foreach ($payment_details as $data_key => $data_value) {

			if($data_key=="Purchase Discount"){
				if(doubleval($data_value['bank_id'])){
					$data['purchase_discount_amount']=doubleval($data_value['bank_id']);
				}else{
					$data['purchase_discount_amount']=$data_value['payment_amount'];
				}
			}else{
				$data['payments'][$data_key]=$data_value;
			}
		}

		$purchase_discount_amount=$data['purchase_discount_amount'];

		$data['total'] = $this->sale_lib->get_total()-$purchase_discount_amount;



		//$data['payments'] = $this->sale_lib->get_sale_payments_shawpon($sale_info['sale_id'])->row_array();

		$previous_due_payment_amount=0;


		$payment_type_str=str_replace(" ","",$sale_info['payment_type']);
		$payment_type_str=str_replace("&nbsp;","",$payment_type_str);
		$find_previous_due_str="PreviousDuePayment:";
		$previous_due_position=strpos($payment_type_str, $find_previous_due_str);

		if($previous_due_position){

			$previous_due_next=substr($payment_type_str,$previous_due_position+19);
			$find_bdt_due_str="BDT";
			$bdt_position=strpos($previous_due_next, $find_bdt_due_str);
			$previous_due_payment_amount=substr($previous_due_next,0,$bdt_position);
		}

		$data['final_due'] = $previous_due_payment_amount;

		$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

		$data['cart_point'] = $this->sale_lib->get_user_points();
		$pointCost = $this->Sale->getPointCost();
		$data['cart_point_value'] = $pointCost->value;
		$data['cart_point_cost'] = $pointCost->value * $data['cart_point'];

		$data['sale_id']=$sale_info['sale_id'];
		$data['receipt_no']=$receipt_no;
		$data['sale_time']=$sale_info['sale_time'];

		if ($data['sale_id'] == '-1') {
			$data['error_message'] = $this->lang->line('sales_transaction_failed');
		}


		$data['subtotal'] = $this->sale_lib->get_subtotal();
		$data['taxes'] = $this->sale_lib->get_taxes_receipt($data,$purchase_discount_amount);
		$data['amount_due'] = $this->sale_lib->get_amount_due($data);
		$data['get_payments_total'] = $this->sale_lib->get_payments_total();


		$this->load->view("sales/receipt_reprint", $data);
		$this->sale_lib->clear_all();

		$this->load->view("reports/invoices");
		///$this->sale_lib->clear_all();
		//$this->_reload($data);
		//redirect('/reports/invoices');
	}

	function receipt_challan($receipt_no){

		$sale_info = $this->Sale->get_info_reprint($this->Sale->get_sale_by_invoice_number_shawpon_local_reprint($receipt_no)->row()->sale_id)->row_array();

		$this->sale_lib->copy_entire_sale_shawpon_reprint($sale_info['sale_id']);
		$summary_data=array();
		foreach ($this->sale_lib->get_cart() as $data_key => $data_value) {

			$summary_data[$data_value['gender']][$data_value['product_description']]['total_qty']=$summary_data[$data_value['gender']][$data_value['product_description']]['total_qty']+$data_value['quantity'];
			$summary_data[$data_value['gender']][$data_value['product_description']]['total_sale_amount']=$summary_data[$data_value['gender']][$data_value['product_description']]['total_sale_amount']+($data_value['total_sale_amount']+$data_value['total_discount']);
			$summary_data[$data_value['gender']][$data_value['product_description']]['total_discount']=$summary_data[$data_value['gender']][$data_value['product_description']]['total_discount']+$data_value['total_discount'];
			$summary_data[$data_value['gender']][$data_value['product_description']]['vat_amount']=$summary_data[$data_value['gender']][$data_value['product_description']]['vat_amount']+$data_value['vat_amount'];
			$summary_data[$data_value['gender']][$data_value['product_description']]['total_invoice_amount']=$summary_data[$data_value['gender']][$data_value['product_description']]['total_invoice_amount']+($data_value['total_sale_amount']+$data_value['vat_amount']);
		}

		$data['cart'] = $this->sale_lib->get_cart();
		$data['summary_cart'] = $summary_data;
		$data['payment_type'] = $sale_info['payment_type'];
		$data['invoice_date'] = date("d/m/Y",strtotime($sale_info['sale_time']));


		if($data['cart'][1]['location'] == LOCATION_CODE){
			$selected_location = LOCATION_CODE;
		}else{
			$this->db->set_dbprefix('');
			$select_location = $this->Sale->get_value('loc_code', 'locations', ['location_name' => $data['cart'][1]['location']]);
			$selected_location = $select_location->loc_code;
			$this->db->set_dbprefix('ospos_');
		}

		if ($data['cart']) {
			foreach ($data['cart'] as $c) {
				$tax = $this->Item->get_item_tax($c['item_id']);
				$data['item_tax'][$c['item_id']] = $tax->percent;
			}
			unset($c);
		}

		//$data['customer_info'] = $this->sale_lib->get_customer();
		$location = $data['cart'][1]['location'];
		$data["mode"] = $this->sale_lib->get_mode();

		$data['taxes'] = $this->sale_lib->get_taxes();

		$data['total'] = $this->sale_lib->get_total();
		$data['receipt_title'] = $this->lang->line('sales_receipt');
		$data['transaction_time'] = date('m/d/Y h:i:s a');
		//$customer_id = $this->sale_lib->get_customer();
		$customer_id = $sale_info['customer_id'];

		$employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->sale_lib->get_comment();
		$receive_location = $this->sale_lib->get_receive_location();

		if(trim($receive_location)==""){
			$data['receive_location']=$sale_info['receive_location'];
		}else{
			$data['receive_location'] = $receive_location;
		}

		if(intval($sale_info['is_global'])>0){
			$data["mode"]="global";
		}


		if ($customer_id != -1) {
			$cust_info = $this->Customer->get_info($customer_id);
			$data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name;
			$data['customerID'] = $customer_id;
		}

		$emp_info = $this->Employee->get_info($employee_id);
		$data['payments'] = $this->sale_lib->get_payments();
		//$data['payments'] = $this->sale_lib->get_sale_payments_shawpon($sale_info['sale_id'])->row_array();

		$previous_due_payment_amount=0;
		$payment_type_str=str_replace(" ","",$sale_info['payment_type']);
		$payment_type_str=str_replace("&nbsp;","",$payment_type_str);
		$find_previous_due_str="PreviousDuePayment:";
		$previous_due_position=strpos($payment_type_str, $find_previous_due_str);

		if($previous_due_position){

			$previous_due_next=substr($payment_type_str,$previous_due_position+19);
			$find_bdt_due_str="BDT";
			$bdt_position=strpos($previous_due_next, $find_bdt_due_str);
			$previous_due_payment_amount=substr($previous_due_next,0,$bdt_position);
		}

		$data['final_due'] = $previous_due_payment_amount;

		$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

		$data['cart_point'] = $this->sale_lib->get_user_points();
		$pointCost = $this->Sale->getPointCost();
		$data['cart_point_value'] = $pointCost->value;
		$data['cart_point_cost'] = $pointCost->value * $data['cart_point'];

		$data['sale_id']=$sale_info['sale_id'];
		$data['receipt_no']=$receipt_no;
		$data['sale_time']=$sale_info['sale_time'];

		if ($data['sale_id'] == '-1') {
			$data['error_message'] = $this->lang->line('sales_transaction_failed');
		}

		$this->load->view("sales/sales_challan",$data);

		/*$this->load->view("sales/receipt_challan", $data);
		$this->sale_lib->clear_all();
		$this->load->view("reports/invoices");*/
	}



	function receipt($sale_id) {

		$sale_info = $this->Sale->get_info($sale_id)->row_array();


		$this->sale_lib->copy_entire_sale($sale_id);
		$data['cart'] = $this->sale_lib->get_cart();
		$data['payments'] = $this->sale_lib->get_payments();
		$data['subtotal'] = $this->sale_lib->get_subtotal();
		$data['taxes'] = $this->sale_lib->get_taxes();
		$data['total'] = $this->sale_lib->get_total();
		$data['receipt_title'] = $this->lang->line('sales_receipt');
		$data['transaction_time'] = date('m/d/Y h:i:s a', strtotime($sale_info['sale_time']));
		$customer_id = $this->sale_lib->get_customer();
		$emp_info = $this->Employee->get_info($sale_info['employee_id']);
		$data['payment_type'] = $sale_info['payment_type'];
		$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

		if ($customer_id != -1) {
			$cust_info = $this->Customer->get_info($customer_id);
			$data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name;
		}
		$data['sale_id'] = 'POS ' . $sale_id;
		$data['sale_time']=$sale_info['sale_time'];
		$this->load->view("sales/receipt", $data);
		//$this->sale_lib->clear_all();
	}

	function edit($sale_id) {
		$data = array();

		$data['customers'] = array('' => 'No Customer');
		foreach ($this->Customer->get_all()->result() as $customer) {
			$data['customers'][$customer->person_id] = $customer->first_name . ' ' . $customer->last_name;
		}

		$data['employees'] = array();
		foreach ($this->Employee->get_all()->result() as $employee) {
			$data['employees'][$employee->person_id] = $employee->first_name . ' ' . $employee->last_name;
		}

		$data['sale_info'] = $this->Sale->get_info($sale_id)->row_array();


		$this->load->view('sales/edit', $data);
	}

	function delete($sale_id) {
		$data = array();

		if ($this->Sale->delete($sale_id)) {
			$data['success'] = true;
		} else {
			$data['success'] = false;
		}

		$this->load->view('sales/delete', $data);
	}

	function save($sale_id) {
		$sale_data = array(
		'sale_time' => date('Y-m-d', strtotime($this->input->post('date'))),
		'customer_id' => $this->input->post('customer_id') ? $this->input->post('customer_id') : null,
		'employee_id' => $this->input->post('employee_id'),
		'comment' => $this->input->post('comment')
		);

		if ($this->Sale->update($sale_data, $sale_id)) {
			echo json_encode(array('success' => true, 'message' => $this->lang->line('sales_successfully_updated')));
		} else {
			echo json_encode(array('success' => false, 'message' => $this->lang->line('sales_unsuccessfully_updated')));
		}
	}

	function _payments_cover_total($data) {
		$total_payments = 0;

		$previous_due = 0;

		if ($this->session->userdata['customer'] != -1) {
			$previous_due = $this->Customer->customer_previous_due($this->session->userdata['customer']);
		}
		foreach ($this->sale_lib->get_payments() as $payment) {
			$total_payments += $payment['payment_amount'];
		}


		/* Changed the conditional to account for floating point rounding */
		if (( $this->sale_lib->get_mode() == 'sale' ) && ( ( to_currency_no_money($this->sale_lib->get_total() + $previous_due-$data['purchase_discount_amount']-$data['coupon_card_discout']) - $total_payments ) > 1e-6 )) {
			if(trim($data['coupon_card_number'])){
				return true;
			}else{
				return false;
			}
		}

		return true;
	}

	function _reload($data = array()) {

		//Add Month in Dropdown


		if(isset($data['amount_due_for_post_submit_reload'])){
			$previous_amount_due=$data['amount_due_for_post_submit_reload'];
		}
		if(isset($data['previous_sales_total'])){
			$previous_sales_total=$data['previous_sales_total'];
		}

		for ($m = 1; $m <= 12; $m++) {
			$month = date('F', mktime(0, 0, 0, $m, 1, date('Y')));

			$data['month'][$m] = $month;
		}


		//Add Year in Dropdown

		$n = 0;
		while ($n < 16) {
			$date = date("Y") + $n;

			$data['year'][$date] = $date;
			$n++;
		}

		//add bank name in Dropdown
		$bank_id = $this->Item->get_bank_id();
		foreach ($bank_id as $key => $id) {
			$data['bank_id'][$id['id']] = $id['name'];
		}

		$person_info = $this->Employee->get_logged_in_employee_info();
		$data['cart'] = $this->sale_lib->get_cart();




		$data['lot_details'] = $this->sale_lib->get_lot_detail();
		$data['modes'] = array('sale' => $this->lang->line('sales_sale'), 'return' => $this->lang->line('sales_return'));
		$data['mode'] = $this->sale_lib->get_mode();
		$data['subtotal'] = $this->sale_lib->get_subtotal();

		$data['totalsubtotal'] = $this->sale_lib->get_totalsubtotal();

		$data['total_provide_discount'] = $this->sale_lib->total_provide_discount();

		$data['total'] = $this->sale_lib->get_total();
		$data['items_module_allowed'] = $this->Employee->has_permission('items', $person_info->person_id);
		$data['comment'] = $this->sale_lib->get_comment();
		$data['bag_big'] = $this->sale_lib->get_bag_big();
		$data['bag_medium'] = $this->sale_lib->get_bag_medium();
		$data['bag_small'] = $this->sale_lib->get_bag_small();
		$data['email_receipt'] = $this->sale_lib->get_email_receipt();
		$data['payments_total'] = $this->sale_lib->get_payments_total();

		$data['payments'] = $this->sale_lib->get_payments();
		$data['cart_point'] = $this->sale_lib->get_user_points();
		$pointCost = $this->Sale->getPointCost();
		$data['cart_point_value'] = $pointCost->value;
		$data['cart_point_cost'] = $pointCost->value * $data['cart_point'];

		$data['facebook_customer_otp_correct'] = $_REQUEST['facebook_customer_otp_correct'];
		$data['facebook_otp'] = $_REQUEST['facebook_otp'];


		if ($this->session->userdata['customer'] != -1) {

			if($data['mode']=="global"){

				$data['payment_options'] = array(
				$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
				//'COD Pathao' => 'COD Pathao',
				//'SSL COMMERZ' => 'SSL COMMERZ',
				//'Ajkerdeal' => 'Ajkerdeal',
				//'Priyoshop' => 'Priyoshop',
				//'Buymobile' => 'Buymobile',
				//'DARAZ' => 'DARAZ',
				//$this->lang->line('sales_check') => $this->lang->line('sales_check'),
				'AMEX Card' => 'AMEX Card',
				$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
				$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
				'BKash' => 'BKash',
				'BKash Apps' => 'BKash Apps',
				//'OkWallet' => 'OkWallet',
				//'User Point' => 'User Point',
				'Purchase Bonus' => 'Special Sales Discount'
				);

			}else{

				$data['payment_options'] = array(
				$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
				//'COD Pathao' => 'COD Pathao',
				//'SSL COMMERZ' => 'SSL COMMERZ',
				//'Ajkerdeal' => 'Ajkerdeal',
				//'Priyoshop' => 'Priyoshop',
				//'Buymobile' => 'Buymobile',
				//'DARAZ' => 'DARAZ',
				//$this->lang->line('sales_check') => $this->lang->line('sales_check'),
				'AMEX Card' => 'AMEX Card',
				$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
				$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
				'BKash' => 'BKash',
				'BKash Apps' => 'BKash Apps',
				//'OkWallet' => 'OkWallet',
				//'User Point' => 'User Point',
				'Purchase Bonus' => 'Special Sales Discount'
				);
			}
		} else {
			$data['payment_options'] = array(
			$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
			//'COD Pathao' => 'COD Pathao',
			//'SSL COMMERZ' => 'SSL COMMERZ',
			//'Ajkerdeal' => 'Ajkerdeal',
			//'Priyoshop' => 'Priyoshop',
			//'Buymobile' => 'Buymobile',
			//'DARAZ' => 'DARAZ',
			//$this->lang->line('sales_check') => $this->lang->line('sales_check'),
			'AMEX Card' => 'AMEX Card',
			$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
			$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
			'BKash' => 'BKash',
			'BKash Apps' => 'BKash Apps',
			//'OkWallet' => 'OkWallet',
			'Purchase Bonus' => 'Special Sales Discount'
			);
		}
		if(isset($data['complete'])){
			$data['customer']="";
		}else{
			$customer_id = $this->sale_lib->get_customer();

			$has_discount_any=0;
			foreach ($data['cart'] as $discount_key => $discount_value) {
				if($discount_value['discount']>0){
					$has_discount_any=1;
				}
			}
			////////////////////DISCOUNT CUSTOMER/////
			if($has_discount_any==1){
				$this->sale_lib->set_customer(26247);
				$customer_id=26247;
			}

			//////////////////////DEFAULT CUSTOMER/////////////
			if(count($this->session->userdata['cart'])>=1){
				$current_date_check=date("Y-m-d");
				if(LOCATION_CODE=="ADB" AND $current_date_check>="2022-09-21"){
					//if($current_date_check>='2022-01-15' AND $current_date_check<='2022-01-31'){
					$this->sale_lib->set_customer(31259);
					$customer_id=31259;
				}elseif(LOCATION_CODE=="DNJ" OR LOCATION_CODE=="MYN" ){
					$this->sale_lib->set_customer(31451);
					$customer_id=31451;
				}
			}
		}

		if ($customer_id != -1) {
			$info = $this->Customer->get_info($customer_id);

			$data['customer'] = $info->first_name . ' ' . $info->last_name;
			$data['customer_gs_card'] = $info->gs_card_no;
			$data['customer_gs_id'] = $info->id;
			$data['customer_email'] = $info->email;
			$data['mobile_no'] = $info->phone_number;
			$mobile_no = $info->phone_number;
			$_REQUEST['mobile_no'] = $info->phone_number;
			$data['customer_state'] = $info->state;
			$data['previous_due'] = $this->Customer->customer_previous_due($customer_id);

			/*		shawpon:OTP	START*/

			$data['facebook_customer'] = $info->facebook_customer;

			if(intval($info->facebook_customer)==1){
				/*	Check OTP Correct/Not		*/
				if(trim($_REQUEST['facebook_otp'])){

					$query_otp = $this->db->query("SELECT id
					FROM pos_ospos_customer_otp 
					WHERE facebook_customer_id='".mysql_real_escape_string($customer_id)
					."' AND mobile_no='".mysql_real_escape_string($mobile_no)
					."' AND otp='".mysql_real_escape_string($_REQUEST['facebook_otp'])
					."' AND use_status='".mysql_real_escape_string(0)
					."' AND is_sms='".mysql_real_escape_string(1)
					."' AND need_to_sync='".mysql_real_escape_string(0)
					."' GROUP BY otp");

					$otp_id=$query_otp->row();


					if(intval($otp_id)){
						$data['facebook_customer_otp_correct'] = 1;
						$data['facebook_otp'] = $_REQUEST['facebook_otp'];
					}else{
						$data['facebook_customer_otp_correct'] = 0;
					}
				}else{

					if(intval($data['facebook_customer_otp_correct'])!=1){
						$data['facebook_customer_otp_correct'] = 0;
					}
				}

			}else{
				$data['facebook_customer_otp_correct'] = 1;
			}


			/*		shawpon:OTP END	*/

			$user_points = $this->Customer->get_user_points($customer_id);
			$data['user_points'] = $user_points->point;

			$purchase_discount_elegible_percentage_amount_temp=($user_points->point*100)+$data['subtotal'];

			$purchase_discount_elegible_percentage_amount_cal=0;


			if(POINT_CARD_ACTIVE==1){
				/*		shawpon:OTP	START*/
				if($data['facebook_customer_otp_correct']==1){
					/*		shawpon:OTP	END*/
					if($customer_id==1009){
						$data['purchase_discount_percentage']= 10;
						$data['purchase_discount_amount']= round(number_format((($data['subtotal']*10)/100),2,'.',''));
						$purchase_discount_elegible_percentage_amount_cal=$data['subtotal'];

					}
					else{

						if(trim($data['customer_gs_card']) AND trim($data['customer_state'])==""){

							if($info->is_special==1){

								$info->special_percentage=50;

								$current_directory = getcwd();
								if (file_exists($current_directory . '\application\config\mrp_config.php')) {
									include('application/config/mrp_config.php');
								}
								if(intval($config_mrp['MRP_VAT_INCLUDE_SPECIAL'])){
									$info->special_percentage=($info->special_percentage+number_format((($info->special_percentage*7.5)/100),2,'.',''));
								}


								$data['purchase_discount_percentage']= $info->special_percentage;
								$data['purchase_discount_amount']= round(number_format((($data['subtotal']*$info->special_percentage)/100),2,'.',''));
								$purchase_discount_elegible_percentage_amount_cal=$data['subtotal'];

							}else{
								///swagatapurna//17-10-2020
								$default_percentage = $this->sale_lib->get_email_receipt();

								if(intval($default_percentage)){
									$data['purchase_discount_percentage']= $default_percentage;
									$data['purchase_discount_amount']= round(number_format((($data['subtotal']*$default_percentage)/100),2,'.',''));
									$purchase_discount_elegible_percentage_amount_cal=$data['subtotal'];
									$data['user_points'] = rand(7000,9999)/100;
								}
								else{
									if($purchase_discount_elegible_percentage_amount_temp>POINT_FOR_FIRST_DISCOUNT_START_GTHAN){

										if($purchase_discount_elegible_percentage_amount_temp>POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
											$data['purchase_discount_percentage']= SECOND_DISCOUNT_PERCENTAGE;
											$data['purchase_discount_amount']= round(number_format((($data['subtotal']*SECOND_DISCOUNT_PERCENTAGE)/100),2,'.',''));

										}else if($purchase_discount_elegible_percentage_amount_temp<=POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
											$data['purchase_discount_percentage']= FIRST_DISCOUNT_PERCENTAGE;
											$data['purchase_discount_amount']= round(number_format((($data['subtotal']*FIRST_DISCOUNT_PERCENTAGE)/100),2,'.',''));
										}
									}else{
										$data['purchase_discount_percentage']= FIRST_DISCOUNT_PERCENTAGE;
										$data['purchase_discount_amount']= round(number_format((($data['subtotal']*FIRST_DISCOUNT_PERCENTAGE)/100),2,'.',''));
									}
									$purchase_discount_elegible_percentage_amount_cal=$data['subtotal'];
								}
							}

						}elseif(trim($data['customer_gs_card']) AND trim($data['customer_state'])!=""){


							if($user_points->point==0){
								$data['new_customer_added_success']=1;
								$purchase_discount_elegible_percentage_amount_temp=($user_points->point*100)+$data['subtotal'];

								if($data['subtotal']>POINT_FOR_FIRST_DISCOUNT_START_GTHAN){
									if(($data['subtotal']-POINT_FOR_CARD)>POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
										$data['purchase_discount_percentage']= SECOND_DISCOUNT_PERCENTAGE;
										$data['purchase_discount_amount']= round(number_format(((($data['subtotal']-POINT_FOR_CARD)*SECOND_DISCOUNT_PERCENTAGE)/100),2,'.',''));

									}else if(($data['subtotal']-POINT_FOR_CARD)<=POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
										$data['purchase_discount_percentage']= FIRST_DISCOUNT_PERCENTAGE;
										$data['purchase_discount_amount']= round(number_format(((($data['subtotal']-POINT_FOR_CARD)*FIRST_DISCOUNT_PERCENTAGE)/100),2,'.',''));
									}
								}else{
									$data['purchase_discount_percentage']= 0;
									$data['purchase_discount_amount']= number_format(0,2,'.','');
								}
								$purchase_discount_elegible_percentage_amount_cal=$data['subtotal']-POINT_FOR_CARD;
							}else{
								if($purchase_discount_elegible_percentage_amount_temp>POINT_FOR_FIRST_DISCOUNT_START_GTHAN){

									if($purchase_discount_elegible_percentage_amount_temp>POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
										$data['purchase_discount_percentage']= SECOND_DISCOUNT_PERCENTAGE;
										$data['purchase_discount_amount']= round(number_format((($data['subtotal']*SECOND_DISCOUNT_PERCENTAGE)/100),2,'.',''));

									}else if($purchase_discount_elegible_percentage_amount_temp<=POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
										$data['purchase_discount_percentage']= FIRST_DISCOUNT_PERCENTAGE;
										$data['purchase_discount_amount']= round(number_format((($data['subtotal']*FIRST_DISCOUNT_PERCENTAGE)/100),2,'.',''));
									}
								}else{
									$data['purchase_discount_percentage']= FIRST_DISCOUNT_PERCENTAGE;
									$data['purchase_discount_amount']= round(number_format((($data['subtotal']*FIRST_DISCOUNT_PERCENTAGE)/100),2,'.',''));
								}
								$purchase_discount_elegible_percentage_amount_cal=$data['subtotal'];
							}

						}else{
							$data['purchase_discount_percentage']= 0;
							$data['purchase_discount_amount']= number_format(0,2,'.','');
							$purchase_discount_elegible_percentage_amount_cal=$data['subtotal']-POINT_FOR_CARD;
						}
						/*		shawpon:OTP	START*/
					}
				}else{
					$data['purchase_discount_percentage']= 0;
					$data['purchase_discount_amount']= number_format(0,2,'.','');
					$purchase_discount_elegible_percentage_amount_cal=-1;
				}/*		shawpon:OTP	END*/
			}else{
				$data['purchase_discount_percentage']= 0;
				$data['purchase_discount_amount']= number_format(0,2,'.','');
				$purchase_discount_elegible_percentage_amount_cal=-1;
			}

			$data['purchase_discount_elegible_percentage_amount']=$purchase_discount_elegible_percentage_amount_cal ;

		}
		//$data['coupon_card_discout']=$this->input->post('coupon_card_discout');

		$data['payments_cover_total'] = $this->_payments_cover_total($data);

		//load locations
		//        $this->load->model('cron_model');
		//        $this->db->set_dbprefix('');
		//        $locations = $this->cron_model->get_data('locations');
		//        $this->db->set_dbprefix('ospos_');
		//        if($locations){
		//            foreach($locations as $l){
		//                $posLocations[$l->loc_code] = $l->loc_code;
		//            }
		//        }
		//
		//        $data['posLocations'] = $posLocations;




		/////////////////////////////////////
		$included_vat_sub_total_qty=0;
		$included_vat_sub_total_qty_return=0;
		$included_vat_sub_total_amount=0;
		$included_vat_sub_total_vat_amount=0;
		$included_vat_sub_total_inv_amount=0;

		$exclued_vat_sub_total_qty=0;
		$exclued_vat_sub_total_qty_return=0;
		$exclued_vat_sub_total_amount=0;
		$exclued_vat_sub_total_vat_amount=0;
		$exclued_vat_sub_total_inv_amount=0;




		foreach ($this->session->userdata['cart'] as $session_key => $session_value) {

			if($session_value['lot_no']>=211100){
				if($session_value['quantity']>0){
					$included_vat_sub_total_qty+=$session_value['quantity'];
				}else{
					$included_vat_sub_total_qty_return+=$session_value['quantity'];
				}
				$included_vat_sub_total_inv_amount+=round(round($session_value['price'])*$session_value['quantity']);
				$included_vat_sub_total_amount+=round($session_value['price_with_vat'])*$session_value['quantity'];
				$included_vat_sub_total_vat_amount+=round((round($session_value['price'])*$session_value['vat_rate'])/100)*$session_value['quantity'];
			}else{
				if($session_value['quantity']>0){
					$exclued_vat_sub_total_qty+=$session_value['quantity'];
				}else{
					$exclued_vat_sub_total_qty_return+=$session_value['quantity'];
				}
				$exclued_vat_sub_total_inv_amount+=round(round($session_value['price'])*$session_value['quantity']);
				$exclued_vat_sub_total_amount+=round($session_value['price'])*$session_value['quantity'];
				$exclued_vat_sub_total_vat_amount+=((round($session_value['price'])*$session_value['vat_rate'])/100)*$session_value['quantity'];
			}
		}

		$data['included_vat_sub_total_qty']=$included_vat_sub_total_qty;
		$data['included_vat_sub_total_qty_return']=$included_vat_sub_total_qty_return;
		$data['included_vat_sub_total_amount']=$included_vat_sub_total_amount;
		$data['included_vat_sub_total_inv_amount']=$included_vat_sub_total_inv_amount;
		$data['included_vat_sub_total_vat_amount']=$included_vat_sub_total_vat_amount;


		$data['exclued_vat_sub_total_qty']=$exclued_vat_sub_total_qty;
		$data['exclued_vat_sub_total_qty_return']=$exclued_vat_sub_total_qty_return;
		$data['exclued_vat_sub_total_amount']=$exclued_vat_sub_total_amount;
		$data['exclued_vat_sub_total_inv_amount']=$exclued_vat_sub_total_inv_amount;
		$data['exclued_vat_sub_total_vat_amount']=$exclued_vat_sub_total_vat_amount;

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

		$data['subtotal']=$exclued_vat_sub_total_amount;
		$data['vat_enable_subtotal'] = $this->sale_lib->get_vat_enable_subtotal($data);

		$data['taxes']['7.5']=$exclued_vat_sub_total_vat_amount;

		$data['amount_due'] = $this->sale_lib->get_amount_due($data);

		//$data['amount_due'] = round($data['amount_due']-$data['purchase_discount_amount']);


		if(doubleval($previous_amount_due)){
			$data['previous_amount_due']=$previous_amount_due;
		}
		if(doubleval($previous_sales_total)){
			$data['previous_sales_total']=$previous_sales_total;
		}

		$this->sale_lib->set_purchase_discount_amount_total($data['purchase_discount_amount']);

		$this->load->view("sales/register", $data);
	}


	function check_otp(){
		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		$this->_reload($data);
	}



	function cancel_sale() {
		$this->sale_lib->clear_all();
		$this->_reload();
	}

	function suspend() {


		$data['cart'] = $this->sale_lib->get_cart();

		$data['subtotal'] = $this->sale_lib->get_subtotal();
		$data['taxes'] = $this->sale_lib->get_taxes();
		$data['total'] = $this->sale_lib->get_total();
		$data['receipt_title'] = $this->lang->line('sales_receipt');
		$data['transaction_time'] = date('m/d/Y h:i:s a');
		$customer_id = $this->sale_lib->get_customer();
		$employee_id = $this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->input->post('comment');
		$emp_info = $this->Employee->get_info($employee_id);
		$payment_type = $this->input->post('payment_type');
		$data['payment_type'] = $this->input->post('payment_type');
		//Alain Multiple payments
		$data['payments'] = $this->sale_lib->get_payments();
		$data['amount_change'] = to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee'] = $emp_info->first_name . ' ' . $emp_info->last_name;

		if ($customer_id != -1) {
			$cust_info = $this->Customer->get_info($customer_id);
			$data['customer'] = $cust_info->first_name . ' ' . $cust_info->last_name;
		}

		$total_payments = 0;

		foreach ($data['payments'] as $payment) {
			$total_payments += $payment['payment_amount'];
		}

		//SAVE sale to database
		$data['sale_id'] = 'POS ' . $this->Sale_suspended->save($data['cart'], $customer_id, $employee_id, $comment, $data['payments']);
		if ($data['sale_id'] == 'POS -1') {
			$data['error_message'] = $this->lang->line('sales_transaction_failed');
		}
		$this->sale_lib->clear_all();
		$this->_reload(array('success' => $this->lang->line('sales_successfully_suspended_sale')));
	}

	function suspended() {
		$data = array();
		$data['suspended_sales'] = $this->Sale_suspended->get_all()->result_array();

		foreach ($data['suspended_sales'] as $key => $value) {
			$search_sales_id=$value['sale_id'];
			$data['suspended_sales_details'][$search_sales_id]=$this->Sale_suspended->get_sale_items($search_sales_id)->result_array();
		}
		$this->load->view('sales/suspended', $data);
	}

	function unsuspend() {
		$sale_id = $this->input->post('suspended_sale_id');
		$this->sale_lib->clear_all();
		$this->sale_lib->copy_entire_suspended_sale($sale_id);
		$this->Sale_suspended->delete($sale_id);

		$this->_reload();
	}

	function globalsale() {

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){

			$item_id = $this->input->post('item_id');
			$location_name = $this->input->post('location_name');
			$description = $this->input->post('description');
			$loc_code = $this->input->post('loc_code');
			$lot_no = $this->input->post('lot_no');
			$price = $this->input->post('price');
			$this->session->set_userdata(['global_receive_location_code' => $loc_code]);
			$this->session->set_userdata(['global_receive_location' => $location_name]);
			$data = array();

			$mode = $this->sale_lib->get_mode();

			$item_id_or_number_or_item_kit_or_receipt = $sale_id;

			$quantity = $mode == "global" ? 1 : -1;

			if (!$this->sale_lib->add_item_global($item_id, $quantity, $loc_code, $lot_no, $mode,0,$price,$description,null)) {

				$data['error'] = $this->lang->line('sales_unable_to_add_item');
				$data['sales_unable_to_add_item_flag'] =1;
			}
		}


		$this->_reload($data);
	}

	function completeSele() {

		$this->sale_lib->clear_all();
		$this->_reload();
	}

	function delete_point() {
		$this->sale_lib->clear_user_points();
		$this->_reload();
	}
	function reset() {

		$current_directory = getcwd();
		/*
		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
		$file_content_live=file_get_contents("https://pharma.santisirmdc.org/admin/mrp_config/mrp_config_".LOCATION_CODE.".php");

		if(trim($file_content_live)){
		$file_content_array=unserialize($file_content_live);
		$filename = "application/config/mrp_config.php";
		$file_content="";
		foreach ($file_content_array as $key => $value) {
		$file_content.="$"."config_mrp['".$key."']='".$value."';\n";
		}
		$obj=fopen($filename, 'w');
		fwrite($obj, "<?php \n".$file_content);
		fclose($obj);
		}
		}
		*/


		/*if (file_exists($current_directory . '\application\config\mrp_config.php')) {
		include('application/config/mrp_config.php');

		$lunch_break=$config_mrp['MRP_LUNCHBREAK'];

		if($lunch_break==1){
		$config_mrp['MRP_LUNCHBREAK']=0;
		$config_mrp['MRP_LUNCHBREAK_START']="0000-00-00 00:00:00";
		$config_mrp['MRP_LUNCHBREAK_END']="0000-00-00 00:00:00";

		}elseif($lunch_break==0){
		$config_mrp['MRP_LUNCHBREAK']=1;
		$config_mrp['MRP_LUNCHBREAK_START']=date("Y-m-d H:i:s");
		$config_mrp['MRP_LUNCHBREAK_END']=date("Y-m-d")." 23:59:59";
		}
		$filename = "application/config/mrp_config.php";

		$file_content="<?php\n";
		foreach ($config_mrp as $key => $value) {
		$file_content.="$"."config_mrp['".$key."']='".$value."';\n";

		}
		$obj=fopen($filename, 'w');
		fwrite($obj, $file_content);
		fclose($obj);
		}*/
		header("Location: ".base_url());

	}


	function force_reset() {

		$current_directory = getcwd();

		if (file_exists($current_directory . '\application\config\mrp_config.php')) {
			include('application/config/mrp_config.php');

			$lunch_break=$config_mrp['MRP_LUNCHBREAK'];

			$config_mrp['MRP_LUNCHBREAK']=1;
			$config_mrp['MRP_LUNCHBREAK_START']=date("Y-m-d H:i:s");
			$config_mrp['MRP_LUNCHBREAK_END']=date("Y-m-d")." 23:59:59";
			$config_mrp['MRP_VAT_INCLUDE_SPECIAL']=1;

			$filename = "application/config/mrp_config.php";
			$file_content="<?php\n";
			foreach ($config_mrp as $key => $value) {
				$file_content.="$"."config_mrp['".$key."']='".$value."';\n";

			}
			$obj=fopen($filename, 'w');
			fwrite($obj, $file_content);
			fclose($obj);
		}

		header("Location: ".base_url());
	}
}

?>