<?php

class Sale extends CI_Model {

	public function get_info($sale_id) {
		$this->db->from('sales');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}
	public function get_info_reprint($sale_id) {
		$this->db->from('sales_reprint');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}

	function exists($sale_id) {
		$this->db->from('sales');
		$this->db->where('sale_id', $sale_id);
		$query = $this->db->get();

		return ($query->num_rows() == 1);
	}

	function update($sale_data, $sale_id) {
		$this->db->where('sale_id', $sale_id);
		$success = $this->db->update('sales', $sale_data);

		return $success;
	}
	function update_card() {

		$success = $this->db->query("UPDATE pos_ospos_customers SET gs_card_no='".mysql_real_escape_string($_POST['new_card_number'])."',state='".mysql_real_escape_string($_POST['new_card_number'])."', point=0
					WHERE id='".mysql_real_escape_string($_POST['customer_gs_id'])."' AND gs_card_no=''");

		$success = $this->db->query("UPDATE ospos_people SET state='".mysql_real_escape_string($_POST['new_card_number'])."'
					WHERE person_id='".mysql_real_escape_string($_POST['customer_gs_id'])."'");

		return $success;
	}


	function save($items, $customer_id, $employee_id, $comment, $payments, $sale_id = false, $receive_location, $location,$data) {


		if (count($items) == 0)
		return -1;

		//Alain Multiple payments
		//Build payment types string
		$payment_types = '';
		$current_due = 0;
		$current_use_point = 0;

		$tax_percentage=0;
		foreach ($data['item_tax'] as $txkey => $txvalue) {
			$tax_percentage=$txvalue;
		}
		$tax_amount=round(($data['total']*$tax_percentage)/100);


		$total_receipt_amount=$data['final_due']+$data['total']+$tax_amount;

		$return_amount=$data['previous_due']-$total_receipt_amount-$data['purchase_discount_amount'];

		//$return_amount


		if($data['final_due']<0){
			$payment_types = $payment_types . "Deduct Advance Payment: " . to_currency(abs($data['final_due'])) . '<br />';
		}
		if($data['final_due']>0){
			$payment_types = $payment_types . "Previous Due Payment: " . to_currency($data['final_due']) . '<br />';
		}

		foreach ($payments as $payment_id => $payment) {

			if ($payment['payment_type'] == "Due") {
				$current_due=$payment['payment_amount'];
				$payment_types = $payment_types . $payment['payment_type'] . ': ' . to_currency($payment['payment_amount']) . '<br />';
			}else{
				if($return_amount>0){
					if ($payment['payment_type'] == "Cash"){
						$payment_types = $payment_types . "Paid Cash" . ': ' . to_currency($payment['payment_amount']-$return_amount) . '<br />';
					}
				}
				if ($payment['payment_type'] == "User Point"){
					if($data['cart_point']>0){
						$payment_types = $payment_types . $payment['payment_type'] . ': ('.$data['cart_point'].'*'.$data['cart_point_value'].') '. to_currency($data['cart_point_cost']) . '<br />';
					}
				}else{
					$payment_types = $payment_types . $payment['payment_type'] . ': ' . to_currency($payment['payment_amount']) . '<br />';
				}
			}
		}







		if(doubleval($data['purchase_discount_amount'])>0){

			$payment_types = $payment_types . "Purchase Discount" . ': ' . to_currency($data['purchase_discount_amount']) . '<br />';


		}

		if($data['mode']=="global"){
			if(trim($receive_location)==""){
				$receive_location=LOCATION_CODE;
			}
			$receipt_no=LOCATION_CODE.date("ymdHis")."GS";
		}else{
			if(trim($receive_location)==""){
				$receive_location=$location;
			}
			$receipt_no=LOCATION_CODE.date("ymdHis");
		}


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

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

			$sales_data = array(
			'sale_time' => date('Y-m-d H:i:s'),
			'customer_id' => $this->Customer->exists($customer_id) ? $customer_id : null,
			'employee_id' => $employee_id,
			'payment_type' => $payment_types,
			'comment' => $comment,
			'receive_location' => $receive_location,
			'location' => $location,
			'receipt_no' => $receipt_no,
			'acc_location' => LOCATION_CODE,
			'is_global' => 1,
			'bag_big'=>$_POST['bag_big'],
			'bag_medium'=>$_POST['bag_medium'],
			'bag_small'=>$_POST['bag_small']
			);

			$this->db->insert('sales', $sales_data);
			$sale_id = $this->db->insert_id();

		}else{

			if(trim($location)==""){
				$location=LOCATION_CODE;
			}
			$sales_data = array(
			'sale_time' => date('Y-m-d H:i:s'),
			'customer_id' => $this->Customer->exists($customer_id) ? $customer_id : null,
			'employee_id' => $employee_id,
			'payment_type' => $payment_types,
			'comment' => $comment,
			'receive_location' => $receive_location,
			'location' => $location,
			'receipt_no' => $receipt_no,
			'acc_location' => $location,
			'bag_big'=>$_POST['bag_big'],
			'bag_medium'=>$_POST['bag_medium'],
			'bag_small'=>$_POST['bag_small']
			);

			$this->db->insert('sales', $sales_data);
			$sale_id = $this->db->insert_id();

		}
		$sale_id_for_coupon = $sale_id;

		if(intval($_POST['bag_big'])>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sale_id,
			'stock_id' => BIG_BAG_CODE,
			'type' => 201,
			'loc_code' => $location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($_POST['bag_big']),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$this->db->insert('stock_moves', $stock_moves_data);
		}
		if(intval($_POST['bag_medium'])>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sale_id,
			'stock_id' => MEDIUM_BAG_CODE,
			'type' => 201,
			'loc_code' => $location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($_POST['bag_medium']),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$this->db->insert('stock_moves', $stock_moves_data);
		}
		if(intval($_POST['bag_small'])>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sale_id,
			'stock_id' => SMALL_BAG_CODE,
			'type' => 201,
			'loc_code' => $location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($_POST['bag_small']),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$this->db->insert('stock_moves', $stock_moves_data);
		}

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

		$tax_array=$this->sale_lib->get_taxes();

		$total_point_amount=0;



		$last_item_details_data=array();
		$total_sale_amount_skb=0;
		$total_vat_skb=0;

		$vat_enable_price_for_coupon=0;

		foreach ($items as $line => $item) {

			$item_discount=0;
			$total_discount=0;


			$item_discount=0;

			if($item['discount']>0){
				$item_discount=($item['price']*$item['discount'])/100;
				//$total_discount=($item['price']*$item['quantity']*$item['discount'])/100;
			}


			//$vat_amount_shawpon=((($item['price']-$item_discount)*$item['quantity'])*$item['vat_rate'])/100;
			$vat_amount_shawpon=((($item['price']-$item_discount)*$item['quantity'])*$item['vat_rate'])/100;
			$total_sale_amount_shawpon=($item['price']-$item_discount)*$item['quantity'];

			//$total_sale_amount_with_vat_shawpon=$item['price_with_vat']*$item['quantity'];

			//$total_discount=$total_sale_amount_with_vat_shawpon-$total_sale_amount_shawpon-$vat_amount_shawpon;//15012017 :: START shawpon@gmail.com
			//$total_discount=$total_sale_amount_with_vat_shawpon-$total_sale_amount_shawpon;//18-04-2017



			if($item['vat_rate']==0){

				$sales_items_data = array(
				'sale_id' => $sale_id,
				'stock_id' => $item['item_id'],
				'description' => $item['name'],
				'lot_no' => $item['lot_no'],
				'line' => $item['line'],
				'quantity_purchased' => $item['quantity'],
				'item_cost_price' => $item['price'],
				'item_unit_price' => $item['price']-$item_discount,
				'discount_percent' => $item['discount'],
				'total_discount' => ($item_discount*$item['quantity']),
				'total_sale_amount' => $total_sale_amount_shawpon,
				//'vat_enable_price' => ($item['price']-$item_discount)*$item['quantity'],
				'vat_enable_price' => $item['price']*$item['quantity'],
				'vat_percentage' => $item['vat_rate'],
				'vat_amount' => $vat_amount_shawpon,
				'sales_employee_code' => $item['serialnumber'],////START::22-12-2018
				'vat_enable_price_after_discount' =>'0.00'
				);
			}else{


				$sales_items_data = array(
				'sale_id' => $sale_id,
				'stock_id' => $item['item_id'],
				'description' => $item['name'],
				'lot_no' => $item['lot_no'],
				'line' => $item['line'],
				'quantity_purchased' => $item['quantity'],
				'item_cost_price' => $item['price'],
				'item_unit_price' => $item['price']-$item_discount,
				'discount_percent' => $item['discount'],
				'total_discount' => ($item_discount*$item['quantity']),
				'total_sale_amount' => $total_sale_amount_shawpon,
				//'vat_enable_price' => ($item['price']-$item_discount)*$item['quantity'],
				'vat_enable_price' => $item['price']*$item['quantity'],
				'vat_percentage' => $item['vat_rate'],
				'vat_amount' => $vat_amount_shawpon,
				'sales_employee_code' => $item['serialnumber'],////START::22-12-2018
				'vat_enable_price_after_discount' => $total_sale_amount_shawpon
				);
			}

			$vat_enable_price_for_coupon = round($item['price']*$item['quantity']);

			$total_sale_amount_skb+=$total_sale_amount_shawpon;
			$total_vat_skb+=$vat_amount_shawpon;

			$this->db->insert('sales_items', $sales_items_data);

			if($item['quantity']>0){

				$item['sale_id']=$sale_id;
				if($item['vat_rate']==0){
					$item['vat_enable_price_after_discount']='0.00';
				}else{
					$item['vat_enable_price_after_discount']=$total_sale_amount_shawpon;
				}
				$last_item_details_data=$item;
			}

			$total_point_amount+=$total_sale_amount_shawpon;

			if($data['mode']=="global"){
				$this->db->set_dbprefix('');
				$stock_moves_data = array(
				'trans_no' => $sale_id,
				'stock_id' => $item['item_id'],
				'type' => 201,
				'loc_code' => $location,
				'tran_date' => date('Y-m-d H:i:s'),
				'person_id' => $sale_id,
				'price' => $item['price_with_vat'],
				'reference' => $receipt_no,
				'qty' => -$item['quantity'],
				'discount_percent' => $item['discount'],
				'standard_cost' => $item['price_with_vat'],
				'visible' => 1,
				'lot_no' => $item['lot_no'],
				'is_imported' => 0,
				'swatch_code' =>0
				);
				$this->db->insert('stock_moves', $stock_moves_data);

				$this->db->set_dbprefix('ospos_');
			}else{
				$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves AS a
					WHERE a.stock_id='".mysql_real_escape_string($item['item_id'])."' AND a.lot_no='".mysql_real_escape_string($item['lot_no'])."' AND a.price='".mysql_real_escape_string($item['price'])."' GROUP BY a.stock_id,a.lot_no,a.price");

				$stock_moves_lot_data=$query_moves->row();

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

				$stock_moves_data = array(
				'trans_no' => $sale_id,
				'stock_id' => $item['item_id'],
				'type' => 201,
				'loc_code' => $location,
				'tran_date' => date('Y-m-d H:i:s'),
				'person_id' => $sale_id,
				'price' => $stock_moves_lot_data->price,
				'reference' => $receipt_no,
				'qty' => -$item['quantity'],
				'discount_percent' => $item['discount'],
				'standard_cost' => $stock_moves_lot_data->standard_cost,
				'visible' => $stock_moves_lot_data->visible,
				'lot_no' => $item['lot_no'],
				'is_imported' => $stock_moves_lot_data->is_imported,
				'swatch_code' => $stock_moves_lot_data->swatch_code
				);
				$this->db->insert('stock_moves', $stock_moves_data);

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


		//$last_item_details_data
		if(doubleval($data['purchase_discount_amount'])>0){


			if($last_item_details_data['vat_enable_price_after_discount']==0){
				$total_sale_amount_suma='0.00';
			}else{
				$total_sale_amount_suma=number_format(($last_item_details_data['vat_enable_price_after_discount']-($total_sale_amount_skb-$data['total'])), 2,".","");
			}

			$coupon_discount_consider_total=0;
			$coupon_discount_consider_vat_total=0;

			if(trim($data['coupon_card_number'])!="" && intval($data['coupon_card_number'])!=0){

				if(intval($data['coupon_card_discout'])>0){
					$coupon_discount_consider_total=round((($data['coupon_card_discout']/107.5)*100));
					$coupon_discount_consider_vat_total=round((($coupon_discount_consider_total*7.5)/100),2);
				}
			}

			$vat_amount_real_suma=number_format(($total_sale_amount_suma*$last_item_details_data['vat_rate'])/100, 2,".","");
			$total_sale_amount_suma=$total_sale_amount_suma-$coupon_discount_consider_total;
			$vat_amount_real_suma=$vat_amount_real_suma-$coupon_discount_consider_vat_total;

			$this->db->query("
                    UPDATE ospos_sales_items
                    SET  vat_enable_price_after_discount='".mysql_real_escape_string($total_sale_amount_suma)."'
					,vat_amount='".mysql_real_escape_string($vat_amount_real_suma)."'
                    WHERE sale_id='".mysql_real_escape_string($last_item_details_data['sale_id'])."' AND line='".mysql_real_escape_string($last_item_details_data['line'])."'");
		}else{
			$coupon_discount_consider_total=0;
			$coupon_discount_consider_vat_total=0;

			if(trim($data['coupon_card_number'])!="" && intval($data['coupon_card_number'])!=0){

				if(intval($data['coupon_card_discout'])>0){

					if($last_item_details_data['vat_enable_price_after_discount']==0){
						$total_sale_amount_suma='0.00';
					}else{
						$total_sale_amount_suma=number_format(($last_item_details_data['vat_enable_price_after_discount']), 2,".","");
					}

					$vat_amount_real_suma=number_format(($total_sale_amount_suma*$last_item_details_data['vat_rate'])/100, 2,".","");

					$coupon_discount_consider_total=round((($data['coupon_card_discout']/107.5)*100));
					$coupon_discount_consider_vat_total=round((($coupon_discount_consider_total*7.5)/100),2);

					$total_sale_amount_suma=$total_sale_amount_suma-$coupon_discount_consider_total;
					$vat_amount_real_suma=$vat_amount_real_suma-$coupon_discount_consider_vat_total;

					$this->db->query("
                    UPDATE ospos_sales_items
                    SET  vat_enable_price_after_discount='".mysql_real_escape_string($total_sale_amount_suma)."'
					,vat_amount='".mysql_real_escape_string($vat_amount_real_suma)."'
                    WHERE sale_id='".mysql_real_escape_string($last_item_details_data['sale_id'])."' AND line='".mysql_real_escape_string($last_item_details_data['line'])."'");
				}
			}
		}


		if($data['final_due']<0){
			$sales_payments_data = array
			(
			'sale_id' => $sale_id,
			'payment_type' => 'Deduct Advance Payment',
			'payment_amount' => abs($data['final_due'])
			);
			$this->db->insert('sales_payments', $sales_payments_data);

		}

		$special_purchase_discount=0;/////////////////////FOR SPECIAL///////////////////

		foreach ($payments as $payment_id => $payment) {

			if ($payment['payment_type'] == 'User Point') {
				if($data['cart_point_cost']>0){
					$sales_payments_data = array
					(
					'sale_id' => $sale_id,
					'payment_type' => $payment['payment_type'],
					'payment_amount' => $data['cart_point_cost']
					);
					$this->db->insert('sales_payments', $sales_payments_data);
				}
			}
			if ($payment['payment_type'] == 'Due') {
				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount']
				);
				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'Purchase Bonus') {
				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount']
				);
				$this->db->insert('sales_payments', $sales_payments_data);
				$special_purchase_discount=$payment['payment_amount'];/////////////////////FOR SPECIAL///////////////////
			}

			if ($payment['payment_type'] == 'Credit Card') {
				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'bank_id' => $payment['bank_name_credit'],
				'branch_name' => $payment['branch_name_check'],
				'account_no' => $payment['ac_no_check'],
				'card_no' => $payment['card_no_credit'],
				'account_holder_name' => $payment['holder_name_credit'],
				'credit_card_expire_month' => $payment['card_expire_month'],
				'credit_card_expire_year' => $payment['card_expire_year']
				);
				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'OkWallet') {
				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'account_no' => $payment['ac_no_check']
				);
				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'AMEX Card') {
				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'bank_id' => $payment['bank_name_credit'],
				'branch_name' => $payment['branch_name_check'],
				'card_no' => $payment['card_no_credit'],
				'account_no' => $payment['ac_no_check'],
				'account_holder_name' => $payment['holder_name_credit'],
				'credit_card_expire_month' => $payment['card_expire_month'],
				'credit_card_expire_year' => $payment['card_expire_year']
				);
				$this->db->insert('sales_payments', $sales_payments_data);
			}


			if ($payment['payment_type'] == 'Debit Card') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'bank_id' => $payment['bank_name_debit'],
				'branch_name' => $payment['branch_name_check'],
				'card_no' => $payment['card_no_debit'],
				'account_no' => $payment['ac_no_check'],
				'account_holder_name' => $payment['holder_name_debit']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'Cash Return') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'account_no' => $payment['transaction_phone_no_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'BKash') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'account_no' => $payment['transaction_phone_no_bkash'],
				'card_no' => $payment['transaction_payment_id_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}if ($payment['payment_type'] == 'BKash Apps') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'account_no' => $payment['transaction_phone_no_bkash'],
				'card_no' => $payment['transaction_payment_id_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'Nagad') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'account_no' => $payment['transaction_phone_no_bkash'],
				'card_no' => $payment['transaction_payment_id_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}if ($payment['payment_type'] == 'Others') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['transaction_phone_no_bkash'],
				'payment_amount' =>$payment['payment_amount'],
				'account_no' => '',
				'card_no' => $payment['transaction_payment_id_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'Bkash Discount') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => $payment['payment_amount'],
				'account_no' => $payment['transaction_phone_no_bkash'],
				'card_no' => $payment['transaction_payment_id_bkash']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'COD Pathao') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_cod']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'RedX') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_redx']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'Paperfly') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_paperfly']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'SSL COMMERZ') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_ssl']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}


			if ($payment['payment_type'] == 'Ajkerdeal') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_ssl']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'Priyoshop') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_ssl']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'Buymobile') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_ssl']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}
			if ($payment['payment_type'] == 'DARAZ') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'card_no' => $payment['transaction_payment_id_ssl']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

			if ($payment['payment_type'] == 'Check') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' =>$payment['payment_amount'],
				'branch_name' => $payment['branch_name_check'],
				'bank_id' => $payment['bank_name_check'],
				'account_no' => $payment['ac_no_check'],
				'account_holder_name' => $payment['holder_name_check'],
				'check_no' => $payment['card_expire_month'],
				'check_date' => $payment['check_date']
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}



			if ($payment['payment_type'] == 'Cash') {

				$sales_payments_data = array
				(
				'sale_id' => $sale_id,
				'payment_type' => $payment['payment_type'],
				'payment_amount' => ($payment['payment_amount']+$data['refund_amount']-intval($data['coupon_card_discout']))
				);

				$this->db->insert('sales_payments', $sales_payments_data);
			}

		}
		if(doubleval($data['purchase_discount_amount'])>0){

			$coupon_discount_consider_total=0;
			$coupon_discount_consider_vat_total=0;

			if(trim($data['coupon_card_number'])!="" && intval($data['coupon_card_number'])!=0){
				if(intval($data['coupon_card_discout'])>0){
					$coupon_discount_consider_total=round((($data['coupon_card_discout']/107.5)*100));
				}
			}

			$sales_payments_data = array
			(
			'sale_id' => $sale_id,
			'payment_type' => "Purchase Discount",
			'payment_amount' => ($data['purchase_discount_amount']+$coupon_discount_consider_total),
			'bank_id' => ($data['card_discount_total_with_vat_for_interface']+intval($data['coupon_card_discout'])),
			'branch_name' => intval($data['coupon_card_discout'])
			);

			$this->db->insert('sales_payments', $sales_payments_data);

		}else{

			$coupon_discount_consider_total=0;
			$coupon_discount_consider_vat_total=0;

			if(trim($data['coupon_card_number'])!="" && intval($data['coupon_card_number'])!=0){

				if(intval($data['coupon_card_discout'])>0){
					$coupon_discount_consider_total=round((($data['coupon_card_discout']/107.5)*100));
					$sales_payments_data = array
					(
					'sale_id' => $sale_id,
					'payment_type' => "Purchase Discount",
					'payment_amount' => $coupon_discount_consider_total,
					'bank_id' => ($data['card_discount_total_with_vat_for_interface']+intval($data['coupon_card_discout'])),
					'branch_name' => intval($data['coupon_card_discout'])
					);

					$this->db->insert('sales_payments', $sales_payments_data);
				}
			}
		}

		if(trim($data['coupon_card_number'])!=""){
			$this->db->query("UPDATE pos_ospos_eid_coupon SET coupon_use_date='".mysql_real_escape_string(date("Y-m-d H:i:s"))."',
			is_used='1',
			used_invoice_no='".mysql_real_escape_string($receipt_no)."',
			used_coupon_value='".mysql_real_escape_string(intval($data['coupon_card_discout']))."'
			WHERE coupon_code='".mysql_real_escape_string(trim($data['coupon_card_number']))."'");
			$this->db->trans_complete();
		}

		$total_point_amount_point=$total_point_amount/100;

		$this->db->query("UPDATE pos_ospos_customers SET point=point+'".mysql_real_escape_string($total_point_amount_point)."'
					WHERE id='".mysql_real_escape_string($this->Customer->exists($customer_id) ? $customer_id : 0)."'");

		$this->db->trans_complete();

		if(trim($_POST['new_card_number'])){
			$this->db->query("UPDATE pos_ospos_customers SET gs_card_no='".mysql_real_escape_string($_POST['new_card_number'])."',state='".mysql_real_escape_string($_POST['new_card_number'])."'
					WHERE id='".mysql_real_escape_string($this->Customer->exists($customer_id) ? $customer_id : 0)."' AND gs_card_no=''");

			$this->db->trans_complete();
		}

		///////////////////REPRINT TABLE DATA ////////////////////////////
		$this->db->query("INSERT INTO ospos_sales_reprint SELECT * FROM ospos_sales WHERE receipt_no='".mysql_real_escape_string($receipt_no)."'");
		$this->db->query("INSERT INTO ospos_sales_items_reprint SELECT * FROM ospos_sales_items WHERE sale_id='".mysql_real_escape_string($sale_id)."'");
		$this->db->query("INSERT INTO ospos_sales_payments_reprint SELECT * FROM ospos_sales_payments WHERE sale_id='".mysql_real_escape_string($sale_id)."'");

		$return_array['receipt_no']=$receipt_no;
		$return_array['sale_id']=$sale_id;

		return $return_array;
	}

	function product_price_reprint($current_date=""){

		////////////////////////////PERMISSION PRODUCT ///////////////////////////////////////////

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

		$current_directory = getcwd();

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

		}else{
			$config_mrp['MRP_ACTIVE']=0;
		}


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

			$count_invoice_no=0;
			$query_count = $this->db->query("SELECT COUNT(sale_id) AS count_sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."'");

			foreach ($query_count->result() as $row_count) {
				$count_invoice_no=$row_count->count_sale_id;
			}
			if($count_invoice_no<=1){
				$config_mrp['MRP_ACTIVE']=0;
			}
		}
		if(intval($config_mrp['MRP_ACTIVE'])==1){
			if(intval($config_mrp['MRP_LUNCHBREAK'])==0){

				$day_name=date('D', strtotime($current_date));
				if($config_mrp['MRP_WEEKEND']!=$day_name){

					function displayDates($date1, $date2, $format = 'Y-m-d' ) {
						$dates = array();
						$current = strtotime($date1);
						$date2 = strtotime($date2);
						$stepVal = '+1 day';
						while( $current <= $date2 ) {
							$dates[] = date($format, $current);
							$current = strtotime($stepVal, $current);
						}
						return $dates;
					}
					$date_array = displayDates($config_mrp['MRP_MANAGER_LEAVE_START'], $config_mrp['MRP_MANAGER_LEAVE_END']);

					if (!in_array($current_date, $date_array)){


						$today_total_sale_amount=0;
						$today_total_mrp_amount=0;
						$minimum_permission_amount=0;

						/////////////////SPECIAL DISCOUNT//////////////////////
						$special_customer_id=array();

						/*$query_special = $this->db->query("SELECT id FROM pos_ospos_customers
						WHERE is_special=1 AND special_percentage>0 AND id!='28550'");*/
						$query_special = $this->db->query("SELECT id FROM pos_ospos_customers
					WHERE is_special=1 AND special_percentage>0 AND id NOT IN('28550','31259','31451','31716','34019','26943','34099','34100','34720','34721','34722','34723','34724') ");

						foreach ($query_special->result() as $row_special) {
							$special_customer_id[]=$row_special->id;
						}

						$special_customer_id[]=100000;/////////////////FOR DEFAULT
						$consider_sale_id=array();
						$consider_sale_id_information=array();

						/////////////////SPECIAL DISCOUNT//////////////////////
						$query_all_sale = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND a.acc_location='".LOCATION_CODE."' AND a.payment_type!='' AND (a.is_sync = 0 OR a.is_sync IS NULL) AND (clr_sync=0 OR clr_sync IS NULL)");


						foreach ($query_all_sale->result() as $row_all) {

							if(intval($row_all->customer_id)!=0){
								if (!in_array(intval($row_all->customer_id), $special_customer_id)){
									$consider_sale_id[]=$row_all->sale_id;
									$consider_sale_id_information[$row_all->sale_id]=$row_all;
								}
							}else{
								$consider_sale_id[]=$row_all->sale_id;
								$consider_sale_id_information[$row_all->sale_id]=$row_all;
							}
						}
						if(count($consider_sale_id)){

							$consider_sale_id_string="";
							$consider_sale_id_string="''";
							if(count($consider_sale_id)){
								$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";
							}


							$query = $this->db->query("SELECT SUM(vat_enable_price) AS total_sale
		FROM ospos_sales_items_reprint WHERE sale_id IN (".$consider_sale_id_string.")");

							foreach ($query->result() as $row) {
								$today_total_sale_amount=$row->total_sale;
							}

							$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_mrp
		FROM ospos_permissions_relations_customer 
		WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' AND payment_type='MRP' AND purchase_discount=0 AND sales_id IN (".$consider_sale_id_string.") ");

							foreach ($query->result() as $row) {
								$today_total_mrp_amount=$row->total_mrp;
							}

							if($config_mrp['MRP_SLOT_ACTIVE']==1){
								$minimum_permission_amount=0;
								$temp_today_total_sale_amount=$today_total_sale_amount;

								if($temp_today_total_sale_amount>0){////SLOT_1
									$maximum_permission_percentage_slot_1=(rand($config_mrp['MRP_RAND_SLOT_1'], ($config_mrp['MRP_RAND_SLOT_1']+100))/100);//////////////////////SET AS MY WISH

									$consider_sale_amount=0;
									if($temp_today_total_sale_amount>=$config_mrp['MRP_SLOT_LIMIT_1']){
										$consider_sale_amount=$config_mrp['MRP_SLOT_LIMIT_1'];
									}else{
										$consider_sale_amount=$temp_today_total_sale_amount;
									}

									$minimum_permission_amount+=round(($consider_sale_amount*$maximum_permission_percentage_slot_1)/100);
									$temp_today_total_sale_amount-=$consider_sale_amount;
								}


								if($temp_today_total_sale_amount>0){////SLOT_2
									$maximum_permission_percentage_slot_2=(rand($config_mrp['MRP_RAND_SLOT_2'], ($config_mrp['MRP_RAND_SLOT_2']+100))/100);//////////////////////SET AS MY WISH

									$consider_sale_amount=0;
									if($temp_today_total_sale_amount>=($config_mrp['MRP_SLOT_LIMIT_2']-$config_mrp['MRP_SLOT_LIMIT_1'])){
										$consider_sale_amount=($config_mrp['MRP_SLOT_LIMIT_2']-$config_mrp['MRP_SLOT_LIMIT_1']);
									}else{
										$consider_sale_amount=$temp_today_total_sale_amount;
									}

									$minimum_permission_amount+=round(($consider_sale_amount*$maximum_permission_percentage_slot_2)/100);
									$temp_today_total_sale_amount-=$consider_sale_amount;
								}

								if($temp_today_total_sale_amount>0){////SLOT_3
									$maximum_permission_percentage_slot_3=(rand($config_mrp['MRP_RAND_SLOT_3'], ($config_mrp['MRP_RAND_SLOT_3']+100))/100);//////////////////////SET AS MY WISH

									$consider_sale_amount=0;
									if($temp_today_total_sale_amount>=($config_mrp['MRP_SLOT_LIMIT_3']-$config_mrp['MRP_SLOT_LIMIT_2'])){
										$consider_sale_amount=($config_mrp['MRP_SLOT_LIMIT_3']-$config_mrp['MRP_SLOT_LIMIT_2']);
									}else{
										$consider_sale_amount=$temp_today_total_sale_amount;
									}

									$minimum_permission_amount+=round(($consider_sale_amount*$maximum_permission_percentage_slot_3)/100);
									$temp_today_total_sale_amount-=$consider_sale_amount;
								}

								if($temp_today_total_sale_amount>0){////SLOT_4
									$maximum_permission_percentage_slot_4=(rand($config_mrp['MRP_RAND_SLOT_4'], ($config_mrp['MRP_RAND_SLOT_4']+100))/100);//////////////////////SET AS MY WISH

									$consider_sale_amount=0;
									$consider_sale_amount=$temp_today_total_sale_amount;

									$minimum_permission_amount+=round(($consider_sale_amount*$maximum_permission_percentage_slot_4)/100);
									$temp_today_total_sale_amount-=$consider_sale_amount;
								}
								$minimum_permission_amount=round($minimum_permission_amount)-round($today_total_mrp_amount);

							}else{
								$maximum_permission_percentage=(rand($config_mrp['MRP_RAND_START'], $config_mrp['MRP_RAND_END'])/100);//////////////////////SET AS MY WISH
								$minimum_permission_amount=round(($today_total_sale_amount*$maximum_permission_percentage)/100)-round($today_total_mrp_amount);

							}

							///////////////////////////START::SPECIAL SALES DISCOUNT SALES OMIT//////////////
							$consider_sale_id_string_special="";
							$sale_special_ids=array();
							if(count($consider_sale_id)){
								$consider_sale_id_string_special="'".implode("','",$consider_sale_id)."'";
							}

							$sql_total_sale_consider_special="SELECT  sale_id FROM ospos_sales_payments WHERE sale_id IN(".$consider_sale_id_string_special.") AND payment_type='Purchase Bonus' GROUP BY sale_id";
							$query_total_sale_consider_special = $this->db->query($sql_total_sale_consider_special);
							foreach ($query_total_sale_consider_special->result() as $row_total_sale_consider_special) {
								$sale_special_ids[]=$row_total_sale_consider_special->sale_id;
							}

							$temp_consider_sale_id_array=array();

							$temp_consider_sale_id_array=$consider_sale_id;
							$consider_sale_id=array();

							foreach ($temp_consider_sale_id_array as $key_sale => $value_sale) {
								if(!in_array($value_sale,$sale_special_ids)){
									$consider_sale_id[]=$value_sale;
								}
							}
							$temp_consider_sale_id_array=array();

							///////////////////////////END::SPECIAL SALES DISCOUNT SALES OMIT//////////////

							if($minimum_permission_amount>0){
								////////////////////////////MODIFY/////////////////////OPTIMIZE
								$vat_enable_price_after_discount_cal_consider=array();
								$consider_sale_id_string="";
								$consider_sale_id_string="''";
								if(count($consider_sale_id)){
									$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";
								}
								$sql_total_sale_consider="SELECT  sale_id,vat_enable_price_after_discount_cal FROM ospos_sales_items WHERE sale_id IN(".$consider_sale_id_string.")";
								$query_total_sale_consider = $this->db->query($sql_total_sale_consider);
								foreach ($query_total_sale_consider->result() as $row_total_sale_consider) {
									if(intval($row_total_sale_consider->vat_enable_price_after_discount_cal)==0){
										$vat_enable_price_after_discount_cal_consider[$row_total_sale_consider->sale_id]=$row_total_sale_consider->sale_id;
									}
								}
								////////////////////////////MODIFY/////////////////////OPTIMIZE

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

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

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

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

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

								}

								$current_cash=0;

								$query_cash = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (".$consider_sale_id_string.") AND  payment_type='CASH'");

								foreach ($query_cash->result() as $row_cash) {
									$current_cash=$row_cash->total_cash;/////////////////////NEXT CONSIDER
								}



								$stock_moves_reprint_reload=array();
								$sql_create="CREATE TABLE IF NOT EXISTS `stock_moves_reprint` (
  `trans_id` int(11) NOT NULL AUTO_INCREMENT,
  `stock_id` char(20) NOT NULL DEFAULT '',
  `loc_code` char(5) NOT NULL DEFAULT '',
  `price` double NOT NULL DEFAULT '0',
  `standard_cost` double NOT NULL DEFAULT '0',
  `visible` tinyint(1) NOT NULL DEFAULT '1',
  `lot_no` int(10) DEFAULT '0',
  `is_imported` smallint(6) NOT NULL DEFAULT '0',
  `swatch_code` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`trans_id`))";
								$this->db->query($sql_create);

								$query_moves_count = $this->db->query("SELECT count(*) AS count_st FROM stock_moves_reprint");

								$has_count=0;
								foreach ($query_moves_count->result() as $row_moves_count) {
									$has_count=intval($row_moves_count->count_st);
								}

								if(intval($has_count)==0){
									$query_moves = $this->db->query("SELECT
		  stock_id,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code
		  FROM stock_moves_reprint_reload AS a WHERE price>=300 AND standard_cost>10
		  GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC,a.lot_no DESC");


									$insert_query="INSERT INTO stock_moves_reprint (
		  stock_id,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code) VALUES
		";

									foreach ($query_moves->result() as $row_compare) {
										$stock_moves_reprint_reload[]=$row_compare->stock_id."#".intval($row_compare->price)."#".intval($row_compare->standard_cost)."#".intval($row_compare->lot_no);

										$row_compare_implode=array();

										foreach ($row_compare as $key => $value) {
											$row_compare_implode[]=$value;
										}
										if(count($row_compare_implode)){
											$insert_query.='(';
											$insert_query.="'".implode("','",$row_compare_implode)."'";
											$insert_query.='),';
										}
									}

									$insert_query=substr($insert_query, 0, -1)."";
									$this->db->query($insert_query);

									$update_query="UPDATE stock_moves_reprint SET loc_code='".LOCATION_CODE."'";
									$this->db->query($update_query);


									if(LOCATION_CODE=="ADB"){
										$query_moves_insert = $this->db->query("SELECT
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code
		  FROM stock_moves AS a WHERE price>=300 AND standard_cost>10
		  GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC,a.lot_no DESC");
									}else{
										$query_moves_insert = $this->db->query("SELECT
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code
		  FROM stock_moves AS a WHERE price>=300 AND standard_cost>10
		  GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC,a.lot_no DESC");
									}




									$has_atleast_one_row=0;

									$insert_query="INSERT INTO stock_moves_reprint (
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code) VALUES
		";

									foreach ($query_moves_insert->result() as $row_compare) {


										$stock_moves_index_for_check=$row_compare->stock_id."#".intval($row_compare->price)."#".intval($row_compare->standard_cost)."#".intval($row_compare->lot_no);
										if(!in_array($stock_moves_index_for_check,$stock_moves_reprint_reload)){

											$has_atleast_one_row=1;

											$row_compare_implode=array();

											foreach ($row_compare as $key => $value) {
												$row_compare_implode[]=$value;
											}
											if(count($row_compare_implode)){
												$insert_query.='(';
												$insert_query.="'".implode("','",$row_compare_implode)."'";
												$insert_query.='),';
											}
										}
									}

									if($has_atleast_one_row==1){
										$insert_query=substr($insert_query, 0, -1)."";
										$this->db->query($insert_query);
									}
								}

								$description_wise_minimum=array();
								$category_wise_minimum=array();
								$stock_id_filter=array();


								if(LOCATION_CODE=="UTA"){
									$description_wise_minimum['Lungi']=450;
									$description_wise_minimum['Male Full Shirt']=650;
									$description_wise_minimum['Male Half Shirt']=600;
									$description_wise_minimum['Male Half Fatua']=600;
									$description_wise_minimum['Male Full Fatua']=650;
									$description_wise_minimum['Gamcha Fabric']=20000;
									$description_wise_minimum['Gamcha']=20000;
									$description_wise_minimum['Boy Trowzer']=521;
									$description_wise_minimum['Female Trowzer']=521;
									$description_wise_minimum['Male Trowzer']=660;
									$description_wise_minimum['Male Three Quarter']=421;
									$description_wise_minimum['Female SHAL']=1781;
									$description_wise_minimum['Male Panjabi']=900;
									$description_wise_minimum['Blazer']=3491;

									$description_wise_minimum['Male Gabardine Pant']=650;
									$description_wise_minimum['Batik Sharee']=900;
									$description_wise_minimum['Endy Sharee']=2000;
									$description_wise_minimum['Girl Sharee']=600;
									$description_wise_minimum['Gray Sharee']=900;
									$description_wise_minimum['Katan Sharee']=1400;
									$description_wise_minimum['Sharee']=900;
									$description_wise_minimum['Sharee Blockprint']=900;
									$description_wise_minimum['Sharee Half Silk']=1400;
									$description_wise_minimum['Sharee Handprint']=1000;
									$description_wise_minimum['Sharee Handwork']=1000;
									$description_wise_minimum['Sharee Screen Print']=1000;
									$description_wise_minimum['Sharee Silk']=4000;
									$description_wise_minimum['Tissue sharee']=900;
									$description_wise_minimum['3 Piece']=900;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Blouse Piece']=900;
									$description_wise_minimum['Female Loose  One piece']=900;
									$description_wise_minimum['Female One piece']=900;
									$description_wise_minimum['Female Two piece']=900;
									$description_wise_minimum['Girl One Piece']=900;
									$description_wise_minimum['Girl Three Piece']=900;
									$description_wise_minimum['Girl Two Piece']=900;
									$description_wise_minimum['Loose Three Piece']=900;
									$description_wise_minimum['One Piece']=900;
									$description_wise_minimum['Showpiece']=900;
									$description_wise_minimum['Three Piece']=1450;
									$description_wise_minimum['Vegetable dai Three Piece']=900;
									$description_wise_minimum['GC Three Pice']=900;
									$description_wise_minimum['Ladies Kurti']=1300;
									$description_wise_minimum['Male Jeans Pant']=700;
									$description_wise_minimum['Maxi']=880;
									$description_wise_minimum['Male Jacket']=900;

									$description_wise_minimum['Bed Sheet']=750;
									$description_wise_minimum['Bed Sheet Aplic']=750;
									$description_wise_minimum['Bed Sheet Block Print']=750;
									$description_wise_minimum['Bed Sheet Dubble']=1080;
									$description_wise_minimum['Bed Sheet Dubble-Manufactured']=1080;
									$description_wise_minimum['Bed Sheet Nokshi']=750;
									$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=930;
									$description_wise_minimum['Bed Sheet Semi-Dubble']=930;
									$description_wise_minimum['Bed Sheet Single']=750;
									$description_wise_minimum['Bed Sheet Single-Manufactured']=750;
									$description_wise_minimum['Three Piece']=900;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Vegetable dai Three Piece']=900;

									$description_wise_minimum['Female Loose  One piece']=1050;
									$description_wise_minimum['Female One piece']=1050;
									$description_wise_minimum['One Piece']=1050;


									$description_wise_minimum['Male Half Shirt']=744;
									$description_wise_minimum['Male Half Fatua']=744;


									$description_wise_minimum['Male Full Shirt']=750;
									$description_wise_minimum['Male Full Fatua']=750;


									$description_wise_minimum['Shal Screen Print']=780;
									$description_wise_minimum['Girl Skirt']=550;
									$description_wise_minimum['Girl Skirt-Tops']=550;
									$description_wise_minimum['Girl Skit-Tops']=550;
									$description_wise_minimum['Male Koti']=690;
									$description_wise_minimum['Male Jeans Pant']=600;
									$description_wise_minimum['Male Pazama']=650;

									$description_wise_minimum['Loose Three Piece']=900;

									$description_wise_minimum['Lungi']=560;
									$description_wise_minimum['Male Panjabi']=1000;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Girl Three Piece']=900;
									$description_wise_minimum['Loose Three Piece']=1700;
									$description_wise_minimum['Three Piece']=1590;
									$description_wise_minimum['Vegetable dai Three Piece']=1500;
									$description_wise_minimum['GC Three Pice']=900;

									$description_wise_minimum['Male Half Fatua']=744;
									$description_wise_minimum['Male Half Shirt']=650;
									$description_wise_minimum['Male Full Shirt']=800;

									if(LOCATION_CODE=="SDB"){
										$description_wise_minimum['Lungi']=450;
										$description_wise_minimum['Male Panjabi']=1000;
										$description_wise_minimum['Batik Three Piece']=1090;
										$description_wise_minimum['Loose Three Piece']=1000;
										$description_wise_minimum['Three Piece']=1090;
										$description_wise_minimum['Vegetable dai Three Piece']=1590;
										$description_wise_minimum['Male Half Fatua']=600;
										$description_wise_minimum['Male Half Shirt']=600;
										$description_wise_minimum['Male Full Shirt']=650;
									}
									if(LOCATION_CODE=="DNJ"){
										$description_wise_minimum['Loose Three Piece']=1960;
									}

									///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////
									$current_directory = getcwd();
									$filename=$current_directory . '\pdf_report\report_file_runtime\product_minimum_price.txt';
									if (file_exists($filename)) {
										if ($fd = fopen($filename, 'rb')) {
											$saved_data = fread($fd, filesize($filename));
											fclose($fd);
											$description_wise_minimum_json_decode = json_decode(trim($saved_data), false);
											foreach ($description_wise_minimum_json_decode as $jeson_key => $jeson_value) {
												$description_wise_minimum[trim($jeson_key)]=trim($jeson_value);
											}
										}
									}
									///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////

									$category_wise_minimum['56']=100000;////Handicraft

								}else{

									$description_wise_minimum['Lungi']=450;
									$description_wise_minimum['Male Full Shirt']=650;
									$description_wise_minimum['Male Half Shirt']=600;
									$description_wise_minimum['Male Half Fatua']=600;
									$description_wise_minimum['Male Full Fatua']=650;
									$description_wise_minimum['Gamcha Fabric']=20000;
									$description_wise_minimum['Gamcha']=20000;
									$description_wise_minimum['Boy Trowzer']=521;
									$description_wise_minimum['Female Trowzer']=521;
									$description_wise_minimum['Male Trowzer']=660;
									$description_wise_minimum['Male Three Quarter']=421;
									$description_wise_minimum['Female SHAL']=1781;
									$description_wise_minimum['Male Panjabi']=900;
									$description_wise_minimum['Blazer']=3491;

									$description_wise_minimum['Male Gabardine Pant']=650;
									$description_wise_minimum['Batik Sharee']=900;
									$description_wise_minimum['Endy Sharee']=2000;
									$description_wise_minimum['Girl Sharee']=600;
									$description_wise_minimum['Gray Sharee']=900;
									$description_wise_minimum['Katan Sharee']=1400;
									$description_wise_minimum['Sharee']=900;
									$description_wise_minimum['Sharee Blockprint']=900;
									$description_wise_minimum['Sharee Half Silk']=1400;
									$description_wise_minimum['Sharee Handprint']=1000;
									$description_wise_minimum['Sharee Handwork']=1000;
									$description_wise_minimum['Sharee Screen Print']=1000;
									$description_wise_minimum['Sharee Silk']=4000;
									$description_wise_minimum['Tissue sharee']=900;
									$description_wise_minimum['3 Piece']=900;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Blouse Piece']=900;
									$description_wise_minimum['Female Loose  One piece']=900;
									$description_wise_minimum['Female One piece']=900;
									$description_wise_minimum['Female Two piece']=900;
									$description_wise_minimum['Girl One Piece']=900;
									$description_wise_minimum['Girl Three Piece']=900;
									$description_wise_minimum['Girl Two Piece']=900;
									$description_wise_minimum['Loose Three Piece']=900;
									$description_wise_minimum['One Piece']=900;
									$description_wise_minimum['Showpiece']=900;
									$description_wise_minimum['Three Piece']=1450;
									$description_wise_minimum['Vegetable dai Three Piece']=900;
									$description_wise_minimum['GC Three Pice']=900;
									$description_wise_minimum['Ladies Kurti']=1300;
									$description_wise_minimum['Male Jeans Pant']=700;
									$description_wise_minimum['Maxi']=880;
									$description_wise_minimum['Male Jacket']=900;

									$description_wise_minimum['Bed Sheet']=750;
									$description_wise_minimum['Bed Sheet Aplic']=750;
									$description_wise_minimum['Bed Sheet Block Print']=750;
									$description_wise_minimum['Bed Sheet Dubble']=1080;
									$description_wise_minimum['Bed Sheet Dubble-Manufactured']=1080;
									$description_wise_minimum['Bed Sheet Nokshi']=750;
									$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=930;
									$description_wise_minimum['Bed Sheet Semi-Dubble']=930;
									$description_wise_minimum['Bed Sheet Single']=750;
									$description_wise_minimum['Bed Sheet Single-Manufactured']=750;
									$description_wise_minimum['Three Piece']=900;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Vegetable dai Three Piece']=900;

									$description_wise_minimum['Female Loose  One piece']=1050;
									$description_wise_minimum['Female One piece']=1050;
									$description_wise_minimum['One Piece']=1050;


									$description_wise_minimum['Male Half Shirt']=744;
									$description_wise_minimum['Male Half Fatua']=744;


									$description_wise_minimum['Male Full Shirt']=750;
									$description_wise_minimum['Male Full Fatua']=750;


									$description_wise_minimum['Shal Screen Print']=780;
									$description_wise_minimum['Girl Skirt']=550;
									$description_wise_minimum['Girl Skirt-Tops']=550;
									$description_wise_minimum['Girl Skit-Tops']=550;
									$description_wise_minimum['Male Koti']=690;
									$description_wise_minimum['Male Jeans Pant']=600;
									$description_wise_minimum['Male Pazama']=650;

									$description_wise_minimum['Loose Three Piece']=900;

									$description_wise_minimum['Lungi']=560;
									$description_wise_minimum['Male Panjabi']=1000;
									$description_wise_minimum['Batik Three Piece']=900;
									$description_wise_minimum['Girl Three Piece']=900;
									$description_wise_minimum['Loose Three Piece']=1700;
									$description_wise_minimum['Three Piece']=1590;
									$description_wise_minimum['Vegetable dai Three Piece']=1500;
									$description_wise_minimum['GC Three Pice']=900;

									$description_wise_minimum['Male Half Fatua']=744;
									$description_wise_minimum['Male Half Shirt']=650;
									$description_wise_minimum['Male Full Shirt']=800;

									if(LOCATION_CODE=="DNJ"){
										$description_wise_minimum['Loose Three Piece']=1960;
									}
									if(LOCATION_CODE=="SDB"){
										$description_wise_minimum['Lungi']=730;
										$description_wise_minimum['Male Panjabi']=1000;
										$description_wise_minimum['Batik Three Piece']=1390;
										$description_wise_minimum['Loose Three Piece']=1200;
										$description_wise_minimum['Three Piece']=1290;
										$description_wise_minimum['Vegetable dai Three Piece']=1290;
										$description_wise_minimum['Male Half Fatua']=600;
										$description_wise_minimum['Male Half Shirt']=600;
										$description_wise_minimum['Male Full Shirt']=650;
									}
									if(LOCATION_CODE=="RAN"){
										$description_wise_minimum['Lungi']=870;
										$description_wise_minimum['Male Full Shirt']=800;
										$description_wise_minimum['Male Half Shirt']=1300;
										$description_wise_minimum['Male Half Fatua']=750;
										$description_wise_minimum['Male Full Fatua']=750;
										$description_wise_minimum['Gamcha Fabric']=20000;
										$description_wise_minimum['Gamcha']=20000;
										$description_wise_minimum['Boy Trowzer']=560;
										$description_wise_minimum['Female Trowzer']=560;
										$description_wise_minimum['Male Trowzer']=660;
										$description_wise_minimum['Male Three Quarter']=550;
										$description_wise_minimum['Female SHAL']=1781;
										$description_wise_minimum['Male Panjabi']=1900;
										$description_wise_minimum['Blazer']=3491;

										$description_wise_minimum['Male Gabardine Pant']=650;
										$description_wise_minimum['Batik Sharee']=1400;
										$description_wise_minimum['Endy Sharee']=2000;
										$description_wise_minimum['Girl Sharee']=600;
										$description_wise_minimum['Gray Sharee']=1000;
										$description_wise_minimum['Katan Sharee']=1400;
										$description_wise_minimum['Sharee']=2000;
										$description_wise_minimum['Sharee Blockprint']=1650;
										$description_wise_minimum['Sharee Half Silk']=2400;
										$description_wise_minimum['Sharee Handprint']=1600;
										$description_wise_minimum['Sharee Handwork']=1600;
										$description_wise_minimum['Sharee Screen Print']=2800;
										$description_wise_minimum['Sharee Silk']=4000;
										$description_wise_minimum['Tissue sharee']=2000;
										$description_wise_minimum['3 Piece']=1200;
										$description_wise_minimum['Batik Three Piece']=1300;
										$description_wise_minimum['Blouse Piece']=2500;
										$description_wise_minimum['Female Loose  One piece']=1500;
										$description_wise_minimum['Female One piece']=1000;
										$description_wise_minimum['Female Two piece']=1600;
										$description_wise_minimum['Girl One Piece']=1000;
										$description_wise_minimum['Girl Three Piece']=1000;
										$description_wise_minimum['Girl Two Piece']=1000;
										$description_wise_minimum['Loose Three Piece']=2000;
										$description_wise_minimum['One Piece']=1000;
										$description_wise_minimum['Showpiece']=1000;
										$description_wise_minimum['Three Piece']=1450;
										$description_wise_minimum['Vegetable dai Three Piece']=2000;
										$description_wise_minimum['GC Three Pice']=2000;
										$description_wise_minimum['Ladies Kurti']=1200;
										$description_wise_minimum['Male Jeans Pant']=700;
										$description_wise_minimum['Maxi']=880;
										$description_wise_minimum['Male Jacket']=1000;
										$description_wise_minimum['Bed Sheet']=750;
										$description_wise_minimum['Bed Sheet Aplic']=750;
										$description_wise_minimum['Bed Sheet Block Print']=750;
										$description_wise_minimum['Bed Sheet Dubble']=1080;
										$description_wise_minimum['Bed Sheet Dubble-Manufactured']=1080;
										$description_wise_minimum['Bed Sheet Nokshi']=750;
										$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=930;
										$description_wise_minimum['Bed Sheet Semi-Dubble']=930;
										$description_wise_minimum['Bed Sheet Single']=750;
										$description_wise_minimum['Bed Sheet Single-Manufactured']=750;
										$description_wise_minimum['Three Piece']=1000;
										$description_wise_minimum['Batik Three Piece']=1000;
										$description_wise_minimum['Vegetable dai Three Piece']=1000;
										$description_wise_minimum['Female Loose  One piece']=1050;
										$description_wise_minimum['Female One piece']=1050;
										$description_wise_minimum['One Piece']=1050;
										$description_wise_minimum['Shal Screen Print']=780;
										$description_wise_minimum['Girl Skirt']=880;
										$description_wise_minimum['Girl Skirt-Tops']=800;
										$description_wise_minimum['Girl Skit-Tops']=800;
										$description_wise_minimum['Male Koti']=690;
										$description_wise_minimum['Male Pazama']=650;
									}


									///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////
									$current_directory = getcwd();
									$filename=$current_directory . '\pdf_report\report_file_runtime\product_minimum_price.txt';
									if (file_exists($filename)) {
										if ($fd = fopen($filename, 'rb')) {
											$saved_data = fread($fd, filesize($filename));
											fclose($fd);
											$description_wise_minimum_json_decode = json_decode(trim($saved_data), false);
											foreach ($description_wise_minimum_json_decode as $jeson_key => $jeson_value) {
												$description_wise_minimum[trim($jeson_key)]=trim($jeson_value);
											}
										}
									}
									///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////

									$category_wise_minimum['56']=100000;////Handicraft
								}

								if(count($description_wise_minimum)){
									$clause_string="";
									$where_string_description=array();
									foreach ($description_wise_minimum as $clause_key => $clause_value) {
										$clause_string.=" WHEN description = '".$clause_key."' THEN ".$clause_value." ";
										$where_string_description[]=$clause_key;
									}
									$where_string_description_string="'".implode("','",$where_string_description)."'";

									$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where description IN(".$where_string_description_string.")");


									foreach ($query_filter->result() as $row_filter) {
										if(intval($row_filter->price)){
											$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
										}
									}
								}

								if(count($category_wise_minimum)){
									$clause_string="";
									$where_string_description=array();
									foreach ($category_wise_minimum as $clause_key => $clause_value) {
										$clause_string.=" WHEN category_id = '".$clause_key."' THEN ".$clause_value." ";
										$where_string_description[]=$clause_key;
									}
									$where_string_description_string="'".implode("','",$where_string_description)."'";

									$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where category_id IN(".$where_string_description_string.")");


									foreach ($query_filter->result() as $row_filter) {
										if(intval($row_filter->price)){
											$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
										}
									}

								}
								$sharee_array[]="02927013";
								$sharee_array[]="02928014";
								$sharee_array[]="02929015";
								$sharee_array[]="02930016";
								$sharee_array[]="02931017";
								$sharee_array[]="02939001";
								$sharee_array[]="02939002";
								$sharee_array[]="02939003";
								$sharee_array[]="02939006";
								$sharee_array[]="02939007";
								$sharee_array[]="02939008";
								$sharee_array[]="02939009";
								$sharee_array[]="02939010";
								$sharee_array[]="02939011";
								$sharee_array[]="02939012";
								$sharee_array[]="02939018";
								$sharee_array[]="02939019";
								$sharee_array[]="02939020";
								$sharee_array[]="02939021";
								$sharee_array[]="05939002";
								$sharee_array[]="06139022";
								$sharee_array[]="06739011";

								///////////////////////////////////////////////////////UPDATE LOT NO FOR CONSIDER START/////////////////////////////////////////
								$current_date_reprint=date("Y-m-d");
								$maximum_lot_no_consider="240000";

								$total_sale_new_product_real=0;
								$query_new_product = $this->db->query("SELECT SUM(quantity_purchased) AS total_quantity_purchased FROM ospos_sales_items_reprint
								WHERE sale_id IN (SELECT sale_id FROM  ospos_sales_reprint WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date_reprint."')
								AND lot_no>='".$maximum_lot_no_consider."' AND quantity_purchased>0");
								foreach ($query_new_product->result() as $row_new_product) {
									$total_sale_new_product_real=intval($row_new_product->total_quantity_purchased);
								}
								$minimum_new_product_should_stay=floor($total_sale_new_product_real*60/100);

								//////ALL SALES IDS today////////

								$all_sale_ids=array();
								$query_sale_ids = $this->db->query("SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date_reprint."'");

								foreach ($query_sale_ids->result() as $row_sale_ids) {
									$all_sale_ids[]=$row_sale_ids->sale_id;
								}

								$consider_all_sale_ids_string="'".implode("','",$all_sale_ids)."'";

								////////////////////////////22-03-2024//////////////////////////////////////////

								$skb_2024_same_price_product_sale_count=array();

								$query_skb_2024 = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_all_sale_ids_string.") AND quantity_purchased>0 AND discount_percent=0 AND (mrp_details!='' OR pcr_lot_no!='') ");

								foreach ($query_skb_2024->result() as $row_2024) {
									$skb_2024_same_price_product_sale_count[$row_2024->stock_id.$row_2024->lot_no.intval($row_2024->item_cost_price)]+=intval($row_2024->quantity_purchased);
								}

								$skb_2024_same_price_product_sale_omit=array();
								foreach ($skb_2024_same_price_product_sale_count as $key_qty => $value_qty) {
									if($value_qty>=2){
										$skb_2024_same_price_product_sale_omit[]=$key_qty;
									}
								}
								$skb_2024_same_price_product_sale_omit_str="";

								if(count($skb_2024_same_price_product_sale_omit)){
									$skb_2024_same_price_product_sale_omit_implode="'".implode("','",$skb_2024_same_price_product_sale_omit)."'";
									$skb_2024_same_price_product_sale_omit_str=" AND CONCAT(stock_id,lot_no,CAST(price AS UNSIGNED)) NOT IN(".$skb_2024_same_price_product_sale_omit_implode.") ";
								}
								////////////////////////////22-03-2024//////////////////////////////////////////

								//$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_string.") AND quantity_purchased>0 AND lot_no<'".$maximum_lot_no_consider_for_loop."' AND  stock_id NOT IN ('03500002','06139020','05639004') AND discount_percent=0 AND (mrp_details='' OR mrp_details IS NULL) ORDER BY item_cost_price DESC,vat_enable_price_after_discount DESC, quantity_purchased ASC ");
								$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_string.") AND quantity_purchased>0 AND  stock_id NOT IN ('03500002','06139020','05639004') AND discount_percent=0 AND (mrp_details='' OR mrp_details IS NULL) ORDER BY item_cost_price DESC,vat_enable_price_after_discount DESC, quantity_purchased ASC ");

								foreach ($query->result() as $row) {
									$new_product_ok=0;
									if($row->lot_no>=$maximum_lot_no_consider){
										$total_sale_new_product_now=0;

										$query_new_productx = $this->db->query("SELECT SUM(quantity_purchased) AS total_quantity_purchased FROM ospos_sales_items
								WHERE sale_id IN (".$consider_all_sale_ids_string.")
								AND lot_no>='".$maximum_lot_no_consider."' AND quantity_purchased>0");
										foreach ($query_new_productx->result() as $row_new_productx) {
											$total_sale_new_product_now=intval($row_new_productx->total_quantity_purchased);
										}
										if($total_sale_new_product_now>$minimum_new_product_should_stay){
											$new_product_ok=1;
										}
									}else{
										$new_product_ok=1;
									}

									if($minimum_permission_amount>0){

										if($new_product_ok==1){
											///////////////////////////////////////////////////////UPDATE LOT NO FOR CONSIDER END/////////////////////////////////////////

											///////////////////////////////////STOCK MOVES/////////////////////
											if(intval($has_count)>0){
												if(array_key_exists ( $row->stock_id, $stock_id_filter)){

													if(in_array($row->stock_id,$sharee_array)){
														$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000'  AND a.lot_no<'241299' AND a.price>='1200' AND a.standard_cost>10
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
													}else{
														$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000'  AND a.lot_no<'241299' AND a.standard_cost>10
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
													}


												}else{
													if(in_array($row->stock_id,$sharee_array)){
														$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.lot_no>='190000' AND a.lot_no<='241299' AND a.price>='1200' AND a.standard_cost>10
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND()");
													}else{
														$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000' AND a.lot_no<'241299' AND a.standard_cost>10
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND()");
													}

												}

												$has_stock_moves=array();

												$has_found=0;
												foreach ($query_moves->result() as $row_moves) {
													if($has_found==0){
														if((fmod($row_moves->price,1)== 0.00)){
															$has_stock_moves=$row_moves;
															$has_found=1;
															break;
														}
													}
												}

												if($has_found==0){

													if(array_key_exists ( $row->stock_id, $stock_id_filter)){
														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) 
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000' AND a.lot_no<'241299' AND a.price>='1200' AND a.standard_cost>10
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) 
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000' AND a.lot_no<'241299' AND a.standard_cost>10
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}
													}else{


														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) 
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.lot_no>='190000' AND a.lot_no<'240000' AND a.price>='1200' AND a.standard_cost>10
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) 
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no>='190000' AND a.lot_no<'241299' AND a.standard_cost>10
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}



													}
													foreach ($query_moves->result() as $row_moves) {
														if((fmod($row_moves->price,1)== 0.00)){
															$has_stock_moves=$row_moves;
															$has_found=1;
															break;
														}
													}
												}


											}else{
												if(array_key_exists ( $row->stock_id, $stock_id_filter)){

													if(LOCATION_CODE=="ADB"){
														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'  AND a.standard_cost>10
									AND a.lot_no>='180000'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
														}

													}else{
														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}
													}
												}else{
													if(LOCATION_CODE=="ADB"){
														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
														}


													}else{
														if(in_array($row->stock_id,$sharee_array)){
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}else{
															$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'  AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299'  AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
														}
													}
												}

												$has_stock_moves=array();

												$has_found=0;
												foreach ($query_moves->result() as $row_moves) {
													if($has_found==0){
														if((fmod($row_moves->price,1)== 0.00)){
															$has_stock_moves=$row_moves;
															$has_found=1;
															break;
														}
													}
												}
												if($has_found==0){
													if(array_key_exists ( $row->stock_id, $stock_id_filter)){

														if(LOCATION_CODE=="ADB"){

															if(in_array($row->stock_id,$sharee_array)){
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
															}else{
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									AND a.lot_no>='180000'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
															}
														}else{

															if(in_array($row->stock_id,$sharee_array)){
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
															}else{
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									AND a.lot_no>='180000' AND a.lot_no<'231299'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
															}


														}
													}else{
														if(LOCATION_CODE=="ADB"){
															if(in_array($row->stock_id,$sharee_array)){
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'  AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
															}else{
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.lot_no>='180000' 
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost HAVING SUM(qty)>0 ORDER BY a.price ASC, RAND() ");
															}


														}else{
															if(in_array($row->stock_id,$sharee_array)){
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299' AND a.price>='1200'
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
															}else{
																$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.standard_cost>10
									AND a.lot_no>='180000' AND a.lot_no<'231299'
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
									GROUP BY a.stock_id,a.price,a.lot_no,a.standard_cost ORDER BY a.price ASC, RAND() ");
															}
														}
													}
													foreach ($query_moves->result() as $row_moves) {
														if((fmod($row_moves->price,1)== 0.00)){
															$has_stock_moves=$row_moves;
															$has_found=1;
															break;
														}
													}
												}
											}

											//////////////////////////////NEW PRICE CAL////////////////////////////////
											$compare_price_per_unit=0;
											$compare_price=0;
											$compare_price_per_unit=round($row->item_cost_price)-round($has_stock_moves->price);
											$compare_price=round($compare_price_per_unit*$row->quantity_purchased);

											$consider_qty=$row->quantity_purchased;

											if($compare_price>$minimum_permission_amount){
												$consider_qty_min=round($minimum_permission_amount/$compare_price_per_unit);


												if($consider_qty_min<$consider_qty){
													$consider_qty=$consider_qty_min;

													if($consider_qty>0){
														$query_line = $this->db->query("SELECT MAX(line) As max_line FROM ospos_sales_items WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
														$max_line_result=$query_line->row();
														$next_line=intval($max_line_result->max_line)+1;


														$sales_items_data_second="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$row->sale_id."',
								'".$row->stock_id."',
								'".$row->description."',
								'".$row->lot_no."',
								'".$next_line."',
								'".($row->quantity_purchased-$consider_qty)."',
								'".$row->item_cost_price."',
								'".$row->item_unit_price."',
								'".$row->discount_percent."',
								'".number_format(((($row->total_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".number_format(((($row->total_sale_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".number_format(((($row->vat_enable_price)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".$row->vat_percentage."',
								'".number_format(((($row->vat_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".$row->sales_employee_code."',
								'".round(((($row->vat_enable_price_after_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)))."',
								'".$row->pcr_lot_no."',
								'".$row->sync_permission."',
								'".$row->cus_permission."')";

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


														$sales_items_data_first="UPDATE ospos_sales_items SET
quantity_purchased='".($consider_qty)."',
total_discount='".($row->total_discount-number_format(((($row->total_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
total_sale_amount='".($row->total_sale_amount-number_format(((($row->total_sale_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_enable_price='".($row->vat_enable_price-number_format(((($row->vat_enable_price)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_amount='".($row->vat_amount-number_format(((($row->vat_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_enable_price_after_discount='".($row->vat_enable_price_after_discount-round(((($row->vat_enable_price_after_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty))))."'

WHERE sale_id='".($row->sale_id)."' 
AND stock_id='".($row->stock_id)."' 
AND lot_no='".($row->lot_no)."' 
AND line='".($row->line)."' 
AND quantity_purchased='".($row->quantity_purchased)."' 
AND item_cost_price='".($row->item_cost_price)."' 
AND item_unit_price='".($row->item_unit_price)."' 
AND discount_percent='".($row->discount_percent)."' 
AND total_discount='".($row->total_discount)."' 
AND total_sale_amount='".($row->total_sale_amount)."' 
AND vat_enable_price='".($row->vat_enable_price)."' 
";
														$this->db->query($sales_items_data_first);///////////NEXT

														//$query_sales_reference = $this->db->query("SELECT * FROM ospos_sales WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
														//$row_sales_reference=$query_sales_reference->row();

														$row_sales_reference=$consider_sale_id_information[$row->sale_id];



														$query_line_moves = $this->db->query("SELECT * FROM stock_moves_reprint
										WHERE stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."' AND lot_no>='190000'");

														$row_stock_moves=$query_line_moves->row();

														$insert_stock_moves_second="INSERT INTO stock_moves(
								trans_no,			
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row->sale_id."',
								'".$row_stock_moves->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row->sale_id."',
								'".$row->item_cost_price."',
								'".$row_sales_reference->receipt_no."',
								'".($consider_qty*-1)."',
								'".$row_stock_moves->discount_percent."',
								'".$row_stock_moves->standard_cost."',
								'".$row_stock_moves->visible."',
								'".$row->lot_no."',
								'".$row_stock_moves->is_imported."',
								'".$row_stock_moves->swatch_code."')";

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

														$update_stock_moves_first="UPDATE stock_moves SET
				qty='".mysql_real_escape_string(($row->quantity_purchased-$consider_qty)*-1)."'
				WHERE type='201'
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND reference='".mysql_real_escape_string($row_sales_reference->receipt_no)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."'
				AND qty='".mysql_real_escape_string($row->quantity_purchased*-1)."'";

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

														$query_after_update = $this->db->query("SELECT * FROM ospos_sales_items
										WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'
										AND stock_id='".($row->stock_id)."' 
										AND lot_no='".($row->lot_no)."' 
										AND line='".($row->line)."' 
									    AND quantity_purchased='".($consider_qty)."' 										
										");

														$row=$query_after_update->row();
													}
												}else{
													$consider_qty=$row->quantity_purchased;
												}
											}else{
												$consider_qty=$row->quantity_purchased;
											}
											if($consider_qty>0){
												if(trim($has_stock_moves->stock_id)){

													//////////////////////////////ospos_sales////////////////
													$query_sales = $this->db->query("SELECT * FROM ospos_sales WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
													$row_sales=$query_sales->row();

													$real_cash=0;//////////////////////////////
													$real_purchase_discount=0;/////////////////
													$real_purchase_discount_for_payment_table=0;/////////////////

													$has_real_cash=0;
													$has_purchase_discount=0;

													$real_item_cost_price=$row->item_cost_price;
													$real_total_sale_amount=$row->total_sale_amount;
													$real_vat_amount=$row->vat_amount;
													$real_vat_enable_price_after_discount=$row->vat_enable_price_after_discount;

													$sql_payment="SELECT  payment_amount FROM ospos_sales_payments WHERE sale_id ='".$row->sale_id."' AND payment_type='Cash' LIMIT 1";
													$query_payment = $this->db->query($sql_payment);
													foreach ($query_payment->result() as $row_payment) {
														$real_cash=$row_payment->payment_amount;
														$has_real_cash=1;
													}

													$sql_payment="SELECT  payment_amount,branch_name FROM ospos_sales_payments WHERE sale_id ='".$row->sale_id."' AND payment_type='Purchase Discount' LIMIT 1";
													$query_payment = $this->db->query($sql_payment);
													foreach ($query_payment->result() as $row_payment) {
														//$real_purchase_discount=intval($row_payment->payment_amount)-intval($row_payment->branch_name);
														$real_purchase_discount=intval($row_payment->payment_amount);
														$real_purchase_discount_for_payment_table=$row_payment->payment_amount;
														$has_purchase_discount=1;
													}

													$real_total_sale_amount_sum=0;

													$sql_total_sale="SELECT  SUM(total_sale_amount) AS total_sale_amount_sum
				FROM ospos_sales_items WHERE sale_id ='".$row->sale_id."'";
													$query_total_sale = $this->db->query($sql_total_sale);
													foreach ($query_total_sale->result() as $row_total_sale) {
														$real_total_sale_amount_sum+=$row_total_sale->total_sale_amount_sum;
													}

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


													$final_cash=0;//////////////////////////////
													$final_purchase_discount=0;/////////////////

													$final_item_cost_price=$has_stock_moves->price;
													$final_total_sale_amount=number_format($has_stock_moves->price*$row->quantity_purchased,2,'.','');

													$final_vat_enable_price_after_discount=$final_total_sale_amount-round(($final_total_sale_amount*$real_purchase_discount_per_100)/100);
													$final_vat_amount=number_format($final_vat_enable_price_after_discount*$row->vat_percentage/100,2,'.','');


													$minimum_permission_amount=$minimum_permission_amount-($real_total_sale_amount-$final_total_sale_amount);


													$difference_purchase_discount=0;
													if($real_purchase_discount_per_100!=0){
														$difference_purchase_discount=round((($real_total_sale_amount*$real_purchase_discount_per_100)/100)-(($final_total_sale_amount*$real_purchase_discount_per_100)/100));
													}

													$permission_total_my=0;

													$permission_total_my=round(($real_vat_enable_price_after_discount+$real_vat_amount)-($final_vat_enable_price_after_discount+$final_vat_amount));

													if($current_cash>=$permission_total_my+129){

														$force_reference=substr($row_sales->receipt_no,3).substr($row_sales->receipt_no,0,3);
														$previous_date=date('Y-m-d', strtotime('-1 year', strtotime($current_date)) );

														$query_moves_mrp = $this->db->query("SELECT *
										FROM stock_moves_reprint
										WHERE stock_id='".mysql_real_escape_string($row->stock_id)."' 
										AND price='".mysql_real_escape_string($row->item_cost_price)."' AND lot_no>='190000'");

														$update_stock_moves_sales=$query_moves_mrp->row();


														///////////////////CONDITION/////////////////////

														$update_stock_moves="UPDATE stock_moves SET
				type=16,
				tran_date='".mysql_real_escape_string($previous_date)."',
				reference='".mysql_real_escape_string($force_reference)."'
				WHERE type='201'
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND reference='".mysql_real_escape_string($row_sales->receipt_no)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."'
				AND qty='".mysql_real_escape_string($row->quantity_purchased*-1)."'";

														if(trim($update_stock_moves_sales->stock_id)){

															if(doubleval($update_stock_moves_sales->standard_cost)==0){
																$update_stock_moves_sales->standard_cost=number_format((($row->item_cost_price)*55)/100, 2,".","");
															}
															$update_stock_moves_sales->visible=1;

															$mrp_details=$update_stock_moves_sales->stock_id."#".$previous_date."#".$update_stock_moves_sales->price."#".$force_reference."#".($row->quantity_purchased*-1)."#".$update_stock_moves_sales->standard_cost."#".$update_stock_moves_sales->visible."#".$row->lot_no."#".$update_stock_moves_sales->is_imported."#".$update_stock_moves_sales->swatch_code;
														}else{

															$price_dummy=$row->item_cost_price;
															$standard_cost_dummy=number_format((($row->item_cost_price)*55)/100, 2,".","");
															$visible_dummy=1;
															$lot_no_dummy=$row->lot_no;
															$is_imported_dummy=0;
															$swatch_code_dummy=0;

															$mrp_details=$row->stock_id."#".$previous_date."#".$price_dummy."#".$force_reference."#".($row->quantity_purchased*-1)."#".$standard_cost_dummy."#".$visible_dummy."#".$lot_no_dummy."#".$is_imported_dummy."#".$swatch_code_dummy;
														}


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

														$mrp_details.="NEWMRP".$has_stock_moves->stock_id."#".$previous_date."#".$has_stock_moves->price."#".$force_reference."#".$row->quantity_purchased."#".$has_stock_moves->standard_cost."#".$has_stock_moves->visible."#".$has_stock_moves->lot_no."#".$has_stock_moves->is_imported."#".$has_stock_moves->swatch_code;

														$insert_stock_moves_sales="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row->sale_id."',
								'".$has_stock_moves->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row->sale_id."',
								'".$has_stock_moves->price."',
								'".$row_sales->receipt_no."',
								'".($row->quantity_purchased*-1)."',
								'0',
								'".$has_stock_moves->standard_cost."',
								'".$has_stock_moves->visible."',
								'".$has_stock_moves->lot_no."',
								'".$has_stock_moves->is_imported."',
								'".$has_stock_moves->swatch_code."')";

														$this->db->query($update_stock_moves);
														$this->db->query($insert_stock_moves);
														$this->db->query($insert_stock_moves_sales);


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

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

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



														$update_sale_items="UPDATE ospos_sales_items SET
				stock_id='".mysql_real_escape_string($has_stock_moves->stock_id)."',
				description='".mysql_real_escape_string($cat_description."</br>".$item_description)."',
				lot_no='".mysql_real_escape_string($has_stock_moves->lot_no)."',
				item_cost_price='".mysql_real_escape_string($final_item_cost_price)."',
				item_unit_price='".mysql_real_escape_string($final_item_cost_price)."',
				total_sale_amount='".mysql_real_escape_string($final_total_sale_amount)."',
				vat_enable_price='".mysql_real_escape_string($final_total_sale_amount)."',
				vat_amount='".mysql_real_escape_string($final_vat_amount)."',
				vat_enable_price_after_discount='".mysql_real_escape_string($final_vat_enable_price_after_discount)."',
				mrp_details='".mysql_real_escape_string($mrp_details)."'

				WHERE sale_id='".mysql_real_escape_string($row->sale_id)."' 
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND lot_no='".mysql_real_escape_string($row->lot_no)."' 
				AND line='".mysql_real_escape_string($row->line)."' 
				AND quantity_purchased='".mysql_real_escape_string($row->quantity_purchased)."'
				AND item_cost_price='".mysql_real_escape_string($row->item_cost_price)."'
				AND total_sale_amount='".mysql_real_escape_string($row->total_sale_amount)."'
				AND vat_enable_price_after_discount='".mysql_real_escape_string($row->vat_enable_price_after_discount)."'"
														;

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

														if($has_real_cash){
															$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($real_cash-round($permission_total_my))."' WHERE sale_id='".$row->sale_id."' AND payment_type='Cash'";
															$this->db->query($update_query_permission);////////////////NEXT

														}else{
															if(round($permission_total_my)!=0){
																$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$row->sale_id."',
					'Cash',
					'-".round($permission_total_my)."')";
																$this->db->query($insert_sql);////NEXT
															}
														}
														if($has_purchase_discount){
															$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($real_purchase_discount_for_payment_table-round($difference_purchase_discount))."' WHERE sale_id='".$row->sale_id."' AND payment_type='Purchase Discount'";
															$this->db->query($update_query_permission);////////////////NEXT

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

														$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$row->sale_id."',
						'0',
						'0',
						'MRP',
						'".round($real_total_sale_amount)."',
						'0',
						'".round($permission_total_my)."',
						'".round($permission_total_my)."',
						'".round($permission_total_my)."',
						'0')";
														$this->db->query($query);////NEXT
														$current_cash=$current_cash-round($permission_total_my);
													}
												}
											}
										}
									}else{
										break;
									}
								}
							}
						}
					}
				}
			}
		}
		return true;
	}

	function product_price_discount($current_date=""){


		////////////////////////////PERMISSION PRODUCT ///////////////////////////////////////////

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

		$current_directory = getcwd();

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

		}else{
			$config_mrp['MRP_DIS_ACTIVE']=0;
		}

		if($current_date<'2024-04-13'){///////////////////////////OFF FOR FLAT DISCOUNT/////////////////////////////

			if($config_mrp['MRP_ACTIVE']==1){
				$config_mrp['MRP_DIS_ACTIVE']=1;
				$config_mrp['MRP_DIS_RAND_START']=6000;
			}
		}






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

			//$count_invoice_no=0;
			$count_invoice_no=2;
			/*$query_count = $this->db->query("SELECT COUNT(sale_id) AS count_sale_id FROM ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND acc_location='".LOCATION_CODE."'");

			foreach ($query_count->result() as $row_count) {
			$count_invoice_no=$row_count->count_sale_id;
			}*/
			if($count_invoice_no<=1){
				$config_mrp['MRP_DIS_ACTIVE']=0;
			}
		}

		if(intval($config_mrp['MRP_DIS_ACTIVE'])==1){
			if(intval($config_mrp['MRP_LUNCHBREAK'])==0){

				$day_name=date('D', strtotime($current_date));
				if($config_mrp['MRP_WEEKEND']!=$day_name){

					function displayDatesDiscount($date1, $date2, $format = 'Y-m-d' ) {
						$dates = array();
						$current = strtotime($date1);
						$date2 = strtotime($date2);
						$stepVal = '+1 day';
						while( $current <= $date2 ) {
							$dates[] = date($format, $current);
							$current = strtotime($stepVal, $current);
						}
						return $dates;
					}
					$date_array = displayDatesDiscount($config_mrp['MRP_MANAGER_LEAVE_START'], $config_mrp['MRP_MANAGER_LEAVE_END']);

					if (!in_array($current_date, $date_array)){


						$today_total_sale_amount=0;
						$today_total_mrp_amount=0;
						$minimum_permission_amount=0;

						/////////////////SPECIAL DISCOUNT//////////////////////
						$special_customer_id=array();

						$query_special = $this->db->query("SELECT id FROM pos_ospos_customers
					WHERE is_special=1 AND special_percentage>0");

						foreach ($query_special->result() as $row_special) {
							$special_customer_id[]=$row_special->id;
						}

						$consider_sale_id=array();
						$consider_sale_id_information=array();

						/////////////////SPECIAL DISCOUNT//////////////////////
						$query_all_sale = $this->db->query("SELECT a.* FROM ospos_sales AS a
					WHERE DATE_FORMAT(a.sale_time,'%Y-%m-%d')='".$current_date."' AND a.acc_location='".LOCATION_CODE."' AND a.payment_type!='' AND a.is_sync=0 AND (clr_sync=0 OR clr_sync IS NULL)");


						foreach ($query_all_sale->result() as $row_all) {

							if(intval($row_all->customer_id)!=0){
								if (!in_array(intval($row_all->customer_id), $special_customer_id)){
									$consider_sale_id[]=$row_all->sale_id;
									$consider_sale_id_information[$row_all->sale_id]=$row_all;
								}
							}else{
								$consider_sale_id[]=$row_all->sale_id;
								$consider_sale_id_information[$row_all->sale_id]=$row_all;
							}
						}

						$consider_sale_id_string="";
						$consider_sale_id_string="''";
						if(count($consider_sale_id)){
							$consider_sale_id_string="'".implode("','",$consider_sale_id)."'";
						}



						$query = $this->db->query("SELECT SUM(vat_enable_price) AS total_sale
		FROM ospos_sales_items_reprint WHERE sale_id IN (".$consider_sale_id_string.") AND discount_percent>0");

						foreach ($query->result() as $row) {
							$today_total_sale_amount=$row->total_sale;
						}

						$query = $this->db->query("SELECT SUM(purchase_discount_my) AS total_mrp
		FROM ospos_permissions_relations_customer 
		WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date."' AND loc_code='".LOCATION_CODE."' AND payment_type='MRP' AND purchase_discount>0 AND sales_id IN (".$consider_sale_id_string.")");

						foreach ($query->result() as $row) {
							$today_total_mrp_amount=$row->total_mrp;
						}

						$maximum_permission_percentage=(rand($config_mrp['MRP_DIS_RAND_START'], ($config_mrp['MRP_DIS_RAND_START']+100))/100);//////////////////////SET AS MY WISH

						if($current_date<'2024-04-13'){///////////////////////////OFF FOR FLAT DISCOUNT/////////////////////////////
							$minimum_permission_amount=round(($today_total_sale_amount*$maximum_permission_percentage)/100);
						}else{

							$minimum_permission_amount=round(($today_total_sale_amount*$maximum_permission_percentage)/100)-round($today_total_mrp_amount);

						}

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

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

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

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

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

							}

							$current_cash=0;

							$query_cash = $this->db->query("SELECT SUM(payment_amount) AS total_cash FROM ospos_sales_payments WHERE sale_id IN (".$consider_sale_id_string.") AND  payment_type='CASH'");

							foreach ($query_cash->result() as $row_cash) {
								$current_cash=$row_cash->total_cash;/////////////////////NEXT CONSIDER
							}


							$sql_create="CREATE TABLE IF NOT EXISTS `stock_moves_reprint` (
  `trans_id` int(11) NOT NULL AUTO_INCREMENT,
  `stock_id` char(20) NOT NULL DEFAULT '',
  `loc_code` char(5) NOT NULL DEFAULT '',
  `price` double NOT NULL DEFAULT '0',
  `standard_cost` double NOT NULL DEFAULT '0',
  `visible` tinyint(1) NOT NULL DEFAULT '1',
  `lot_no` int(10) DEFAULT '0',
  `is_imported` smallint(6) NOT NULL DEFAULT '0',
  `swatch_code` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`trans_id`))";
							$this->db->query($sql_create);


							$query_moves_count = $this->db->query("SELECT count(*) AS count_st FROM stock_moves_reprint");


							$has_count=0;
							foreach ($query_moves_count->result() as $row_moves_count) {
								$has_count=intval($row_moves_count->count_st);
							}

							if(intval($has_count)==0){
								$query_moves_insert = $this->db->query("SELECT
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code
		  FROM stock_moves AS a WHERE price!=0 AND standard_cost!=0
		  GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no DESC");


								$insert_query="INSERT INTO stock_moves_reprint (
		stock_id,
		  loc_code,
		  price,
		  standard_cost,
		  visible,
		  lot_no,
		  is_imported,
		  swatch_code) VALUES
		";

								foreach ($query_moves_insert->result() as $row_compare) {

									$row_compare_implode=array();

									foreach ($row_compare as $key => $value) {
										$row_compare_implode[]=$value;
									}
									if(count($row_compare_implode)){
										$insert_query.='(';
										$insert_query.="'".implode("','",$row_compare_implode)."'";
										$insert_query.='),';
									}
								}

								$insert_query=substr($insert_query, 0, -1)."";
								$this->db->query($insert_query);

							}


							$description_wise_minimum=array();
							$category_wise_minimum=array();
							$stock_id_filter=array();

							if(LOCATION_CODE=="UTA"){
								$description_wise_minimum['Lungi']=200000;
								$description_wise_minimum['Male Full Shirt']=650;
								$description_wise_minimum['Male Half Shirt']=530;
								$description_wise_minimum['Male Half Fatua']=623;
								$description_wise_minimum['Male Full Fatua']=530;
								$description_wise_minimum['Sharee']=800;
								$description_wise_minimum['Gamcha Fabric']=20000;
								$description_wise_minimum['Gamcha']=20000;
								$description_wise_minimum['Boy Trowzer']=521;
								$description_wise_minimum['Female Trowzer']=521;
								$description_wise_minimum['Male Trowzer']=521;
								$description_wise_minimum['Male Three Quarter']=421;
								$description_wise_minimum['Female SHAL']=781;
								$description_wise_minimum['Male Panjabi']=711;
								$description_wise_minimum['Blazer']=3491;

								$description_wise_minimum['Male Gabardine Pant']=650;
								$description_wise_minimum['Batik Sharee']=999;
								$description_wise_minimum['Endy Sharee']=999;
								$description_wise_minimum['Girl Sharee']=999;
								$description_wise_minimum['Gray Sharee']=999;
								$description_wise_minimum['Katan Sharee']=999;
								$description_wise_minimum['Sharee']=999;
								$description_wise_minimum['Sharee Blockprint']=999;
								$description_wise_minimum['Sharee Half Silk']=999;
								$description_wise_minimum['Sharee Handprint']=999;
								$description_wise_minimum['Sharee Handwork']=999;
								$description_wise_minimum['Sharee Screen Print']=999;
								$description_wise_minimum['Sharee Silk']=999;
								$description_wise_minimum['Tissue sharee']=999;
								$description_wise_minimum['3 Piece']=999;
								$description_wise_minimum['Batik Three Piece']=999;
								$description_wise_minimum['Blouse Piece']=999;
								$description_wise_minimum['Female Loose  One piece']=999;
								$description_wise_minimum['Female One piece']=999;
								$description_wise_minimum['Female Two piece']=999;
								$description_wise_minimum['Girl One Piece']=999;
								$description_wise_minimum['Girl Three Piece']=999;
								$description_wise_minimum['Girl Two Piece']=999;
								$description_wise_minimum['Loose Three Piece']=999;
								$description_wise_minimum['One Piece']=999;
								$description_wise_minimum['Showpiece']=999;
								$description_wise_minimum['Three Piece']=999;
								$description_wise_minimum['Vegetable dai Three Piece']=999;
								$description_wise_minimum['GC Three Pice']=999;
								$description_wise_minimum['Ladies Kurti']=999;


								$description_wise_minimum['Bed Sheet']=750;
								$description_wise_minimum['Bed Sheet Aplic']=750;
								$description_wise_minimum['Bed Sheet Block Print']=750;
								$description_wise_minimum['Bed Sheet Dubble']=750;
								$description_wise_minimum['Bed Sheet Dubble-Manufactured']=750;
								$description_wise_minimum['Bed Sheet Nokshi']=750;
								$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=750;
								$description_wise_minimum['Bed Sheet Semi-Dubble']=750;
								$description_wise_minimum['Bed Sheet Single']=750;
								$description_wise_minimum['Bed Sheet Single-Manufactured']=750;

								$description_wise_minimum['Male Full Shirt']=1900;
								$description_wise_minimum['Male Half Shirt']=1300;
								$description_wise_minimum['Male Half Fatua']=1300;
								$description_wise_minimum['Male Full Fatua']=1900;
								$description_wise_minimum['Male Jeans Pant']=650;
								$description_wise_minimum['Male Gabardine Pant']=650;
								$description_wise_minimum['Male Polo Shirt']=450;
								$description_wise_minimum['Male T- Shirt']=450;
								$description_wise_minimum['Male T- Shirt']=450;
								$description_wise_minimum['Boy T-Shirt']=450;

								if(LOCATION_CODE=="RAN"){
									$description_wise_minimum['Male Full Shirt']=1900;
									$description_wise_minimum['Male Half Shirt']=1300;
									$description_wise_minimum['Male Half Fatua']=1300;
									$description_wise_minimum['Male Full Fatua']=1900;
									$description_wise_minimum['Male Jeans Pant']=650;
									$description_wise_minimum['Male Gabardine Pant']=650;
									$description_wise_minimum['Male Polo Shirt']=450;
									$description_wise_minimum['Male T- Shirt']=450;
									$description_wise_minimum['Male T- Shirt']=450;
									$description_wise_minimum['Boy T-Shirt']=450;
								}
								///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////
								$current_directory = getcwd();
								$filename=$current_directory . '\pdf_report\report_file_runtime\product_minimum_price.txt';
								if (file_exists($filename)) {
									if ($fd = fopen($filename, 'rb')) {
										$saved_data = fread($fd, filesize($filename));
										fclose($fd);
										$description_wise_minimum_json_decode = json_decode(trim($saved_data), false);
										foreach ($description_wise_minimum_json_decode as $jeson_key => $jeson_value) {
											$description_wise_minimum[trim($jeson_key)]=trim($jeson_value);
										}
									}
								}
								///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////

								$category_wise_minimum['56']=100000;////Handicraft

							}else{
								$description_wise_minimum['Lungi']=200000;
								$description_wise_minimum['Male Full Shirt']=650;
								$description_wise_minimum['Male Half Shirt']=530;
								$description_wise_minimum['Male Half Fatua']=623;
								$description_wise_minimum['Male Full Fatua']=530;
								$description_wise_minimum['Sharee']=800;
								$description_wise_minimum['Gamcha Fabric']=20000;
								$description_wise_minimum['Gamcha']=20000;
								$description_wise_minimum['Boy Trowzer']=521;
								$description_wise_minimum['Female Trowzer']=521;
								$description_wise_minimum['Male Trowzer']=521;
								$description_wise_minimum['Male Three Quarter']=421;
								$description_wise_minimum['Female SHAL']=781;
								$description_wise_minimum['Male Panjabi']=711;
								$description_wise_minimum['Blazer']=3491;

								$description_wise_minimum['Male Gabardine Pant']=650;
								$description_wise_minimum['Batik Sharee']=999;
								$description_wise_minimum['Endy Sharee']=999;
								$description_wise_minimum['Girl Sharee']=999;
								$description_wise_minimum['Gray Sharee']=999;
								$description_wise_minimum['Katan Sharee']=999;
								$description_wise_minimum['Sharee']=999;
								$description_wise_minimum['Sharee Blockprint']=999;
								$description_wise_minimum['Sharee Half Silk']=999;
								$description_wise_minimum['Sharee Handprint']=999;
								$description_wise_minimum['Sharee Handwork']=999;
								$description_wise_minimum['Sharee Screen Print']=999;
								$description_wise_minimum['Sharee Silk']=999;
								$description_wise_minimum['Tissue sharee']=999;
								$description_wise_minimum['3 Piece']=999;
								$description_wise_minimum['Batik Three Piece']=999;
								$description_wise_minimum['Blouse Piece']=999;
								$description_wise_minimum['Female Loose  One piece']=999;
								$description_wise_minimum['Female One piece']=999;
								$description_wise_minimum['Female Two piece']=999;
								$description_wise_minimum['Girl One Piece']=999;
								$description_wise_minimum['Girl Three Piece']=999;
								$description_wise_minimum['Girl Two Piece']=999;
								$description_wise_minimum['Loose Three Piece']=999;
								$description_wise_minimum['One Piece']=999;
								$description_wise_minimum['Showpiece']=999;
								$description_wise_minimum['Three Piece']=999;
								$description_wise_minimum['Vegetable dai Three Piece']=999;
								$description_wise_minimum['GC Three Pice']=999;
								$description_wise_minimum['Ladies Kurti']=999;

								$description_wise_minimum['Bed Sheet']=750;
								$description_wise_minimum['Bed Sheet Aplic']=750;
								$description_wise_minimum['Bed Sheet Block Print']=750;
								$description_wise_minimum['Bed Sheet Dubble']=750;
								$description_wise_minimum['Bed Sheet Dubble-Manufactured']=750;
								$description_wise_minimum['Bed Sheet Nokshi']=750;
								$description_wise_minimum['Bed Sheet Semi Dubble-Manufactured']=750;
								$description_wise_minimum['Bed Sheet Semi-Dubble']=750;
								$description_wise_minimum['Bed Sheet Single']=750;
								$description_wise_minimum['Bed Sheet Single-Manufactured']=750;

								$description_wise_minimum['Male Full Shirt']=1900;
								$description_wise_minimum['Male Half Shirt']=1300;
								$description_wise_minimum['Male Half Fatua']=1300;
								$description_wise_minimum['Male Full Fatua']=1900;
								$description_wise_minimum['Male Jeans Pant']=650;
								$description_wise_minimum['Male Gabardine Pant']=650;
								$description_wise_minimum['Male Polo Shirt']=450;
								$description_wise_minimum['Male T- Shirt']=450;
								$description_wise_minimum['Male T- Shirt']=450;
								$description_wise_minimum['Boy T-Shirt']=450;

								if(LOCATION_CODE=="RAN"){
									$description_wise_minimum['Male Full Shirt']=1900;
									$description_wise_minimum['Male Half Shirt']=1300;
									$description_wise_minimum['Male Half Fatua']=1300;
									$description_wise_minimum['Male Full Fatua']=1900;
									$description_wise_minimum['Male Jeans Pant']=650;
									$description_wise_minimum['Male Gabardine Pant']=650;
									$description_wise_minimum['Male Polo Shirt']=450;
									$description_wise_minimum['Male T- Shirt']=450;
									$description_wise_minimum['Male T- Shirt']=450;
									$description_wise_minimum['Boy T-Shirt']=450;
								}

								///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////
								$current_directory = getcwd();
								$filename=$current_directory . '\pdf_report\report_file_runtime\product_minimum_price.txt';
								if (file_exists($filename)) {
									if ($fd = fopen($filename, 'rb')) {
										$saved_data = fread($fd, filesize($filename));
										fclose($fd);
										$description_wise_minimum_json_decode = json_decode(trim($saved_data), false);
										foreach ($description_wise_minimum_json_decode as $jeson_key => $jeson_value) {
											$description_wise_minimum[trim($jeson_key)]=trim($jeson_value);
										}
									}
								}
								///////////////////////////PRICE UPDATE BY REFERENCE/////////////////////////////////////

								$category_wise_minimum['56']=100000;////Handicraft

							}

							if(count($description_wise_minimum)){
								$clause_string="";
								$where_string_description=array();
								foreach ($description_wise_minimum as $clause_key => $clause_value) {
									$clause_string.=" WHEN description = '".$clause_key."' THEN ".$clause_value." ";
									$where_string_description[]=$clause_key;
								}
								$where_string_description_string="'".implode("','",$where_string_description)."'";

								$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where description IN(".$where_string_description_string.")");


								foreach ($query_filter->result() as $row_filter) {
									if(intval($row_filter->price)){
										$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
									}
								}
							}

							if(count($category_wise_minimum)){
								$clause_string="";
								$where_string_description=array();
								foreach ($category_wise_minimum as $clause_key => $clause_value) {
									$clause_string.=" WHEN category_id = '".$clause_key."' THEN ".$clause_value." ";
									$where_string_description[]=$clause_key;
								}
								$where_string_description_string="'".implode("','",$where_string_description)."'";

								$query_filter = $this->db->query("SELECT stock_id,description,(CASE
        													  ".$clause_string."
   															  END) AS price
															  FROM stock_master where category_id IN(".$where_string_description_string.")");


								foreach ($query_filter->result() as $row_filter) {
									if(intval($row_filter->price)){
										$stock_id_filter[$row_filter->stock_id]=$row_filter->price;
									}
								}

							}



							//////ALL SALES IDS today////////

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

							$all_sale_ids=array();
							$query_sale_ids = $this->db->query("SELECT sale_id FROM  ospos_sales WHERE DATE_FORMAT(sale_time,'%Y-%m-%d')='".$current_date_reprint."'");

							foreach ($query_sale_ids->result() as $row_sale_ids) {
								$all_sale_ids[]=$row_sale_ids->sale_id;
							}

							$consider_all_sale_ids_string="'".implode("','",$all_sale_ids)."'";

							////////////////////////////22-03-2024//////////////////////////////////////////

							$skb_2024_same_price_product_sale_count=array();

							$query_skb_2024 = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_all_sale_ids_string.") AND quantity_purchased>0 AND discount_percent>0 AND (mrp_details!='' OR pcr_lot_no!='') ");

							foreach ($query_skb_2024->result() as $row_2024) {
								$skb_2024_same_price_product_sale_count[$row_2024->stock_id.$row_2024->lot_no.intval($row_2024->item_cost_price)]+=intval($row_2024->quantity_purchased);
							}

							$skb_2024_same_price_product_sale_omit=array();
							foreach ($skb_2024_same_price_product_sale_count as $key_qty => $value_qty) {
								if($value_qty>3){
									$skb_2024_same_price_product_sale_omit[]=$key_qty;
								}
							}
							$skb_2024_same_price_product_sale_omit_str="";

							if(count($skb_2024_same_price_product_sale_omit)){
								$skb_2024_same_price_product_sale_omit_implode="'".implode("','",$skb_2024_same_price_product_sale_omit)."'";
								$skb_2024_same_price_product_sale_omit_str=" AND CONCAT(stock_id,lot_no,CAST(price AS UNSIGNED)) NOT IN(".$skb_2024_same_price_product_sale_omit_implode.") ";
							}
							////////////////////////////22-03-2024//////////////////////////////////////////


							$query = $this->db->query("SELECT * FROM ospos_sales_items WHERE sale_id IN (".$consider_sale_id_string.") AND quantity_purchased>0 AND stock_id NOT IN ('03500002','06139020','05639004') AND discount_percent>0 AND (mrp_details='' OR mrp_details IS NULL) ORDER BY item_cost_price DESC,vat_enable_price_after_discount DESC, quantity_purchased ASC ");

							foreach ($query->result() as $row) {
								if($minimum_permission_amount>0){
									///////////////////////////////////STOCK MOVES/////////////////////
									if(intval($has_count)>0){
										if(array_key_exists ( $row->stock_id, $stock_id_filter)){
											$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no<210000
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no ASC");

										}else{
											$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves_reprint AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.lot_no<210000
									".$skb_2024_same_price_product_sale_omit_str."
									GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no ASC");
										}

										$has_stock_moves=array();

										$has_found=0;
										foreach ($query_moves->result() as $row_moves) {
											if($has_found==0){
												if((fmod($row_moves->price,1)== 0.00)){
													$has_stock_moves=$row_moves;
													$has_found=1;
													break;
												}
											}
										}
										if($has_found==0){

											if(array_key_exists ( $row->stock_id, $stock_id_filter)){
												$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.lot_no<210000
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."'
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price ORDER BY a.stock_id,a.price ASC,a.lot_no ASC");

											}else{
												$query_moves = $this->db->query("SELECT a.*
					FROM stock_moves_reprint AS a
					WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."')) AND a.lot_no<210000
					AND a.price<'".mysql_real_escape_string($row->item_cost_price)."'
					".$skb_2024_same_price_product_sale_omit_str."
					GROUP BY a.stock_id,a.price ORDER BY a.stock_id,a.price ASC,a.lot_no ASC");
											}
											foreach ($query_moves->result() as $row_moves) {
												if((fmod($row_moves->price,1)== 0.00)){
													$has_stock_moves=$row_moves;
													break;
												}
											}
										}

									}else{
										if(array_key_exists ( $row->stock_id, $stock_id_filter)){
											$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no<210000
									GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no ASC");

										}else{
											$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id='".mysql_real_escape_string($row->stock_id)."' AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.lot_no<210000
									GROUP BY a.stock_id,a.price ORDER BY a.price ASC,a.lot_no ASC");

										}

										$has_stock_moves=array();

										$has_found=0;
										foreach ($query_moves->result() as $row_moves) {
											if($has_found==0){
												if((fmod($row_moves->price,1)== 0.00)){
													$has_stock_moves=$row_moves;
													$has_found=1;
													break;
												}
											}
										}
										if($has_found==0){
											if(array_key_exists ( $row->stock_id, $stock_id_filter)){
												$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."'))
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.price>='".mysql_real_escape_string($stock_id_filter[$row->stock_id])."' AND a.lot_no<210000
									GROUP BY a.stock_id,a.price ORDER BY a.stock_id,a.price ASC,a.lot_no ASC");
											}else{
												$query_moves = $this->db->query("SELECT a.*
									FROM stock_moves AS a
									WHERE a.stock_id IN (SELECT stock_id FROM stock_master AS c WHERE c.description=(SELECT description FROM stock_master AS b WHERE  b.stock_id='".mysql_real_escape_string($row->stock_id)."'))
									AND a.price<'".mysql_real_escape_string($row->item_cost_price)."' AND a.lot_no<210000
									GROUP BY a.stock_id,a.price ORDER BY a.stock_id,a.price ASC,a.lot_no ASC");
											}
											foreach ($query_moves->result() as $row_moves) {
												if((fmod($row_moves->price,1)== 0.00)){
													$has_stock_moves=$row_moves;
													break;
												}
											}
										}
									}

									//////////////////////////////NEW PRICE CAL////////////////////////////////
									$compare_price_per_unit=0;
									$compare_price=0;
									$compare_price_per_unit=round($row->item_cost_price)-round($has_stock_moves->price);
									$compare_price=round($compare_price_per_unit*$row->quantity_purchased);

									$consider_qty=$row->quantity_purchased;

									if($compare_price>$minimum_permission_amount){
										$consider_qty_min=round($minimum_permission_amount/$compare_price_per_unit);


										if($consider_qty_min<$consider_qty){
											$consider_qty=$consider_qty_min;

											if($consider_qty>0){
												$query_line = $this->db->query("SELECT MAX(line) As max_line FROM ospos_sales_items WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
												$max_line_result=$query_line->row();
												$next_line=intval($max_line_result->max_line)+1;


												$sales_items_data_second="INSERT INTO ospos_sales_items(
								sale_id,
								stock_id,
								description,
								lot_no,
								line,
								quantity_purchased,
								item_cost_price,
								item_unit_price,
								discount_percent,
								total_discount,
								total_sale_amount,
								vat_enable_price,
								vat_percentage,
								vat_amount,
								sales_employee_code,
								vat_enable_price_after_discount,
								pcr_lot_no,
								sync_permission,
								cus_permission) VALUES(
								'".$row->sale_id."',
								'".$row->stock_id."',
								'".$row->description."',
								'".$row->lot_no."',
								'".$next_line."',
								'".($row->quantity_purchased-$consider_qty)."',
								'".$row->item_cost_price."',
								'".$row->item_unit_price."',
								'".$row->discount_percent."',
								'".number_format(((($row->total_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".number_format(((($row->total_sale_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".number_format(((($row->vat_enable_price)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".$row->vat_percentage."',
								'".number_format(((($row->vat_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.','')."',
								'".$row->sales_employee_code."',
								'".round(((($row->vat_enable_price_after_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)))."',
								'".$row->pcr_lot_no."',
								'".$row->sync_permission."',
								'".$row->cus_permission."')";

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


												$sales_items_data_first="UPDATE ospos_sales_items SET
quantity_purchased='".($consider_qty)."',
total_discount='".($row->total_discount-number_format(((($row->total_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
total_sale_amount='".($row->total_sale_amount-number_format(((($row->total_sale_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_enable_price='".($row->vat_enable_price-number_format(((($row->vat_enable_price)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_amount='".($row->vat_amount-number_format(((($row->vat_amount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty)),2,'.',''))."',
vat_enable_price_after_discount='".($row->vat_enable_price_after_discount-round(((($row->vat_enable_price_after_discount)/$row->quantity_purchased)*($row->quantity_purchased-$consider_qty))))."'

WHERE sale_id='".($row->sale_id)."' 
AND stock_id='".($row->stock_id)."' 
AND lot_no='".($row->lot_no)."' 
AND line='".($row->line)."' 
AND quantity_purchased='".($row->quantity_purchased)."' 
AND item_cost_price='".($row->item_cost_price)."' 
AND item_unit_price='".($row->item_unit_price)."' 
AND discount_percent='".($row->discount_percent)."' 
AND total_discount='".($row->total_discount)."' 
AND total_sale_amount='".($row->total_sale_amount)."' 
AND vat_enable_price='".($row->vat_enable_price)."' 
";
												$this->db->query($sales_items_data_first);///////////NEXT

												//$query_sales_reference = $this->db->query("SELECT * FROM ospos_sales WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
												//$row_sales_reference=$query_sales_reference->row();

												$row_sales_reference=$consider_sale_id_information[$row->sale_id];



												$query_line_moves = $this->db->query("SELECT * FROM stock_moves_reprint
										WHERE stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."'  AND lot_no<='210000' ");

												$row_stock_moves=$query_line_moves->row();

												$insert_stock_moves_second="INSERT INTO stock_moves(
								trans_no,			
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row->sale_id."',
								'".$row_stock_moves->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row->sale_id."',
								'".$row->item_cost_price."',
								'".$row_sales_reference->receipt_no."',
								'".($consider_qty*-1)."',
								'".$row_stock_moves->discount_percent."',
								'".$row_stock_moves->standard_cost."',
								'".$row_stock_moves->visible."',
								'".$row->lot_no."',
								'".$row_stock_moves->is_imported."',
								'".$row_stock_moves->swatch_code."')";

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

												$update_stock_moves_first="UPDATE stock_moves SET
				qty='".mysql_real_escape_string(($row->quantity_purchased-$consider_qty)*-1)."'
				WHERE type='201'
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND reference='".mysql_real_escape_string($row_sales_reference->receipt_no)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."'
				AND qty='".mysql_real_escape_string($row->quantity_purchased*-1)."'";

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

												$query_after_update = $this->db->query("SELECT * FROM ospos_sales_items
										WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'
										AND stock_id='".($row->stock_id)."' 
										AND lot_no='".($row->lot_no)."' 
										AND line='".($row->line)."' 
									    AND quantity_purchased='".($consider_qty)."' 										
										");

												$row=$query_after_update->row();
											}
										}else{
											$consider_qty=$row->quantity_purchased;
										}
									}else{
										$consider_qty=$row->quantity_purchased;
									}



									if($consider_qty>0){
										if(trim($has_stock_moves->stock_id)){

											//////////////////////////////ospos_sales////////////////
											$query_sales = $this->db->query("SELECT * FROM ospos_sales WHERE sale_id='".mysql_real_escape_string($row->sale_id)."'");
											$row_sales=$query_sales->row();

											$real_cash=0;//////////////////////////////
											$real_purchase_discount=0;/////////////////

											$has_real_cash=0;
											$has_purchase_discount=0;

											$real_item_cost_price=$row->item_cost_price;
											$real_total_sale_amount=$row->total_sale_amount;
											$real_vat_amount=$row->vat_amount;
											$real_vat_enable_price_after_discount=$row->vat_enable_price_after_discount;

											$sql_payment="SELECT  payment_amount FROM ospos_sales_payments WHERE sale_id ='".$row->sale_id."' AND payment_type='Cash' LIMIT 1";
											$query_payment = $this->db->query($sql_payment);
											foreach ($query_payment->result() as $row_payment) {
												$real_cash=$row_payment->payment_amount;
												$has_real_cash=1;
											}

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

											$real_total_sale_amount_sum=0;

											$sql_total_sale="SELECT  SUM(total_sale_amount) AS total_sale_amount_sum
				FROM ospos_sales_items WHERE sale_id ='".$row->sale_id."'";
											$query_total_sale = $this->db->query($sql_total_sale);
											foreach ($query_total_sale->result() as $row_total_sale) {
												$real_total_sale_amount_sum+=$row_total_sale->total_sale_amount_sum;
											}

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


											$final_cash=0;//////////////////////////////
											$final_purchase_discount=0;/////////////////

											$final_item_cost_price=$has_stock_moves->price;

											$final_unit_discount=round(number_format(($final_item_cost_price*$row->discount_percent)/100,2,'.',''));

											$final_item_unit_price=$final_item_cost_price-$final_unit_discount;

											$final_total_discount=number_format($final_unit_discount*$row->quantity_purchased,2,'.','');


											$final_total_sale_amount=number_format($final_item_unit_price*$row->quantity_purchased,2,'.','');
											$final_vat_enable_price=number_format($final_item_cost_price*$row->quantity_purchased,2,'.','');

											$final_vat_enable_price_after_discount=$final_total_sale_amount-round(($final_total_sale_amount*$real_purchase_discount_per_100)/100);
											$final_vat_amount=number_format($final_vat_enable_price_after_discount*$row->vat_percentage/100,2,'.','');


											$minimum_permission_amount=$minimum_permission_amount-($real_total_sale_amount-$final_total_sale_amount);


											$difference_purchase_discount=0;
											if($real_purchase_discount_per_100!=0){
												$difference_purchase_discount=round((($real_total_sale_amount*$real_purchase_discount_per_100)/100)-(($final_total_sale_amount*$real_purchase_discount_per_100)/100));
											}

											$permission_total_my=0;

											$permission_total_my=round(($real_vat_enable_price_after_discount+$real_vat_amount)-($final_vat_enable_price_after_discount+$final_vat_amount));


											if($current_cash>=$permission_total_my+129){

												$force_reference=substr($row_sales->receipt_no,3).substr($row_sales->receipt_no,0,3);
												$previous_date=date('Y-m-d', strtotime('-1 year', strtotime($current_date)) );

												$query_moves_mrp = $this->db->query("SELECT *
										FROM stock_moves_reprint
										WHERE stock_id='".mysql_real_escape_string($row->stock_id)."' 
										AND price='".mysql_real_escape_string($row->item_cost_price)."' AND lot_no<='210000'");

												$update_stock_moves_sales=$query_moves_mrp->row();


												///////////////////CONDITION/////////////////////

												$update_stock_moves="UPDATE stock_moves SET
				type=16,
				tran_date='".mysql_real_escape_string($previous_date)."',
				reference='".mysql_real_escape_string($force_reference)."'
				WHERE type='201'
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND reference='".mysql_real_escape_string($row_sales->receipt_no)."' 
				AND price='".mysql_real_escape_string($row->item_cost_price)."'
				AND qty='".mysql_real_escape_string($row->quantity_purchased*-1)."'";

												if(trim($update_stock_moves_sales->stock_id)){

													if(doubleval($update_stock_moves_sales->standard_cost)==0){
														$update_stock_moves_sales->standard_cost=number_format((($row->item_cost_price)*55)/100, 2,".","");
													}
													$update_stock_moves_sales->visible=1;

													$mrp_details=$update_stock_moves_sales->stock_id."#".$previous_date."#".$update_stock_moves_sales->price."#".$force_reference."#".($row->quantity_purchased*-1)."#".$update_stock_moves_sales->standard_cost."#".$update_stock_moves_sales->visible."#".$row->lot_no."#".$update_stock_moves_sales->is_imported."#".$update_stock_moves_sales->swatch_code;
												}else{

													$price_dummy=$row->item_cost_price;
													$standard_cost_dummy=number_format((($row->item_cost_price)*55)/100, 2,".","");
													$visible_dummy=1;
													$lot_no_dummy=$row->lot_no;
													$is_imported_dummy=0;
													$swatch_code_dummy=0;

													$mrp_details=$row->stock_id."#".$previous_date."#".$price_dummy."#".$force_reference."#".($row->quantity_purchased*-1)."#".$standard_cost_dummy."#".$visible_dummy."#".$lot_no_dummy."#".$is_imported_dummy."#".$swatch_code_dummy;
												}


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

												$mrp_details.="NEWMRP".$has_stock_moves->stock_id."#".$previous_date."#".$has_stock_moves->price."#".$force_reference."#".$row->quantity_purchased."#".$has_stock_moves->standard_cost."#".$has_stock_moves->visible."#".$has_stock_moves->lot_no."#".$has_stock_moves->is_imported."#".$has_stock_moves->swatch_code;

												$insert_stock_moves_sales="INSERT INTO stock_moves(
								trans_no,
								stock_id,
								type,
								loc_code,
								tran_date,
								person_id,
								price,
								reference,
								qty,
								discount_percent,
								standard_cost,
								visible,
								lot_no,
								is_imported,
								swatch_code) VALUES(
								'".$row->sale_id."',
								'".$has_stock_moves->stock_id."',
								'201',
								'".LOCATION_CODE."',
								'".$current_date."',
								'".$row->sale_id."',
								'".$has_stock_moves->price."',
								'".$row_sales->receipt_no."',
								'".($row->quantity_purchased*-1)."',
								'0',
								'".$has_stock_moves->standard_cost."',
								'".$has_stock_moves->visible."',
								'".$has_stock_moves->lot_no."',
								'".$has_stock_moves->is_imported."',
								'".$has_stock_moves->swatch_code."')";

												$this->db->query($update_stock_moves);////////////seedupriya
												$this->db->query($insert_stock_moves);////////////seedupriya
												$this->db->query($insert_stock_moves_sales);////////////seedupriya


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

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

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



												$update_sale_items="UPDATE ospos_sales_items SET
				stock_id='".mysql_real_escape_string($has_stock_moves->stock_id)."',
				description='".mysql_real_escape_string($cat_description."</br>".$item_description)."',
				lot_no='".mysql_real_escape_string($has_stock_moves->lot_no)."',
				item_cost_price='".mysql_real_escape_string($final_item_cost_price)."',
				item_unit_price='".mysql_real_escape_string($final_item_unit_price)."',
				total_discount='".mysql_real_escape_string($final_total_discount)."',
				total_sale_amount='".mysql_real_escape_string($final_total_sale_amount)."',
				vat_enable_price='".mysql_real_escape_string($final_vat_enable_price)."',
				vat_amount='".mysql_real_escape_string($final_vat_amount)."',
				vat_enable_price_after_discount='".mysql_real_escape_string($final_vat_enable_price_after_discount)."',
				mrp_details='".mysql_real_escape_string($mrp_details)."'

				WHERE sale_id='".mysql_real_escape_string($row->sale_id)."' 
				AND stock_id='".mysql_real_escape_string($row->stock_id)."' 
				AND lot_no='".mysql_real_escape_string($row->lot_no)."' 
				AND line='".mysql_real_escape_string($row->line)."' 
				AND quantity_purchased='".mysql_real_escape_string($row->quantity_purchased)."'
				AND item_cost_price='".mysql_real_escape_string($row->item_cost_price)."'
				AND total_sale_amount='".mysql_real_escape_string($row->total_sale_amount)."'
				AND vat_enable_price_after_discount='".mysql_real_escape_string($row->vat_enable_price_after_discount)."'"
												;

												$this->db->query($update_sale_items);////////////////Seedupriya

												if($has_real_cash){
													$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($real_cash-round($permission_total_my))."' WHERE sale_id='".$row->sale_id."' AND payment_type='Cash'";
													$this->db->query($update_query_permission);////////////////////////////////Seedupriya

												}else{
													if(round($permission_total_my)!=0){
														$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$row->sale_id."',
					'Cash',
					'-".round($permission_total_my)."')";
														$this->db->query($insert_sql);////////////////////Seedupriya
													}
												}
												if($has_purchase_discount){
													$update_query_permission="UPDATE ospos_sales_payments SET payment_amount='".($real_purchase_discount-round($difference_purchase_discount))."' WHERE sale_id='".$row->sale_id."' AND payment_type='Purchase Discount'";
													$this->db->query($update_query_permission);////////////////////////////////Seedupriya

												}else{
													if(round($difference_purchase_discount)!=0){
														$insert_sql="INSERT INTO  ospos_sales_payments(sale_id,payment_type,payment_amount)
					VALUES('".$row->sale_id."',
					'Purchase Discount',
					'-".round($difference_purchase_discount)."')";
														$this->db->query($insert_sql);////////////////////Seedupriya
													}
												}

												$query = "INSERT INTO ospos_permissions_relations_customer(
						loc_code,
						sale_time,
						sales_id,
						customer_id,
						customer_id_root,
						payment_type,
						cash_amount,
						purchase_discount,
						cash_amount_permission,
						purchase_discount_permission,
						purchase_discount_my,
						is_sync
						)
						VALUES('".LOCATION_CODE."',
						'".date("Y-m-d H:i:s",strtotime($current_date))."',
						'".$row->sale_id."',
						'0',
						'0',
						'MRP',
						'".round($real_total_sale_amount)."',
						'".round($row->discount_percent)."',
						'".round($permission_total_my)."',
						'".round($permission_total_my)."',
						'".round($permission_total_my)."',
						'0')";
												$this->db->query($query);////seedupriya


												$current_cash=$current_cash-round($permission_total_my);
											}
										}
									}
								}else{
									break;
								}
							}
						}
					}
				}
			}
		}

		return true;
	}



	function delete($sale_id) {
		//Run these queries as a transaction, we want to make sure we do all or nothing
		$this->db->trans_start();

		$this->db->delete('sales_payments', array('sale_id' => $sale_id));
		$this->db->delete('sales_items_taxes', array('sale_id' => $sale_id));
		$this->db->delete('sales_items', array('sale_id' => $sale_id));
		$this->db->delete('sales', array('sale_id' => $sale_id));

		$this->db->trans_complete();

		return $this->db->trans_status();
	}

	function get_sale_items($sale_id) {
		$this->db->from('sales_items');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}
	function get_sale_items_reprint($sale_id) {
		$this->db->from('sales_items_reprint');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}
	function get_sale_items_by_receive_id_local($sale_id) {
		$this->db->from('sales_items');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}

	function get_sale_items_by_receive_id_live($sale_id) {

		$this->db->set_dbprefix('');
		$this->db->from('pos_ospos_sales_items');
		$this->db->where('sale_id', $sale_id);
		$return_data=array();
		$return_data=$this->db->get();
		$this->db->set_dbprefix('ospos_');
		return $return_data;
	}

	function get_sale_payments($sale_id) {
		$this->db->from('sales_payments');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}

	function get_sale_payments_reprint($sale_id) {
		$this->db->from('sales_payments_reprint');
		$this->db->where('sale_id', $sale_id);
		return $this->db->get();
	}

	function get_customer($sale_id) {
		$this->db->from('sales');
		$this->db->where('sale_id', $sale_id);
		return $this->Customer->get_info($this->db->get()->row()->customer_id);
	}

	function get_customer_local($sale_id) {
		$this->db->from('sales');
		$this->db->where('sale_id', $sale_id);
		return $this->Customer->get_info($this->db->get()->row()->customer_id);
	}
	function get_customer_server($sale_id) {
		$this->db->set_dbprefix('');
		$this->db->from('pos_ospos_sales');
		$this->db->where('sale_id', $sale_id);
		$customer_info=$this->Customer->get_info($this->db->get()->row()->customer_id);
		$this->db->set_dbprefix('ospos_');
		return $customer_info;
	}

	//We create a temp table that allows us to do easy report/sales queries
	public function create_sales_items_temp_table() {
		$this->db->query("CREATE TEMPORARY TABLE " . $this->db->dbprefix('sales_items_temp') . "
		(SELECT date(sale_time) as sale_date, " . $this->db->dbprefix('sales_items') . ".sale_id, comment,payment_type, customer_id, employee_id, 
		" . $this->db->dbprefix('items') . ".item_id, supplier_id, quantity_purchased, item_cost_price, item_unit_price, SUM(percent) as item_tax_percent,
		discount_percent, (item_unit_price*quantity_purchased-item_unit_price*quantity_purchased*discount_percent/100) as subtotal,
		" . $this->db->dbprefix('sales_items') . ".line as line, " . $this->db->dbprefix('sales_items') . ".description as description,
		ROUND((item_unit_price*quantity_purchased-item_unit_price*quantity_purchased*discount_percent/100)*(1+(SUM(percent)/100)),2) as total,
		ROUND((item_unit_price*quantity_purchased-item_unit_price*quantity_purchased*discount_percent/100)*(SUM(percent)/100),2) as tax,
		(item_unit_price*quantity_purchased-item_unit_price*quantity_purchased*discount_percent/100) - (item_cost_price*quantity_purchased) as profit
		FROM " . $this->db->dbprefix('sales_items') . "
		INNER JOIN " . $this->db->dbprefix('sales') . " ON  " . $this->db->dbprefix('sales_items') . '.sale_id=' . $this->db->dbprefix('sales') . '.sale_id' . "
		INNER JOIN " . $this->db->dbprefix('items') . " ON  " . $this->db->dbprefix('sales_items') . '.stock_id=' . $this->db->dbprefix('items') . '.item_id' . "
		LEFT OUTER JOIN " . $this->db->dbprefix('suppliers') . " ON  " . $this->db->dbprefix('items') . '.supplier_id=' . $this->db->dbprefix('suppliers') . '.person_id' . "
		LEFT OUTER JOIN " . $this->db->dbprefix('sales_items_taxes') . " ON  "
		. $this->db->dbprefix('sales_items') . '.sale_id=' . $this->db->dbprefix('sales_items_taxes') . '.sale_id' . " and "
		. $this->db->dbprefix('sales_items') . '.stock_id=' . $this->db->dbprefix('sales_items_taxes') . '.item_id' . " and "
		. $this->db->dbprefix('sales_items') . '.line=' . $this->db->dbprefix('sales_items_taxes') . '.line' . "
		GROUP BY sale_id, stock_id, line)");

		//Update null item_tax_percents to be 0 instead of null
		$this->db->where('item_tax_percent IS NULL');
		$this->db->update('sales_items_temp', array('item_tax_percent' => 0));

		//Update null tax to be 0 instead of null
		$this->db->where('tax IS NULL');
		$this->db->update('sales_items_temp', array('tax' => 0));

		//Update null subtotals to be equal to the total as these don't have tax
		$this->db->query('UPDATE ' . $this->db->dbprefix('sales_items_temp') . ' SET total=subtotal WHERE total IS NULL');
	}

	public function get_giftcard_value($giftcardNumber) {
		if (!$this->Giftcard->exists($this->Giftcard->get_giftcard_id($giftcardNumber)))
		return 0;

		$this->db->from('giftcards');
		$this->db->where('giftcard_number', $giftcardNumber);
		return $this->db->get()->row()->value;
	}

	function insert_user_points($table, $data) {
		$this->db->insert($table, $data);
		return $this->db->insert_id();
	}

	function get_value($column, $table, $where = '') {
		$this->db->select($column);
		$this->db->from($table);
		if ($where) {
			foreach ($where as $key => $val) {
				$this->db->where($key, $val);
			}
		}

		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return $query->row();
		} else {
			return FALSE;
		}
		$query->free_result();
	}

	function insert_data($table, $data) {
		$this->db->insert($table, $data);
		return $this->db->insert_id();
	}
	function update_data($table, $data, $where)
	{
		$res = $this->db->update($table, $data, $where);
		if ($res) {
			return true;
		} else {
			return false;
		}
	}

	function getPointCost() {
		$this->db->select('value');
		$this->db->from('app_config');
		$this->db->where('key', 'point_per_sell');
		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return $query->row();
		} else {
			return FALSE;
		}
		$query->free_result();
	}

	public function get_sale_by_invoice_number($invoice_number) {
		$this->db->from('sales');
		$this->db->where('sale_id', $invoice_number);

		return $this->db->get();
	}

	public function get_sale_by_invoice_number_shawpon_local($invoice_number) {
		$this->db->from('sales');
		$this->db->where('receipt_no', $invoice_number);
		return $this->db->get();
	}
	public function get_sale_by_invoice_number_shawpon_local_reprint($invoice_number) {
		$this->db->from('sales_reprint');
		$this->db->where('receipt_no', $invoice_number);
		return $this->db->get();
	}
	public function get_sale_by_invoice_number_shawpon_server($invoice_number) {
		$this->db->set_dbprefix('');
		$this->db->from('pos_ospos_sales');
		$this->db->where('receipt_no', $invoice_number);
		$return_data=$this->db->get();
		$this->db->set_dbprefix('ospos_');
		return $return_data;
	}

	public function get_global_items($sale_id){
		$this->db->select('*');
		$this->db->from('sales');
		$this->db->where('sales.sale_id', $sale_id);
		$this->db->where('sales.receive_location', 0);
		$this->db->join('sales_items', 'sales.sale_id = sales_items.sale_id','INNER');

		$query = $this->db->get();
		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return FALSE;
		}
		$query->free_result();
	}


	public function get_global_items_shawpon($sale_id){

		$query = $this->db->query("
                    SELECT a.*,b.*,CONCAT(c.first_name,' ',c.last_name) AS customer_name,c.phone_number,c.previous_due,
                    d.description AS item_description,e.size AS item_size
                    ,f.description AS category_description
FROM ospos_sales AS a
INNER JOIN ospos_sales_items AS b ON a.sale_id=b.sale_id
LEFT JOIN pos_ospos_customers AS c ON a.customer_id=c.id
LEFT JOIN stock_master AS d ON b.stock_id=d.stock_id
LEFT JOIN stock_category AS f ON d.category_id=f.category_id
LEFT JOIN pos_item_sizes AS e ON d.item_size_id=e.id
WHERE a.receipt_no='".$sale_id."' AND a.receive_location='".LOCATION_CODE."' AND a.is_global=1 AND is_delivered=0");


		if ($query->num_rows() > 0) {
			return $query->result();
		} else {
			return FALSE;
		}
		$query->free_result();
	}


	public function get_sale_payments_data_shawpon($sale_id)
	{
		$this->db->from('sales_payments');
		$this->db->where('sale_id',$sale_id);
		return $this->db->get();
	}

	public function update_delivery_global($receipt_no,$bag_big,$bag_medium,$bag_small)
	{
		$this->db->where('receipt_no', $receipt_no);
		$success = $this->db->update('ospos_sales', array('is_delivered' => 1,'bag_big' => $bag_big,'bag_medium' => $bag_medium,'bag_small' => $bag_small));

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

		$this->db->from('sales');
		$this->db->where('receipt_no',$receipt_no);
		$sales_info_obj=$this->db->get();
		$sales_info_array=$sales_info_obj->result();

		$sales_info=$sales_info_array[0];

		if(intval($bag_big)>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sales_info->sale_id,
			'stock_id' => BIG_BAG_CODE,
			'type' => 201,
			'loc_code' => $sales_info->receive_location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sales_info->sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($bag_big),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$success=$this->db->insert('stock_moves', $stock_moves_data);
		}
		if(intval($bag_medium)>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sales_info->sale_id,
			'stock_id' => MEDIUM_BAG_CODE,
			'type' => 201,
			'loc_code' => $sales_info->receive_location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sales_info->sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($bag_medium),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$success=$this->db->insert('stock_moves', $stock_moves_data);
		}
		if(intval($bag_small)>0){
			$this->db->set_dbprefix('');
			$stock_moves_data = array(
			'trans_no' => $sales_info->sale_id,
			'stock_id' => SMALL_BAG_CODE,
			'type' => 201,
			'loc_code' => $sales_info->receive_location,
			'tran_date' => date('Y-m-d H:i:s'),
			'person_id' => $sales_info->sale_id,
			'price' => 0,
			'reference' => $receipt_no,
			'qty' => -intval($bag_small),
			'discount_percent' => 0,
			'standard_cost' => 0,
			'visible' => 0,
			'lot_no' => 0,
			'is_imported' => 0,
			'swatch_code' => 0
			);
			$success=$this->db->insert('stock_moves', $stock_moves_data);
		}

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

		return $success;
	}

}

?>