<?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() {
		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();
	}

	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();

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

		if(!$pageWasRefreshed){

			$payment_type = $this->input->post('payment_type');

			$amount_tendered = $this->input->post('amount_tendered');
			$ac_no_check = $this->input->post('ac_no_check');
			$check_name = $this->input->post('check_name');
			$holder_name_credit = $this->input->post('holder_name_credit');
			$holder_name_debit = $this->input->post('holder_name_debit');
			$holder_name_check = $this->input->post('holder_name_check');
			$bank_name_check = $this->input->post('bank_name_check');
			$bank_name_credit = $this->input->post('bank_name_credit');
			$bank_name_debit = $this->input->post('bank_name_debit');
			$branch_name_check = $this->input->post('branch_name_check');
			$check_date = $this->input->post('check_date');
			$card_expire_year = $this->input->post('card_expire_year');
			$card_expire_month = $this->input->post('card_expire_month');
			$card_no_credit = $this->input->post('card_no_credit');
			$card_no_debit = $this->input->post('card_no_debit');

			$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 (!$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)) {
				$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) {
		$this->sale_lib->delete_payment($payment_id);
		//$this->sale_lib->clear_user_points();
		$this->_reload();
	}

	function add() {
		$data = array();
		$mode = $this->sale_lib->get_mode();

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

		if(!$pageWasRefreshed){

			$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"));
				}
			}

			//if(POINT_CARD_PERMISSION==1){
			$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,null,0,null,null,null,0,null,null,null,null,null,$this->input->post("item"))) {
				$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,$lot)) {
				//$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
			}
			
			foreach ($this->session->userdata['cart'] as $session_key => $session_value) {
				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 = array();
		$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");


		if ($this->form_validation->run() != FALSE) {
			$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))) {
			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
		}


		$this->_reload($data);
	}

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

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

	function new_card(){
		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
		if(!$pageWasRefreshed){
			$this->Sale->update_card();
		}
		$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');


				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;

					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'));
						}
					}
				}

				//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";



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

				$this->_reload($data);

			}
		}
	}


	function receipt_reprint($receipt_no){
		$sale_info = $this->Sale->get_info($this->Sale->get_sale_by_invoice_number_shawpon_local($receipt_no)->row()->sale_id)->row_array();

		$this->sale_lib->copy_entire_sale_shawpon($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['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['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;

		foreach ($this->sale_lib->get_payments() as $data_key => $data_value) {
			if($data_key=="Purchase Discount"){
				$data['purchase_discount_amount']=$data_value['payment_amount'];
			}else{
				$data['payments'][$data_key]=$data_value;
			}
		}


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

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

		$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($this->Sale->get_sale_by_invoice_number_shawpon_local($receipt_no)->row()->sale_id)->row_array();
		$this->sale_lib->copy_entire_sale_shawpon($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;

		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;
		$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']) - $total_payments ) > 1e-6 )) {
			return false;
		}

		return true;
	}

	function _reload($data = array()) {

		//Add Month in Dropdown

		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'), 'global' => $this->lang->line('sales_global'), 'global_delivery' => 'Global Delivery');
		$data['mode'] = $this->sale_lib->get_mode();
		$data['subtotal'] = $this->sale_lib->get_subtotal();
		$data['taxes'] = $this->sale_lib->get_taxes();
		$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['amount_due'] = round($this->sale_lib->get_amount_due());
		$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'];

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

			if($data['mode']=="global"){
				$data['payment_options'] = array(
				$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
				$this->lang->line('sales_check') => $this->lang->line('sales_check'),
				//$this->lang->line('sales_giftcard') => $this->lang->line('sales_giftcard'),
				$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
				$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
				'User Point' => 'User Point',
				'Purchase Bonus' => 'Purchase Bonus'
				);
			}else{

				$data['payment_options'] = array(
				$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
				$this->lang->line('sales_check') => $this->lang->line('sales_check'),
				//$this->lang->line('sales_giftcard') => $this->lang->line('sales_giftcard'),
				$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
				$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
				'User Point' => 'User Point',
				'Due' => 'Due',
				'Purchase Bonus' => 'Purchase Bonus'
				//$this->lang->line('sales_due') => $this->lang->line('sales_due')
				);

			}
		} else {
			$data['payment_options'] = array(
			$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
			$this->lang->line('sales_check') => $this->lang->line('sales_check'),
			//$this->lang->line('sales_giftcard') => $this->lang->line('sales_giftcard'),
			$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
			$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
			'Purchase Bonus' => 'Purchase Bonus'
			//'User Point' => 'User Point'
			);
		}

		$customer_id = $this->sale_lib->get_customer();

		if(isset($data['complete'])){
			$data['customer']="";
		}


		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['customer_state'] = $info->state;
			$data['previous_due'] = $this->Customer->customer_previous_due($customer_id);
			$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){
				if(trim($data['customer_gs_card']) AND trim($data['customer_state'])==""){
					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){
						$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;
				}

			}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['amount_due'] = round($data['amount_due']-$data['purchase_discount_amount']);

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


		$this->load->view("sales/register", $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();
		$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->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt) && $mode=='return')
			//		{
			//
			//			$this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
			//
			//		}
			//
			//		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);
			//		}
			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');
			}
			//
			//		if($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt))
			//		{
			//			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
			//		}
		}


		$this->_reload($data);
	}

	function completeSele() {

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

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


	function discount($percentage,$current_date){


		///http://localhost/gs_pos_uta_my/index.php/sales/discount/60/

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

		/*	START::SALES PRODUCT*/

		$query = $this->db->query("SELECT c.*,IF(a.item_size_id> 0, CONCAT(cat.description,'</br>',a.description,' - ',b.size), CONCAT(cat.description,'</br>',a.description)) AS name
									   FROM ospos_permission_exchange_trans AS c
									   LEFT JOIN stock_master AS a ON c.org_stock_id=a.stock_id
									   LEFT JOIN pos_item_sizes AS b ON a.item_size_id=b.id
									   LEFT JOIN stock_category AS cat ON a.category_id=cat.category_id
									   WHERE c.is_consider=0 AND c.is_sync=0 AND c.loc_code='".LOCATION_CODE."'");
		$sale_products=array();
		foreach ($query->result() as $row) {
			$sale_products[$row->sales_id][]=$row;
		}

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

			$total_amount=0;
			$total_vat=0;
			$total_permission=0;
			$total_permission_vat=0;
			$total_update=0;
			$total_update_vat=0;

			$has_discount=0;
			$discount_percentage=0;
			$discount_amount_root=0;
			$has_card=0;
			$has_cash=0;
			$calculative_purchase_discount_in_payment=0;
			$cash_out=0;
			$card_name="";
			$card_amount="";
			$cash_amount_root="";

			/*	Payment Amount */
			$query = $this->db->query("SELECT *
									   FROM ospos_sales_payments
									   WHERE sale_id='".$sale_key."'");
			$payment_array=array();

			foreach ($query->result() as $row_payment) {
				$payment_array[$row_payment->payment_type]=$row_payment->payment_amount;

				if($row_payment->payment_type=="Purchase Discount"){
					$has_discount=1;
					$discount_percentage=5;
					$discount_amount_root=$row_payment->payment_amount;
				}
				if($row_payment->payment_type=="Debit Card"){
					$has_card=1;
					$card_name="Debit Card";
					$card_amount=$row_payment->payment_amount;
				}if($row_payment->payment_type=="Credit Card"){
					$has_card=1;
					$card_name="Credit Card";
					$card_amount=$row_payment->payment_amount;
				}if($row_payment->payment_type=="Cash"){
					$has_cash=1;
					$cash_amount_root=$row_payment->payment_amount;
				}
			}

			$line_array=array();


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


			$total_purchase=0;

			$max_line=0;

			foreach ($query->result() as $row_line) {
				$line_array[$row_line->sale_id][$row_line->line]=$row_line;
				$total_purchase+=$row_line->vat_enable_price;
				if($max_line<=$row_line->line){
					$max_line=$row_line->line;
				}
			}

			$update_lines=array();
			$generated_lines=array();

			foreach ($sale_value as $sl_key => $sl_value) {

				$temp_line=$line_array[$sl_value->sales_id][$sl_value->line];



				$total_amount+=$temp_line->total_sale_amount;
				$total_vat+=$temp_line->vat_amount;

				if($sl_value->permission_quantity_purchased==$temp_line->quantity_purchased){

					$update_lines['sale_id']=$temp_line->sale_id;
					$update_lines['stock_id']=$sl_value->org_stock_id;
					$update_lines['description']=$sl_value->name;
					$update_lines['lot_no']=$sl_value->org_lot_no;
					$update_lines['line']=$temp_line->line;
					$update_lines['quantity_purchased']=$sl_value->permission_quantity_purchased;
					$update_lines['item_cost_price']=$sl_value->org_price;
					$update_lines['item_unit_price']=$sl_value->org_price;
					$update_lines['discount_percent']=$temp_line->discount_percent;
					$update_lines['total_discount']=number_format((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100,2,'.','');
					$update_lines['total_sale_amount']=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$update_lines['vat_enable_price']=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$update_lines['vat_percentage']=$temp_line->vat_percentage;
					$update_lines['vat_amount']=number_format(((($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');

					$total_permission+=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$total_permission_vat+=number_format(((($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');


				}else{
					$generated_lines['sale_id']=$temp_line->sale_id;
					$generated_lines['stock_id']=$sl_value->org_stock_id;
					$generated_lines['description']=$sl_value->name;
					$generated_lines['lot_no']=$sl_value->org_lot_no;
					$generated_lines['line']=$max_line+1;
					$generated_lines['quantity_purchased']=$sl_value->permission_quantity_purchased;
					$generated_lines['item_cost_price']=$sl_value->org_price;
					$generated_lines['item_unit_price']=$sl_value->org_price;
					$generated_lines['discount_percent']=$temp_line->discount_percent;
					$generated_lines['total_discount']=number_format((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100,2,'.','');
					$generated_lines['total_sale_amount']=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$generated_lines['vat_enable_price']=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$generated_lines['vat_percentage']=$temp_line->vat_percentage;
					$generated_lines['vat_amount']=number_format(((($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');

					$total_permission+=number_format(($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100),2,'.','');
					$total_permission_vat+=number_format(((($sl_value->permission_quantity_purchased*$sl_value->org_price)-((($sl_value->permission_quantity_purchased*$sl_value->org_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');

					$max_line++;

					$update_lines['sale_id']=$temp_line->sale_id;
					$update_lines['stock_id']=$temp_line->stock_id;
					$update_lines['description']=$temp_line->description;
					$update_lines['lot_no']=$temp_line->lot_no;
					$update_lines['line']=$temp_line->line;
					$update_lines['quantity_purchased']=$temp_line->quantity_purchased-$sl_value->permission_quantity_purchased;
					$update_lines['item_cost_price']=$temp_line->item_cost_price;
					$update_lines['item_unit_price']=$temp_line->item_unit_price;
					$update_lines['discount_percent']=$temp_line->discount_percent;
					$update_lines['total_discount']=number_format(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100,2,'.','');
					$update_lines['total_sale_amount']=number_format((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)-(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100),2,'.','');
					$update_lines['vat_enable_price']=number_format((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)-(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100),2,'.','');
					$update_lines['vat_percentage']=$temp_line->vat_percentage;
					$update_lines['vat_amount']=number_format((((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)-(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');


					$total_update+=number_format((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)-(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100),2,'.','');
					$total_update_vat+=number_format((((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)-(((($temp_line->quantity_purchased-$sl_value->permission_quantity_purchased)*$temp_line->item_unit_price)*$temp_line->discount_percent)/100))*$temp_line->vat_percentage)/100,2,'.','');

				}

				if(count($update_lines)){

					if(intval($update_lines['sale_id'])){
						$this->db->query(" UPDATE ospos_sales_items SET
							stock_id='".$update_lines['stock_id']."',
							description='".$update_lines['description']."',
							lot_no='".$update_lines['lot_no']."',
							quantity_purchased='".$update_lines['quantity_purchased']."',
							item_cost_price='".$update_lines['item_cost_price']."',
							item_unit_price='".$update_lines['item_unit_price']."',
							discount_percent='".$update_lines['discount_percent']."',
							total_discount='".$update_lines['total_discount']."',
							total_sale_amount='".$update_lines['total_sale_amount']."',
							vat_enable_price='".$update_lines['vat_enable_price']."',
							vat_percentage='".$update_lines['vat_percentage']."',
							vat_amount='".$update_lines['vat_amount']."'
							WHERE sale_id='".$update_lines['sale_id']."' AND line='".$update_lines['line']."'");
					}
				}

				if(count($generated_lines)){

					if(intval($generated_lines['sale_id'])){
						$this->db->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)
						VALUES(
						'".$generated_lines['sale_id']."',
						'".$generated_lines['stock_id']."',
						'".$generated_lines['description']."',
						'".$generated_lines['lot_no']."',
						'".$generated_lines['line']."',
						'".$generated_lines['quantity_purchased']."',
						'".$generated_lines['item_cost_price']."',
						'".$generated_lines['item_unit_price']."',
						'".$generated_lines['discount_percent']."',
						'".$generated_lines['total_discount']."',
						'".$generated_lines['total_sale_amount']."',
						'".$generated_lines['vat_enable_price']."',
						'".$generated_lines['vat_percentage']."',
						'".$generated_lines['vat_amount']."')");
					}

				}
				$calculative_purchase_discount=0;

				if($has_discount==1){
					$calculative_purchase_discount=($sl_value->calculative_total_sale_amount*$discount_percentage)/100;
					$calculative_purchase_discount_in_payment+=$calculative_purchase_discount;
				}
				$cash_out+=$sl_value->calculative_total-$calculative_purchase_discount;

				$this->db->query("UPDATE ospos_permission_exchange_trans SET calculative_purchase_discount='".$calculative_purchase_discount."',
					calculative_total=calculative_total-'".$calculative_purchase_discount."',is_consider=1
					WHERE id='".$sl_value->id."'");

			}

			if($has_discount==1){
				$this->db->query("UPDATE ospos_sales_payments SET payment_amount=payment_amount-'".round($calculative_purchase_discount_in_payment)."'
					WHERE sale_id='".$sale_key."' AND payment_type='Purchase Discount'");
			}

			if($has_card==1){
				if($has_cash==1){
					$this->db->query("UPDATE ospos_sales_payments SET payment_amount=payment_amount-'".round($cash_out)."'
										  WHERE sale_id='".$sale_key."' AND payment_type='Cash'");
				}else{
					$this->db->query("INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount) VALUES('".$sale_key."','Cash','-".round($cash_out)."')");
				}
				if($has_discount==1){
					$payment_type_text=$card_name.": ".number_format($card_amount,2,'.','')."&nbsp;BDT<br />Purchase Discount: ".number_format($discount_amount_root-round($calculative_purchase_discount_in_payment),2,'.','')."&nbsp;BDT<br />";
				}else{
					$payment_type_text=$card_name.": ".number_format($card_amount,2,'.','')."&nbsp;BDT<br />";
				}

			}else{
				if($has_cash==1){
					$this->db->query("UPDATE ospos_sales_payments SET payment_amount=payment_amount-'".round($cash_out)."'
										  WHERE sale_id='".$sale_key."' AND payment_type='Cash'");
				}else{
					$this->db->query("INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount) VALUES('".$sale_key."','Cash','-".round($cash_out)."')");
				}


				if($has_discount==1){
					$payment_type_text="Cash: ".number_format($cash_amount_root-round($cash_out),2,'.','')."&nbsp;BDT<br />Purchase Discount: ".number_format($discount_amount_root-round($calculative_purchase_discount_in_payment),2,'.','')."&nbsp;BDT<br />";
				}else{
					$payment_type_text="Cash: ".number_format($cash_amount_root-round($cash_out),2,'.','')."&nbsp;BDT<br />";
				}
			}
			$this->db->query("
					UPDATE ospos_sales SET
					payment_type='".mysql_real_escape_string($payment_type_text)."'
					WHERE sale_id='".$sale_key."'");

		}

		if(POINT_CARD_PERMISSION==1){
			if(intval($percentage)<=40){
				$percentage=40;
			}

			/*	START::NON CUSTOMER SALES*/


			if(trim($current_date)==""){
				$current_date=date("Y-m-d");
			}
			$query = $this->db->query("
					SELECT a.sale_time,a.sale_id,a.payment_type as pay_type,c.id as customer_id,c.gs_card_no,b.*
					FROM ospos_sales AS a
					LEFT JOIN ospos_sales_payments AS b ON a.sale_id=b.sale_id
					LEFT JOIN pos_ospos_customers AS c ON a.customer_id=c.id
					WHERE b.payment_type IN('Cash','Purchase Discount') AND DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND a.is_sync=0 AND is_permission=0
					AND b.payment_amount<'".POINT_FOR_CARD."' ORDER BY a.sale_id");

			$my_discount=array();

			$sales_all_data=array();


			foreach ($query->result() as $row) {
				if(intval($row->customer_id)==0){
					if($row->payment_type=="Cash"){
						$my_discount[$row->sale_id] = $row->payment_amount;
					}
					if($row->payment_type=="Purchase Discount"){
						$my_discount[$row->sale_id] = 0;
					}
					$query=$this->db->query("
					UPDATE ospos_sales
					SET is_permission='2'
					WHERE sale_id='".$row->sale_id."'");
				}
				$sales_all_data[$row->sale_id]=$row;
			}

			$my_discount_final=array();
			$total_my_discount_amount=0;
			foreach ($my_discount as $key => $value) {
				if($value>0){
					$my_discount_final[$key]=$value;
					$total_my_discount_amount+=$value;
				}
			}


			if($percentage<=100){
				$not_more_than_total_my_discount_amount=($total_my_discount_amount*$percentage)/100;
			}else{
				$not_more_than_total_my_discount_amount=$total_my_discount_amount;
			}

			$my_discount_final_index=array();

			foreach ($my_discount_final as $key => $value) {
				$my_discount_final_index[]=$key;
			}
			shuffle($my_discount_final_index);

			$consider_amount=0;

			$tobe_shift_sales_id_array=array();

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

				if($consider_amount<=$not_more_than_total_my_discount_amount){
					$tobe_shift_sales_id_array[]=$value;
					$consider_amount+=$my_discount_final[$value];
				}else{
					$tobe_shift_sales_id_array[]=$value;
					$consider_amount+=$my_discount_final[$value];
					break;
				}
			}



			/*	ALL Customers	*/
			$query = $this->db->query("SELECT * FROM pos_ospos_customers WHERE gs_card_no!='' AND is_dealer='Retail' AND loc_code!='CST'");
			$my_discount_customer=array();
			$my_discount_customer_details=array();

			foreach ($query->result() as $row) {
				$my_discount_customer[]=$row->id;
				$my_discount_customer_details[$row->id]=$row->point;
			}

			shuffle($my_discount_customer);

			$serial=0;
			foreach ($tobe_shift_sales_id_array as $key => $value) {


				$discount_points_amount=$my_discount_customer_details[$my_discount_customer[$serial]]*100;

				$discount_percentage=FIRST_DISCOUNT_PERCENTAGE;
				if($discount_points_amount>=POINT_FOR_SECOND_DISCOUNT_START_GTHAN){
					$discount_percentage=SECOND_DISCOUNT_PERCENTAGE;
				}

				$query = $this->db->query("SELECT SUM(total_sale_amount) AS total_amount,SUM(vat_amount) as total_vat
									   FROM ospos_sales_items WHERE sale_id='".$value."'");

				$total_sale_price=0;
				$total_vat_amout=0;
				foreach ($query->result() as $row) {
					$total_sale_price=$row->total_amount;
					$total_vat_amout=$row->total_vat;
				}

				$purchase_discount_amount=round(($total_sale_price*$discount_percentage)/100);
				$cash_amount=round($total_sale_price-$purchase_discount_amount)+$total_vat_amout;

				$payment_type_text="Cash: ".number_format($cash_amount,2,'.','')."&nbsp;BDT<br />Purchase Discount: ".number_format($purchase_discount_amount,2,'.','')."&nbsp;BDT<br />";

				$query = $this->db->query("
					INSERT INTO ospos_permissions_relations(
					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."',
					'".$sales_all_data[$value]->sale_time."',
					'".$value."',
					'".$my_discount_customer[$serial]."',
					'".$sales_all_data[$value]->customer_id."',
					'".$sales_all_data[$value]->pay_type."',
					'".$sales_all_data[$value]->payment_amount."',
					'0',
					'".$cash_amount."',
					'".$purchase_discount_amount."',
					'".$purchase_discount_amount."',
					'0')");



				$query=$this->db->query("
					UPDATE ospos_sales
					SET customer_id='".$my_discount_customer[$serial]."',
					payment_type='".mysql_real_escape_string($payment_type_text)."',
					is_permission='1'
					WHERE sale_id='".$value."'");


				$query=$this->db->query("
					DELETE FROM  ospos_sales_payments
					WHERE sale_id='".$value."'");



				$query = $this->db->query("
					INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$value."',
					'Cash',
					'".number_format($cash_amount,2,'.','')."')");

				$query = $this->db->query("
					INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$value."',
					'Purchase Discount',
					'".number_format($purchase_discount_amount,2,'.','')."')");

				$serial++;
			}
			/*	END::NON CUSTOMER SALES*/

			/*	START::NEW CUSTOMER SALES */

			$query = $this->db->query("
					SELECT a.sale_time,a.sale_id,a.payment_type as pay_type,c.id as customer_id,c.gs_card_no,b.*
					FROM ospos_sales AS a
					LEFT JOIN ospos_sales_payments AS b ON a.sale_id=b.sale_id
					LEFT JOIN pos_ospos_customers AS c ON a.customer_id=c.id
					WHERE b.payment_type IN('Cash','Purchase Discount') AND DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND a.is_sync=0 AND is_permission=0
					AND c.state !='' ORDER BY a.sale_id");

			$my_discount_new_card_cash=array();
			$my_discount_new_card_purchase_discount=array();

			$sales_all_new_data=array();

			foreach ($query->result() as $row) {
				if($row->payment_type=="Cash"){
					$my_discount_new_card_cash[$row->sale_id] = $row->payment_amount;
				}
				if($row->payment_type=="Purchase Discount"){
					$my_discount_new_card_purchase_discount[$row->sale_id] = $row->payment_amount;
				}

				$query=$this->db->query("
			UPDATE ospos_sales
			SET is_permission='2'
			WHERE sale_id='".$row->sale_id."'");
				$sales_all_new_data[$row->sale_id]=$row;
			}



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

				$real_total=$value+$my_discount_new_card_purchase_discount[$key];
				$frist_slot_discount=100;
				$second_slot_discount=0;
				if(($my_discount_new_card_purchase_discount[$key]+$value)>=5000){
					$second_slot_discount=(($value-2000)*3)/100;
				}
				$final_purchase_discount_amount=round($my_discount_new_card_purchase_discount[$key]+$frist_slot_discount+$second_slot_discount);
				$final_cash_amount=$real_total-$final_purchase_discount_amount;


				$payment_type_text="Cash: ".number_format($final_cash_amount,2,'.','')."&nbsp;BDT<br />Purchase Discount: ".number_format($final_purchase_discount_amount,2,'.','')."&nbsp;BDT<br />";


				$query = $this->db->query("
			INSERT INTO ospos_permissions_relations(
			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."',
			'".$sales_all_new_data[$key]->sale_time."',
			'".$key."',
			'".$sales_all_new_data[$key]->customer_id."',
			'".$sales_all_new_data[$key]->customer_id."',
			'".$sales_all_new_data[$key]->pay_type."',
			'".$value."',
			'".$my_discount_new_card_purchase_discount[$key]."',
			'".$final_cash_amount."',
			'".$final_purchase_discount_amount."',
			'".($final_purchase_discount_amount-$my_discount_new_card_purchase_discount[$key])."',
			'0')");

				$query=$this->db->query("
			UPDATE ospos_sales
			SET payment_type='".mysql_real_escape_string($payment_type_text)."',
			is_permission='1'
			WHERE sale_id='".$key."'");

				$query=$this->db->query("
			DELETE FROM  ospos_sales_payments
			WHERE sale_id='".$key."'");



				$query = $this->db->query("
			INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
			VALUES('".$key."',
			'Cash',
			'".number_format($final_cash_amount,2,'.','')."')");

				$query = $this->db->query("
			INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
			VALUES('".$key."',
			'Purchase Discount',
			'".number_format($final_purchase_discount_amount,2,'.','')."')");
			}

			/*	END::NEW CUSTOMER SALES */


			/*	START::OLD CUSTOMER SALES */

			$query = $this->db->query("
					SELECT a.sale_time,a.sale_id,a.payment_type as pay_type,c.id as customer_id,c.gs_card_no,b.*
					FROM ospos_sales AS a
					LEFT JOIN ospos_sales_payments AS b ON a.sale_id=b.sale_id
					LEFT JOIN pos_ospos_customers AS c ON a.customer_id=c.id
					WHERE b.payment_type IN('Cash','Purchase Discount') AND DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND a.is_sync=0 AND is_permission=0
					AND c.state ='' ORDER BY a.sale_id");

			$my_discount_old_card_cash=array();
			$my_discount_old_card_purchase_discount=array();

			$sales_all_old_data=array();

			foreach ($query->result() as $row) {
				if($row->payment_type=="Cash"){

					if($row->payment_amount>=3000){

						$my_discount_old_card_cash[$row->sale_id] = $row->payment_amount;
					}
				}
				if($row->payment_type=="Purchase Discount"){
					$my_discount_old_card_purchase_discount[$row->sale_id] = $row->payment_amount;
				}
				/*
				$query=$this->db->query("
				UPDATE ospos_sales
				SET is_permission='2'
				WHERE sale_id='".$row->sale_id."'");*/

				$sales_all_old_data[$row->sale_id]=$row;
			}


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

				$real_total_old=$value+$my_discount_old_card_purchase_discount[$key];
				$frist_slot_discount_old=0;
				$second_slot_discount_old=0;
				$second_slot_discount_old=(($value-2000)*3)/100;

				$final_purchase_discount_amount_old=round($my_discount_old_card_purchase_discount[$key]+$frist_slot_discount_old+$second_slot_discount_old);
				$final_cash_amount_old=$real_total_old-$final_purchase_discount_amount_old;

				$payment_type_text="Cash: ".number_format($final_cash_amount_old,2,'.','')."&nbsp;BDT<br />Purchase Discount: ".number_format($final_purchase_discount_amount_old,2,'.','')."&nbsp;BDT<br />";


				$query = $this->db->query("
			INSERT INTO ospos_permissions_relations(
			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."',
			'".$sales_all_old_data[$key]->sale_time."',
			'".$key."',
			'".$sales_all_old_data[$key]->customer_id."',
			'".$sales_all_old_data[$key]->customer_id."',
			'".$sales_all_old_data[$key]->pay_type."',
			'".$value."',
			'".$my_discount_old_card_purchase_discount[$key]."',
			'".$final_cash_amount_old."',
			'".$final_purchase_discount_amount_old."',
			'".($final_purchase_discount_amount_old-$my_discount_old_card_purchase_discount[$key])."',
			'0')");


				$query=$this->db->query("
			UPDATE ospos_sales
			SET payment_type='".mysql_real_escape_string($payment_type_text)."',
			is_permission='1'
			WHERE sale_id='".$key."'");

				$query=$this->db->query("
			DELETE FROM  ospos_sales_payments
			WHERE sale_id='".$key."'");



				$query = $this->db->query("
			INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
			VALUES('".$key."',
			'Cash',
			'".number_format($final_cash_amount_old,2,'.','')."')");

				$query = $this->db->query("
			INSERT INTO ospos_sales_payments(sale_id,payment_type,payment_amount)
			VALUES('".$key."',
			'Purchase Discount',
			'".number_format($final_purchase_discount_amount_old,2,'.','')."')");
			}

			/*	END::OLD CUSTOMER SALES */

			echo "<pre>";
			print_r("DONE");
			echo "</pre>";
			exit();
		}
	}
}

?>