HEX
Server: Apache/2.2.15 (CentOS)
System: Linux ip-10-0-2-146.eu-west-1.compute.internal 2.6.32-754.35.1.el6.centos.plus.x86_64 #1 SMP Sat Nov 7 11:33:42 UTC 2020 x86_64
User: root (0)
PHP: 5.6.40
Disabled: NONE
Upload Files
File: /www/exchange2/exchange/classes/Model/MTradeFloor.php
<?php
include_once(ROOT_FOLDER . 'admin/classes/Model/trade_actions.php');
class Model_MTradeFloor extends Trade_actions
{
	var $output = array();
	
	//Trade Floor Json
	function getTradeJson(){
		
		if($_SESSION['invFloorFlag'] == '1'){
			unset($_SESSION['invFloorFlag']);
			exit;
		}
		
		if($_SESSION['invBookFlag'] == '1'){
			unset($_SESSION['invBookFlag']);
			exit;
		}
		
		$where					= '';
		$query					= new Bin_Query();
		$sql 					= "SELECT * FROM invoice_bidding $where group by invoice_id "; //LIMIT 30
		$query->executeQuery($sql);
		$invoice				= $query->records;
	
		foreach($invoice as $key){
	
			$querys				= new Bin_Query();
			$sqls 				= "SELECT   
								m.*, d.currency_id , dm.debtor_insurance_cost,
								c.currency_code 
								
								FROM 
								`organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
								`invoice_master` as m ,currencies as c , debtors_master as dm
								
								WHERE  
								d.debtor_id = m.debtor_id && m.draft = 0 && r.debtor_id = d.debtor_id  && dm.debtor_master_id = d.parent_id
								&& org.organisation_id =  r.organisation_id &&
								c.currency_id = d.currency_id  &&
								m.invoice_id = '".$key['invoice_id']."' group by m.invoice_id LIMIT 1";


		
		
			$querys->executeQuery($sqls);
			$tradefloor 		= $querys->records[0];
		
			
			$clquery			= new Bin_Query();
			$closed_sql 		= "SELECT * FROM `invoice_closed` WHERE `invoice_id` = '".$key['invoice_id']."' LIMIT 1";
			$clquery->executeQuery($closed_sql);
			$closed_sbid 		= $clquery->records;
			
		
			if(count($closed_sbid) > 0){
				
				
	
				if($tradefloor['sales_type'] == 1){
					
					if($_REQUEST['area'] == 'floor'){
					
						if($_SESSION['closedInvFloor'][$tradefloor['invoice_id']] != $closed_sbid[0]['min_advance']){
							
							if($_SESSION['closedInvFloor'][$tradefloor['invoice_id']] ==''){
								$flag 	= 0;
							}else{							
								$flag 	= 1;
							}
							$_SESSION['closedInvFloor'][$tradefloor['invoice_id']] = $closed_sbid[0]['min_advance'];
						}else{
							$flag 	= 0;
						}
					}else{
						
						if($_SESSION['closedInvBook'][$tradefloor['invoice_id']] != $closed_sbid[0]['min_advance']){
							if($_SESSION['closedInvBook'][$tradefloor['invoice_id']] ==''){
								$flag 	= 0;
							}else{							
								
								$flag 	= 1;
							}
							$_SESSION['closedInvBook'][$tradefloor['invoice_id']] = $closed_sbid[0]['min_advance'];
						}else{
							$flag 	= 0;
						}	
						
					}
						
					
				}else{
					if($_REQUEST['area'] == 'floor'){
					
						if($_SESSION['closedInvFloor'][$tradefloor['invoice_id']] != $closed_sbid[0]['max_thirty_reserve']){
							
							if($_SESSION['closedInvFloor'][$tradefloor['invoice_id']] ==''){
								$flag 	= 0;
							}else{							
								$flag 	= 1;
							}
							$_SESSION['closedInvFloor'][$tradefloor['invoice_id']] = $closed_sbid[0]['max_thirty_reserve'];
						}else{
							$flag 	= 0;
						}
						
					}else{
						
						if($_SESSION['closedInvBook'][$tradefloor['invoice_id']] != $closed_sbid[0]['max_thirty_reserve']){
							
							if($_SESSION['closedInvBook'][$tradefloor['invoice_id']] ==''){
								$flag 	= 0;
							}else{							
								
								$flag 	= 1;
							}
							$_SESSION['closedInvBook'][$tradefloor['invoice_id']] = $closed_sbid[0]['max_thirty_reserve'];

						}else{
							$flag 	= 0;
						}	
					}
				}
				
				$user_sql  		= "SELECT organisation_reference_id FROM organisation_details ".
								" WHERE user_id= ".$closed_sbid[0]['won_by']." LIMIT 1";
	
				$user_query		= new Bin_Query();
				$user_query->executeQuery($user_sql);
				$user_details	= $user_query->records[0];
				$investor_id 	= $user_details['organisation_reference_id'];
	
				
				$myjson[] 		= array("id" => $closed_sbid[0]['invoice_id'],
								"min" =>"&nbsp;", 
								"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
								"style" =>'ED1C24',
								"flag" =>$flag,
								"invs"=>$investor_id,
								"closed"=>'1',
								"sales"=>$tradefloor['sales_type']);
			}else{
	
				if($tradefloor['sales_type'] == 1){
					$sql1 		= "SELECT * FROM invoice_bidding WHERE invoice_id= ".$key['invoice_id']." 
								order by min_advance DESC LIMIT 1";
				}
				else {
					$sql1 		= "SELECT * FROM invoice_bidding WHERE invoice_id= ".$key['invoice_id']." 
								order by max_thirty_reserve ASC LIMIT 1";
				}
	
				$query1			= new Bin_Query();
				$query1->executeQuery($sql1);
				$invoice1		= $query1->records[0];
				
				
				$user_sql 		= "SELECT organisation_reference_id FROM organisation_details ".
								" WHERE user_id= ".$invoice1['user_id']." LIMIT 1";
	
				$user_query		= new Bin_Query();
				$user_query->executeQuery($user_sql);
				$user_details	= $user_query->records[0];
				$investor_id 	= $user_details['organisation_reference_id'];
	
	
				/*$flag						= '1';*/
				if($_SESSION['user']['usertype'] == 1 || $_SESSION['user']['usertype'] == 2){
					
	
					$bid_query				= new Bin_Query();
					$bid_sql 				= "SELECT * FROM invoice_bidding_history WHERE ".
											" invoice_id = '".$invoice1['invoice_id']."' ORDER BY history_id DESC LIMIT 1";
					$bid_query->executeQuery($bid_sql);
					$history 				= $bid_query->records;
					
					if($tradefloor['sales_type'] =="1"){
									
						if($_REQUEST['area'] == 'floor'){
							
							if($_SESSION['invFloor'][$tradefloor['invoice_id']] != $history[0]['min_advance']){
								$_SESSION['invFloor'][$tradefloor['invoice_id']] = $history[0]['min_advance'];
								$flag 	= 1;
							}else{
								
								if($_SESSION['invFloor'][$tradefloor['invoice_id']] == $history[0]['min_advance'] && $_SESSION['invUserID'][$tradefloor['invoice_id']] != $history[0]['user_id']){
									
									$flag 	= 1;
									$_SESSION['invUserID'][$tradefloor['invoice_id']] = $history[0]['user_id'];
								}else{
							
									$flag 	= 0;
									
								}
							}
						
						}else{
				
							if($_SESSION['invBook'][$tradefloor['invoice_id']] != $history[0]['min_advance']){
								$_SESSION['invBook'][$tradefloor['invoice_id']] = $history[0]['min_advance'];
								$flag 	= 1;
							}else{
								if($_SESSION['invBook'][$tradefloor['invoice_id']] == $history[0]['min_advance'] && $_SESSION['invBookUserID'][$tradefloor['invoice_id']] != $history[0]['user_id']){
									
									$flag 	= 1;
									$_SESSION['invBookUserID'][$tradefloor['invoice_id']] = $history[0]['user_id'];
								}else{
							
									$flag 	= 0;
									
								}
							}	
						}
					}else{
						
						if($_REQUEST['area'] == 'floor'){
							
							if($_SESSION['invFloor'][$tradefloor['invoice_id']] != $history[0]['max_thirty_reserve']){
								$_SESSION['invFloor'][$tradefloor['invoice_id']] = $history[0]['max_thirty_reserve'];
								$flag 	= 1;
							}else{
								if($_SESSION['invFloor'][$tradefloor['invoice_id']] == $history[0]['max_thirty_reserve'] && $_SESSION['invUserID'][$tradefloor['invoice_id']] != $history[0]['user_id']){
									
									$_SESSION['invUserID'][$tradefloor['invoice_id']] = $history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}
						
						}else{
				
							if($_SESSION['invBook'][$tradefloor['invoice_id']] != $history[0]['max_thirty_reserve']){
								$_SESSION['invBook'][$tradefloor['invoice_id']] = $history[0]['max_thirty_reserve'];
								$flag 	= 1;
							}else{
								if($_SESSION['invBook'][$tradefloor['invoice_id']] == $history[0]['max_thirty_reserve'] && $_SESSION['invBookUserID'][$tradefloor['invoice_id']] != $history[0]['user_id']){
									$_SESSION['invBookUserID'][$tradefloor['invoice_id']] = $history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}	
						}
					}
	
					if(count($history) ==0){
						$style				= "000000"; //black
						$flag				= 0;
					}else{
	
						$bid_query1			= new Bin_Query();
						$bid_sql1 			= "SELECT * FROM invoice_bidding WHERE ".
											" invoice_id = '".$invoice1['invoice_id']."' && ".
											" user_id ='".$_SESSION['user']['userid']."'";
						$bid_query1->executeQuery($bid_sql1);
						$history1 			= $bid_query1->records;
						
						if(count($history1) ==0){
							$style			= "3F48CC"; // blue
						}else{
							$bid_query		= new Bin_Query();
							
							if($tradefloor['sales_type'] == 1){
								$bid_sql 	= "SELECT * FROM invoice_bidding WHERE invoice_id = '".$invoice1['invoice_id']."' 
											order by min_advance DESC LIMIT 1";
							}
							else {
								$bid_sql 	= "SELECT * FROM invoice_bidding WHERE invoice_id = '".$invoice1['invoice_id']."' 
											order by max_thirty_reserve ASC LIMIT 1";
							}
							$bid_query->executeQuery($bid_sql);
							$history2 		= $bid_query->records[0];
	
							if($_SESSION['user']['userid'] != $history2['user_id']){
								$style		= "ED1C24"; //red
							}else{
								$style		= "22B14C"; //green
								
							}
						}
					}
	
				
				}else{
					
					
					
					$bid_query				= new Bin_Query();
					$bid_sql 				= "SELECT * FROM invoice_bidding_history WHERE ".
											" invoice_id = '".$invoice1['invoice_id']."' ORDER BY history_id DESC LIMIT 1";
					$bid_query->executeQuery($bid_sql);
					$bid_history 			= $bid_query->records;
					
					if($tradefloor['sales_type'] =="1"){
									
						if($_REQUEST['area'] == 'floor'){
							
							if($_SESSION['invFloor'][$tradefloor['invoice_id']] != $bid_history[0]['min_advance']){
								$_SESSION['invFloor'][$tradefloor['invoice_id']] = $bid_history[0]['min_advance'];
								$flag 	= 1;
							}else{
								if($_SESSION['invFloor'][$tradefloor['invoice_id']] == $bid_history[0]['min_advance'] && $_SESSION['invUserID'][$tradefloor['invoice_id']] != $bid_history[0]['user_id']){
									
									$_SESSION['invUserID'][$tradefloor['invoice_id']] = $bid_history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}
						
						}else{
				
							if($_SESSION['invBook'][$tradefloor['invoice_id']] != $bid_history[0]['min_advance']){
								$_SESSION['invBook'][$tradefloor['invoice_id']] = $bid_history[0]['min_advance'];
								$flag 	= 1;
							}else{
								if($_SESSION['invBook'][$tradefloor['invoice_id']] == $bid_history[0]['min_advance'] && $_SESSION['invBookUserID'][$tradefloor['invoice_id']] != $bid_history[0]['user_id']){
									$_SESSION['invBookUserID'][$tradefloor['invoice_id']] = $bid_history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}	
						}
					}else{
						
						if($_REQUEST['area'] == 'floor'){
							
							if($_SESSION['invFloor'][$tradefloor['invoice_id']] != $bid_history[0]['max_thirty_reserve']){
								$_SESSION['invFloor'][$tradefloor['invoice_id']] = $bid_history[0]['max_thirty_reserve'];
								$flag 	= 1;
							}else{
								if($_SESSION['invFloor'][$tradefloor['invoice_id']] == $bid_history[0]['max_thirty_reserve'] && $_SESSION['invUserID'][$tradefloor['invoice_id']] != $bid_history[0]['user_id']){
									$_SESSION['invUserID'][$tradefloor['invoice_id']] = $bid_history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}
						
						}else{
				
							if($_SESSION['invBook'][$tradefloor['invoice_id']] != $bid_history[0]['max_thirty_reserve']){
								$_SESSION['invBook'][$tradefloor['invoice_id']] = $bid_history[0]['max_thirty_reserve'];
								$flag 	= 1;
							}else{
								if($_SESSION['invBook'][$tradefloor['invoice_id']] == $bid_history[0]['max_thirty_reserve'] && $_SESSION['invBookUserID'][$tradefloor['invoice_id']] != $bid_history[0]['user_id']){
									$_SESSION['invBookUserID'][$tradefloor['invoice_id']] = $bid_history[0]['user_id'];
									$flag 	= 1;
									
								}else{
							
									$flag 	= 0;
									
								}
							}	
						}
					}
					
					
					
	
					if(count($bid_history) ==0){
						$style				= "000000"; //black
						$flag				= 0;
					}else{
	
						$bid_query1			= new Bin_Query();
						$bid_sql1 			= "SELECT inv.* FROM invoice_bidding_history as inv, invoice_master as m ".
											" WHERE inv.invoice_id = '".$invoice1['invoice_id']."' ".
											" && m.invoice_id = '".$invoice1['invoice_id']."' ".
											" && m.user_id = '".$_SESSION['user']['userid']."' LIMIT 1";
						$bid_query1->executeQuery($bid_sql1);
						$history1 			= $bid_query1->records;
						
						if(count($history1) ==0){
							$style			= "3F48CC";
						}else{
							
							$bid_query		= new Bin_Query();
							
							if($tradefloor['sales_type'] =="1"){
							
								$bid_sql 	= "SELECT * FROM invoice_bidding WHERE ".
											" invoice_id = '".$invoice1['invoice_id']."' order by min_advance DESC LIMIT 1";
							}else{
								$bid_sql 	= "SELECT * FROM invoice_bidding WHERE ".
											" invoice_id = '".$invoice1['invoice_id']."' ".
											" order by max_thirty_reserve ASC LIMIT 1";
							}
								
							$bid_query->executeQuery($bid_sql);
							$history 		= $bid_query->records[0];
							
							
							if($tradefloor['sales_type'] =="1"){
	
								if($history['min_advance'] >= $tradefloor['min_advance']){
									$style	= "22B14C"; //green
								}else{
									$style	= "ED1C24"; //red
								}
							}else{
							
								if($history['max_thirty_reserve'] <= $tradefloor['max_thirty_day_reserve']){
									$style	= "22B14C"; //green
								}else{
									$style	= "ED1C24"; //red
								}
							}
						}
					}
				}
				
				
				
				
				if($_SESSION['user']['usertype'] == 3 || $_SESSION['user']['usertype'] == 4){
				
					if($tradefloor['sales_type'] !="1"){

						$tradeValues 							= $tradefloor;
						if($tradefloor['invoice_status'] >= 2){
							$tradeValues['yield'] 				= $tradefloor['buy_yield'];
						}else{
							$tradeValues['yield'] 				= $tradefloor['bid_yield'];
						}
						$tradeValues['min_advance'] 			= $invoice1['min_advance'];
						$tradeValues['max_thirty_day_reserve'] 	= $invoice1['max_thirty_reserve'];	
						
						if($tradefloor['sales_type'] =="2"){
							$returnCalc 						= Model_MHelpers::manageDiscountCalc($tradeValues);
						}elseif($tradefloor['sales_type'] =="5"){
							$returnCalc 						= Model_MHelpers::performInstallDiscountCalc($tradeValues);
						}else{
							$returnCalc 						= Model_MHelpers::performDiscountCalc($tradeValues);	
						}
						
						$tPurchase			= $returnCalc['tPurchase'];
						$rebate				= $returnCalc['rebate'];
						$purchaseTotal		= $returnCalc['purchaseTotal'];
						$discount			= number_format($invoice1['max_thirty_reserve'], 3, '.', '')."%";
						
					}else{

						$tradeValues 							= $tradefloor;
						if($tradefloor['invoice_status'] >= 2){
							$tradeValues['yield'] 				= $tradefloor['buy_yield'];
						}else{
							$tradeValues['yield'] 				= $tradefloor['bid_yield'];
						}
						$tradeValues['min_advance'] 			= $invoice1['min_advance'];
						$tradeValues['max_thirty_day_reserve'] 	= $invoice1['max_thirty_reserve'];
						
						$returnCalc 		= Model_MHelpers::outrightDiscountCalc($tradeValues);	
						$tPurchase			= $returnCalc['tPurchase'];
						$discount			= $returnCalc['discount'];
					}
				
				}else{
					
					if($tradefloor['sales_type'] =="1"){
						
						if($tradefloor['debx'] =='1'){
							$return 		= $tradefloor['face_value'] -7 - 50 ;
						}else{
							$return 		= $tradefloor['face_value'] -7;	
						}
						
						$trade_offer		= $tradefloor['currency_code'].
											number_format($invoice1['min_advance'], 2, '.', ',');
						$trade_return		= $tradefloor['currency_code'].number_format($return, 2, '.', ',');
						$trade_yield 		= number_format(($tradefloor['bid_yield']*100),'3','.',',')."%";
						
						
					}elseif($tradefloor['sales_type'] =="2"){
						$tradeValues 							= $tradefloor;
						$tradeValues['min_advance'] 			= $invoice1['min_advance'];
						$tradeValues['max_thirty_day_reserve'] 	= $invoice1['max_thirty_reserve'];
						if($tradefloor['invoice_status'] >= 2){
							$tradeValues['yield'] 				= $tradefloor['buy_yield'];
						}else{
							$tradeValues['yield'] 				= $tradefloor['bid_yield'];
						}
						
						$returnCalc 		= Model_MHelpers::manageYieldValue($tradeValues);
						$yieldValue			= $returnCalc['yieldValue'];
						$tPurchasePrice		= $returnCalc['tPurchasePrice'];
						$valReturn			= $returnCalc['valReturn'];
						$trade_yield 		= number_format(($tradefloor['bid_yield']*100),'3','.',',')."%";
						$trade_offer 		= number_format($invoice1['max_thirty_reserve'],'3','.',',')."%";
						
					}elseif($tradefloor['sales_type'] =="3"){
						$tradeValues 							= $tradefloor;
						$tradeValues['min_advance'] 			= $invoice1['min_advance'];
						$tradeValues['max_thirty_day_reserve'] 	= $invoice1['max_thirty_reserve'];
						if($tradefloor['invoice_status'] >= 2){
							$tradeValues['yield'] 				= $tradefloor['buy_yield'];
						}else{
							$tradeValues['yield'] 				= $tradefloor['bid_yield'];
						}
						
						$returnCalc 		= Model_MHelpers::performYieldValue($tradeValues);
						$non_yield 			= Model_MHelpers::nonPerformanceYield($tradeValues,'simple');
						$yieldValue			= $returnCalc['yieldValue'];
						$tPurchasePrice		= $returnCalc['tPurchasePrice'];
						$valReturn			= $returnCalc['valReturn'];
						$trade_yield 		= number_format(($tradefloor['bid_yield']*100),'3','.',',')."%";
						$trade_offer 		= number_format($invoice1['max_thirty_reserve'],'3','.',',')."%";
					}elseif($tradefloor['sales_type'] =="5"){
						$tradeValues 							= $tradefloor;
						$tradeValues['min_advance'] 			= $invoice1['min_advance'];
						$tradeValues['max_thirty_day_reserve'] 	= $invoice1['max_thirty_reserve'];
						if($tradefloor['invoice_status'] >= 2){
							$tradeValues['yield'] 				= $tradefloor['buy_yield'];
						}else{
							$tradeValues['yield'] 				= $tradefloor['bid_yield'];
						}
						
						$returnCalc 		= Model_MHelpers::performInstallYieldValue($tradeValues);
						$yieldValue			= $returnCalc['yieldValue'];
						$tPurchasePrice		= $returnCalc['tPurchasePrice'];
						$valReturn			= $returnCalc['valReturn'];
						$trade_yield 		= number_format(($tradefloor['bid_yield']*100),'3','.',',')."%";
						$trade_offer 		= number_format($invoice1['max_thirty_reserve'],'3','.',',')."%";
					}
				}
				

				$insurance_flag = Model_MHelpers::getBuyInsurance($tradefloor, $trade_yield);

				$trade_yield = Model_MHelpers::getInsuranceCost($insurance_flag, $trade_yield, $tradefloor);


				
				
				if($invoice1['min_advance'] == "0"){
					$invoice1['min_advance'] = "&nbsp;";
				}else{
					
					if($invoice1['min_advance'] >= 1000000 ){
				
						$invoice1['min_advance'] = $invoice1['min_advance'] / 1000000;
						
						$invoice1['min_advance'] = $tradefloor['currency_code'].
													number_format($invoice1['min_advance'], 1, '.', '')."M";
					}else{
						$invoice1['min_advance'] = $tradefloor['currency_code'].
													number_format(round($invoice1['min_advance']));
					}
				}
				
				if($invoice1['max_thirty_reserve'] == "0"){
					$invoice1['max_thirty_reserve'] = "&nbsp;";
				}else{
					
					$invoice1['max_thirty_reserve'] = number_format(($invoice1['max_thirty_reserve']), 3, '.', '');
				}


								
			
				if($_SESSION['user']['usertype'] == 3 || $_SESSION['user']['usertype'] == 4){
	
					if($tradefloor['invoice_status'] == 2){
						
						if($tradefloor['sales_type'] == 1){
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1', 
											"trade_payment"=>$tPurchase,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');
						}else{
	
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1', 
											"trade_payment"=>$tPurchase,
											"trade_rebate"=>$rebate,
											"trade_total"=>$purchaseTotal,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');//22B14B
						}
							
					}else{
						
					
						if($tradefloor['sales_type'] == 3){
							
							$return 		.= $tradefloor['face_value'] -7;
							$val_return		=  $tradefloor['currency_code'].number_format($return);
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$val_return, 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0', 
											"trade_payment"=>$tPurchase,
											"trade_rebate"=>$rebate,
											"trade_total"=>$purchaseTotal,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');

						}elseif($tradefloor['sales_type'] == 2){
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$invoice1['min_advance'], 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0',
											"trade_payment"=>$tPurchase,
											"trade_rebate"=>$rebate,
											"trade_total"=>$purchaseTotal,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');
						}elseif($tradefloor['sales_type'] == 5){
							

							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$invoice1['min_advance'], 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0',
											"trade_payment"=>$tPurchase,
											"trade_rebate"=>$rebate,
											"trade_total"=>$purchaseTotal,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');
						}else{
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$invoice1['min_advance'], 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'], 
											"closed"=>'0',
											"trade_payment"=>$tPurchase,
											"trade_discount"=>$discount." p.m",
											"user_type" =>'trader');
						}
					}//invoice status closed
					
				}else{
					
					if($tradefloor['invoice_status'] == 2){
							
						if($tradefloor['sales_type'] == 1){
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1',
											"trade_offer"=>$trade_offer." p.m",
											"trade_return"=>$trade_return,
											"trade_yield"=>$trade_yield." p.a",
											"user_type" =>'investor');
							
						}elseif($tradefloor['sales_type'] == 2){
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer." p.m" ,
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"user_type" =>'investor');//22B14B
							
						}elseif($tradefloor['sales_type'] == 5){
							

							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer." p.m" ,
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"user_type" =>'investor');//22B14B
							
						}else{
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>"&nbsp;", 
											"max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',
											"style" =>"22B14B",
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'1',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer." p.m" ,
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"trade_nonyield" =>$non_yield." p.a",
											"user_type" =>'investor');//22B14B
						}
					}else{
						
						if($tradefloor['sales_type'] == 3){
							
							$return 		= $tradefloor['face_value'] -7;
							$val_return 	=  $tradefloor['currency_code'].number_format($return);
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$val_return, 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,"
											invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer ." p.m",
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"trade_nonyield" =>$non_yield." p.a",
											"user_type" =>'investor');
							 
						}elseif($tradefloor['sales_type'] == 2){
							
							$return 		= $tradefloor['face_value'] -7;
							$val_return 	=  $tradefloor['currency_code'].number_format($return);
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$val_return, 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer." p.m" ,
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"user_type" =>'investor');
						}elseif($tradefloor['sales_type'] == 5){


							$return 		= $tradefloor['face_value'] -7;
							$val_return 	=  $tradefloor['currency_code'].number_format($return);
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$val_return, 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,
											"invs"=>$investor_id,
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"closed"=>'0',
											"trade_purchase" =>$tPurchasePrice,
											"trade_offer" =>$trade_offer." p.m" ,
											"trade_return" =>$valReturn,
											"trade_yield" =>$trade_yield." p.a",
											"trade_yieldval" =>$yieldValue,
											"user_type" =>'investor');
						}else{
							
							$myjson[] 		= array("id" => $invoice1['invoice_id'],
											"min" =>$invoice1['min_advance'], 
											"max" =>$invoice1['max_thirty_reserve'],
											"style" =>$style,"invs"=>$investor_id,
											"closed"=>'0',
											"flag"=>$flag,
											"sales"=>$tradefloor['sales_type'],
											"trade_offer"=>$trade_offer." p.m",
											"trade_return"=>$trade_return,
											"trade_yield"=>$trade_yield." p.a",
											"user_type" =>'investor');
							
						}
					}//invoice status closed
				}
			}
			
		}
	
		$myarray = array("records"=>$myjson);
		$myfeed = json_encode($myarray);

		return $myfeed;
		
	}
	
	function getTradeWindowCalc(){
		
		if($_REQUEST['bid'] == '' || $_REQUEST['range'] ==''){
			
			$_SESSION['set'] = $_REQUEST['set']; 
			
			
			$query			= new Bin_Query();
			$sql 			= "SELECT * FROM `search_saved` WHERE user_id = '".$_SESSION['user']['userid']."' limit 1";
			$query->executeQuery($sql);
			$search 		= $query->records;
			
			
			if(count($search) > 0) {
			
				if($_REQUEST['type'] == '1'){
					$update .= "`window` = '".$_REQUEST['set']."'";
				}else if($_REQUEST['type'] == '2'){
					$update .= "`window_m` = '".$_REQUEST['set']."'";
				}else if($_REQUEST['type'] == '3'){
					$update .= "`window_p` = '".$_REQUEST['set']."'";
				}else{
					exit;	
				}

				$query		= new Bin_Query();
				$update_sql = "UPDATE `search_saved` SET ".$update." WHERE `save_id` = '".$search[0]['save_id']."' LIMIT 1 ;";
				$query->updateQuery($update_sql);
			
			
			}else{
				
				if($_REQUEST['type'] == '1'){
					$window = $_REQUEST['set'];
				}else if($_REQUEST['type'] == '2'){
					$window_m = $_REQUEST['set'];
				}else if($_REQUEST['type'] == '3'){
					$window_p = $_REQUEST['set'];
				}else{
					exit;	
				}
				
				$query		= new Bin_Query();
				$insert_sql = "INSERT INTO `search_saved` (`sort1`, `sort2`, `sort3`, `sort4`, `sort5`, `sort6`, `sort7`,".
							   "`sort8`, `sort9`, `window`,`window_m`,`window_p`, `order1`, `order2`, `order3`, `order4`, `order5`, `order6`, `order7`,".
							   "`order8`, `order9`, `user_id`)".
							   "VALUES".
							   "('102', '102', '102', '102', '102', '102', '102', '102', '102', '".$window."','".$window_m."','".$window_p."', '102', '102', '102', '102', '102', '102', '102', '102', '102', '".$_SESSION['user']['userid']."')";
				$query->updateQuery($insert_sql);
				//$closed_sbid = $query->records;
			}
			
			
			exit;
			
		}
		
			$query			= new Bin_Query();
			$temp_sql 		= "SELECT * FROM `invoice_master` where   invoice_id=".$_REQUEST['id']." ".
							" && trading_close_date > NOW() && invoice_status =1 limit 1";
			$query->executeQuery($temp_sql);
			$temp_reg 		= $query->records;
		
			$sales_type 				= $temp_reg[0]['sales_type'];
			$face_value 				= $temp_reg[0]['face_value'];
			$min_advance				= $_REQUEST['bid'] + $_REQUEST['range'];
			$max_thirty_day_reserve 	= $_REQUEST['bid'] - ($_REQUEST['range']/100);
			//$max_thirty_day_reserve 	= $_REQUEST['bid'] + $_REQUEST['range'];
			$ex_date 					= $temp_reg[0]['expected_date'];
			$tr_date 					= $temp_reg[0]['trading_close_date'];
			$buy_min_advance 			=  $temp_reg[0]['buy_min_advance'];
			$buy_max_thirty_day_reserve = $temp_reg[0]['buy_max_thirty_day_reserve'];
			$reg_id 					= $temp_reg[0]['invoice_id'];
			$debx 						= $temp_reg[0]['debx'];	
			$actual_date 				= $temp_reg[0]['actual_date'];

			
			if($temp_reg[0]['sales_type'] =="1"){
				
				$value 										= $min_advance;
				$tradeValues 								= $temp_reg[0];

				$tradeValues['min_advance'] 				= $value;
				$yield 										= Model_MHelpers::outrightYield($tradeValues,'2');
				
				$temp_reg[0]['yield']						= $yield;
				$temp_reg[0]['min_advance']					= $min_advance;
				$temp_reg[0]['max_thirty_day_reserve']		= $max_thirty_day_reserve;
				$returnCalc 								= Model_MHelpers::outrightDiscountCalc($temp_reg[0],'2');
				$tPurchase									= number_format($min_advance,2, '.', ',');
				$discount									= $returnCalc['discount'];	
				$yield 										= number_format(($yield*100), 3, '.', '')."% p.a"; 
				
			}elseif($temp_reg[0]['sales_type'] =="2"){
				
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::managedYieldCalc($tradeValues,'2');
				$purchase_price								= Model_MHelpers::manageYieldValue($tradeValues,'2');

				$temp_reg[0]['yield']						= $yield;
				$temp_reg[0]['min_advance']					= $min_advance;
				$temp_reg[0]['max_thirty_day_reserve']		= $max_thirty_day_reserve;
				$returnCalc 								= Model_MHelpers::manageDiscountCalc($temp_reg[0],'2');
				$rebate										= $returnCalc['rebate'];
				$purchaseTotal								= $returnCalc['purchaseTotal'];
				$yield 										= number_format(($yield*100), 3, '.', '')."% p.a";
				$tPurchase									= number_format($purchase_price, 2, '.', ',');				
				$value 										= number_format($value, 3, '.', ',');	
				
				
				
			}else{
				

				
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::performanceYield($tradeValues,'2');
				$purchase_price 							= $temp_reg[0]['face_value']/(1+(($rebate_refund/360)*(($value/100)*12)));
				
				$temp_reg[0]['yield']						= $yield;
				$temp_reg[0]['min_advance']					= $min_advance;
				$temp_reg[0]['max_thirty_day_reserve']		= $max_thirty_day_reserve;
				$returnCalc 								= Model_MHelpers::performDiscountCalc($temp_reg[0],'2');
				$tPurchase									= $returnCalc['tPurchase'];
				$rebate										= $returnCalc['rebate'];
				$purchaseTotal								= $returnCalc['purchaseTotal'];
				$yield 										= number_format(($yield*100), 3, '.', '')."% p.a";
				$tPurchase									= number_format($purchase_price, 2, '.', ',');	
				$value 										= number_format($value, 3, '.', ',');	
				$non_yield 									= Model_MHelpers::nonPerformanceYield($tradeValues,'simple','2');
	
								
			}
			
			$output = $value.":".$yield.":".$tPurchase.":".$non_yield;
			echo $output;
		
			
	}
	
		//Starts Get all Debtors
	public function getAllDebtor(){

		$query=new Bin_Query();
		$sql = "SELECT debtor_id, debtor_name FROM `debtors_detail` order by debtor_name asc";
		$query->executeQuery($sql);
		$debtor = $query->records;

		return $debtor;
	}//End of Function
	
	function saveSearchTerm(){
		
		
		$query=new Bin_Query();
		$sql = "SELECT * FROM `search_saved` WHERE user_id = '".$_SESSION['user']['userid']."' limit 1";
		$query->executeQuery($sql);
		$search = $query->records;
		
		
		if(count($search) > 0) {
			
			$update ='';
			for($j=1;$j<=9;$j++){

				if($_REQUEST["sort$j"] =='' || $_REQUEST["sort$j"] =='100') $_REQUEST["sort$j"] ='102';


				$update .= "`sort$j` = '".$_REQUEST["sort$j"]."', `order$j` = '".$_REQUEST["ordr$j"]."'";
				if($j < 9){
					$update .= ",";
				}
			}

			$query=new Bin_Query();
			$update_sql = "UPDATE `search_saved` SET ".$update." WHERE `save_id` = '".$search[0]['save_id']."' LIMIT 1 ;";
			
			$query->updateQuery($update_sql);
			
			
		}else{
			
			
			for($j=1;$j<=9;$j++){
				if($_REQUEST["sort$j"] =='' || $_REQUEST["sort$j"] =='100') $_REQUEST["sort$j"] ='102';
			}
			
			$query=new Bin_Query();
			$insert_sql = "INSERT INTO `search_saved` (`sort1`, `sort2`, `sort3`, `sort4`, `sort5`, `sort6`, `sort7`,".
						   "`sort8`, `sort9`, `window`,`window_m`,`window_p`, `order1`, `order2`, `order3`, `order4`, `order5`, `order6`, `order7`,".
						   "`order8`, `order9`, `user_id`)".
						   "VALUES".
						   "('".$_REQUEST['sort1']."', '".$_REQUEST['sort2']."', '".$_REQUEST['sort3']."', '".$_REQUEST['sort4']."', '".$_REQUEST['sort5']."', '".$_REQUEST['sort6']."', '".$_REQUEST['sort7']."', '".$_REQUEST['sort8']."', '".$_REQUEST['sort9']."', 1,1,1, '".$_REQUEST['ordr1']."', '".$_REQUEST['ordr2']."', '".$_REQUEST['ordr3']."', '".$_REQUEST['ordr4']."', '".$_REQUEST['ordr5']."', '".$_REQUEST['ordr6']."', '".$_REQUEST['ordr7']."', '".$_REQUEST['ordr8']."', '".$_REQUEST['ordr9']."', '".$_SESSION['user']['userid']."')";
			$query->updateQuery($insert_sql);
		}	
	}

	function getTraderTradeJson(){

		$query=new Bin_Query();
		$sql = "SELECT * FROM invoice_bidding group by invoice_id";
		$query->executeQuery($sql);
		$invoice= $query->records;


		foreach($invoice as $key){
			
			$querys=new Bin_Query();
			$sqls = "SELECT   
			m.*, d.currency_id , 
			c.currency_code 
			
			FROM 
			`organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
			`invoice_master` as m ,currencies as c
			
			WHERE  
			d.debtor_id = m.debtor_id && m.draft = 0 && r.debtor_id = d.debtor_id && org.organisation_id =  r.organisation_id && 
			
			c.currency_id = d.currency_id  &&
			m.invoice_id = '".$key['invoice_id']."' group by m.invoice_id limit 1";

			
			$querys->executeQuery($sqls);
			$tradefloor = $querys->records[0];
		
				
			
				if($tradefloor['sales_type'] == 1){
								$sql1 = "SELECT * FROM invoice_bidding where invoice_id= ".$key['invoice_id']." 
								order by min_advance DESC limit 1";
				}
				else {
					$sql1 = "SELECT * FROM invoice_bidding where invoice_id= ".$key['invoice_id']." 
								order by max_thirty_reserve ASC limit 1";
				}
	
				$query1=new Bin_Query();
				$query1->executeQuery($sql1);
				$invoice1= $query1->records[0];
				
				


				if($_SESSION['user']['usertype'] == 1 || $_SESSION['user']['usertype'] == 2){

					$bid_query=new Bin_Query();
					$bid_sql = "SELECT * FROM invoice_bidding_history where invoice_id = '".$invoice1['invoice_id']."'";
					$bid_query->executeQuery($bid_sql);
					$history = $bid_query->records;
	
					if(count($history) ==0){
						$style="000000"; //black
					}else{
	
						$bid_query1=new Bin_Query();
						$bid_sql1 = "SELECT * FROM invoice_bidding_history where invoice_id = '".$invoice1['invoice_id']."' && user_id ='".$_SESSION['user']['userid']."'";
						$bid_query1->executeQuery($bid_sql1);
						$history1 = $bid_query1->records;
						
						if(count($history1) ==0){
							$style="3F48CC"; // blue
						}else{
							$bid_query=new Bin_Query();
							
							if($tradefloor['sales_type'] == 1){
								$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice1['invoice_id']."' 
											order by min_advance DESC limit 1";
							}
							else {
								$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice1['invoice_id']."' 
											order by max_thirty_reserve ASC limit 1";
							}
							$bid_query->executeQuery($bid_sql);
							$history2 = $bid_query->records[0];
	
							if($_SESSION['user']['userid'] != $history2['user_id']){
								$style="ED1C24"; //red
							}else{
								$style="22B14C"; //green
							}
						}
					}
	
				}else{
					

					$bid_query=new Bin_Query();
					$bid_sql = "SELECT * FROM invoice_master where invoice_id = '".$invoice1['invoice_id']."' && user_id = '".$_SESSION['user']['userid']."'";
					$bid_query->executeQuery($bid_sql);
					$history = $bid_query->records;
	
					if(count($history) ==0){
						$bid_query1=new Bin_Query();
						$bid_sql1 = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice1['invoice_id']."' ";
						$bid_query1->executeQuery($bid_sql1);
						$history1 = $bid_query1->records;
						
						if(count($history1) > 0){
							$style="3F48CC;"; //blue
						}else{
							$style="000000;"; //black
						}
	
					}else{
	
						
						$bid_query=new Bin_Query();
						
						if($tradefloor['sales_type'] == 1){
						
							$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice1['invoice_id']."' 
										order by min_advance DESC limit 1";
						}else{
							$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice1['invoice_id']."' 
										order by max_thirty_reserve ASC limit 1";
						}
						
						$bid_query->executeQuery($bid_sql);
						$history1 = $bid_query->records[0];
	
						if($history['max_thirty_day_reserve'] > $history1['max_thirty_reserve']){
							$style="ED1C24;"; //red
						}else{
							$style="22B14C;"; //green
						}
	
					}
		
			}
				
				if($invoice1['min_advance'] == "0"){
					$invoice1['min_advance'] = "&nbsp;";
				}else{
					
					if($invoice1['min_advance'] >= 1000000 ){
				
						$invoice1['min_advance'] = $invoice1['min_advance'] / 1000000;
						
						$invoice1['min_advance'] = $tradefloor['currency_code'].number_format($invoice1['min_advance'], 1, '.', '')."M";
					}else{
						$invoice1['min_advance'] = $tradefloor['currency_code'].number_format(round($invoice1['min_advance']));
					}	
				}
				if($invoice1['max_thirty_reserve'] == "0"){
					$invoice1['max_thirty_reserve'] = "&nbsp;";
				}else{
						$invoice1['max_thirty_reserve'] = number_format(($invoice1['max_thirty_reserve']), 3, '.', '');
				}
				
				
			if($tradefloor['invoice_status'] == 2){
					
					if($tradefloor['sales_type'] == 1){
						$myjson[] = array("id" => $invoice1['invoice_id'],"min" =>"&nbsp;", "max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',"style" =>$style);
					}else{
						$myjson[] = array("id" => $invoice1['invoice_id'],"min" =>"&nbsp;", "max" =>'<span style="color: #000;background:#FFE1EA; font-weight:normal; text-align:center;left: -74px; top:0px; position: absolute;width: 124px;"><img src="https://www.credebtexchange.com/images/icon_error.png" /> Bid is Closed</span><span style="text-indent:-999em;width:50px; ">Closed</span>',"style" =>$style);
					}
					
					
			}else{
			
			
				if($tradefloor['sales_type'] == 3){
						$return = $tradefloor['face_value'] -7;
						$val_return =  $tradefloor['currency_code'].number_format($return, 2, '.', ',');
					$myjson[] = array("id" => $invoice1['invoice_id'],"min" =>$val_return, "max" =>$invoice1['max_thirty_reserve'],"style" =>$style,"invs"=>$history1['user_id']);
				}else{
					$myjson[] = array("id" => $invoice1['invoice_id'],"min" =>$invoice1['min_advance'], "max" =>$invoice1['max_thirty_reserve'],"style" =>$style,"invs"=>$history1['user_id']);
				}		
				
			}//invoice status closed
		}

		$myarray = array("records"=>$myjson);

		$myfeed = json_encode($myarray);

		
		return $myfeed;
	}
	

	function getsearchFace($sort_arr, $sort_count,$order,$j){
		$flag =0;
		$sorting='';
		if(in_array("1", $sort_arr) || in_array("28", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '1' || $sort =='28') && $flag=='0'){
						$flag = 1;
						$sorting = "m.face_value $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchOffer($sort_arr, $sort_count,$order,$j){
		$flag =0; $flag1 =0; $flag2 =0; $sorting=''; $where ='';
		if (in_array("2", $sort_arr) || in_array("29", $sort_arr)) {
			
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '8' || $sort =='35') && $flag == '0'){
						$flag = 1;
						$where .="&& m.sales_type ='1'";
						$sorting = "m.min_advance $order ,";
				}
				if(($sort == '9'|| $sort =='36') && $flag1 == '0'){
						$flag1 = 1;
						$where .="&& m.sales_type ='3'";
						$sorting = "m.max_thirty_day_reserve $order ,";
				}
				if(($sort == '10' || $sort =='37') && $flag2 == '0'){
						$flag2 = 1;
						$where .="&& m.sales_type ='2'";
						$sorting = "m.max_thirty_day_reserve $order ,";
				}
			}
		}
		
		return $where."::".$sorting;
	}
	
	function getsearchReturn($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("3", $sort_arr) || in_array("30", $sort_arr)) {
			



			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '3' || $sort =='30') && $flag=='0'){
						$flag = 1;
						$sorting = "m.return $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchYield($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("4", $sort_arr) || in_array("31", $sort_arr)) {

			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '4' || $sort =='31')  && $flag=='0'){
						$flag = 1;
						$sorting = "m.yield $order ,";
				}
			}
		}
		
		return $sorting;
	}

	function getsearchNPYield($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting=''; $where ='';
		if (in_array("5", $sort_arr) || in_array("32", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '5' || $sort =='36')  &&  $flag=='0'){
						$flag = 1;
						$where ="&& m.sales_type ='3'";
						$sorting = " m.yield $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchBid($sort_arr, $sort_count,$order,$j){
		$flag =0; $flag1 =0; $flag2 =0;$sorting='';  $where ='';
		if (in_array("6", $sort_arr) || in_array("33", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '8' || $sort =='35')  && $flag == '0'){
						$flag = 1;
						$where .="&& m.sales_type ='1'";
						$sorting = "m.min_advance $order ,";
				}
				if(($sort == '9' || $sort =='36')  && $flag1 == '0'){
						$flag1 = 1;
						$where .="&& m.sales_type ='3'";
						$sorting = "m.max_thirty_day_reserve $order ,";
				}
				if(($sort == '10' || $sort =='37')  && $flag2 == '0'){
						$flag2 = 1;
						$where .="&& m.sales_type ='2'";
						$sorting = "m.max_thirty_day_reserve $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchOutright($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';  $where ='';
		if (in_array("8", $sort_arr) || in_array("35", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '8' || $sort =='35')  &&  $flag=='0'){
						$flag = 1;
						$where .="&& m.sales_type ='1'";
				}
			}
		}
		return $where;
	}
	
	function getsearchPerform($sort_arr, $sort_count,$order,$j){
		$flag =0; $where='';
		if (in_array("9", $sort_arr) || in_array("36", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '9' || $sort =='36')  &&  $flag=='0'){
						$flag = 1;
						$where .="&& m.sales_type ='3'";
				}
			}
		}
		return $where;
	}
	
	function getsearchManaged($sort_arr, $sort_count,$order,$j){
		$flag =0;$where='';
		

		if (in_array("10", $sort_arr) || in_array("37", $sort_arr)) {

			for($i=1;$i<=$sort_count;$i++){
				
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];

				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '10' || $sort =='37')  &&  $flag=='0'){
						$flag = 1;
						$where .="&& m.sales_type ='2'";
				}
			}
		}
		

		return $where;
	}
	function getsearchRevolving($sort_arr, $sort_count,$order,$j){
		$flag =0;$where='';
		

		if (in_array("68", $sort_arr) || in_array("69", $sort_arr)) {

			for($i=1;$i<=$sort_count;$i++){
				
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];

				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '68' || $sort =='69')  &&  $flag=='0'){
						$flag = 1;
						$where .="&& m.revolving ='1'";
				}
			}
		}
		

		return $where;
	}
	
	function getsearchDebtorName($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("12", $sort_arr) || in_array("39", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '12' || $sort =='39')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "d.debtor_name $order ,";
				}
			}
		}
		
		return $sorting;
	}
	
	function getsearchDebtorNacec($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("13", $sort_arr) || in_array("40", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '13' || $sort =='40')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "d.nace_id $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchDebtorNaced($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("14", $sort_arr) || in_array("41", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '14' || $sort =='41')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "d.nace_group_id  $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchDebtorRisk($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("15", $sort_arr) || in_array("42", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '15' || $sort =='42')  &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE debtor_id = dm.debtor_master_id  LIMIT 1 ) = '2' ) ";
						$sorting = " CAST(dm.debtor_risk AS SIGNED) $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchDebtorCredit($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("16", $sort_arr) || in_array("43", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '16' || $sort =='43')  &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE debtor_id = dm.debtor_master_id  LIMIT 1 ) = '2' ) ";
						$sorting = "  CAST(dm.debtor_limit AS SIGNED) $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	
	function getsearchTradeName($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("18", $sort_arr) || in_array("45", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '18' || $sort =='45')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "m.user_id $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchTradeNacec($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("19", $sort_arr) || in_array("46", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '19' || $sort =='46')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "org.nace_id $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchTradeNaced($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("20", $sort_arr) || in_array("47", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '20' || $sort =='47')  &&  $flag=='0'){
						$flag = 1;
						$sorting = "org.nace_group_id  $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchTradeRisk($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("21", $sort_arr) || in_array("48", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '21' || $sort =='48') &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE organisation_id = org.organisation_id  LIMIT 1 ) = '2' ) ";
						$sorting = " CAST(org.organisation_risk AS SIGNED) $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchTradeCredit($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("22", $sort_arr) || in_array("49", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '22' || $sort =='49') &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE organisation_id = org.organisation_id  LIMIT 1 ) = '2' ) ";
						
						$sorting = " CAST(org.organisation_limit AS SIGNED) $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	
	function getsearchPaymentTerms($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("24", $sort_arr) || in_array("51", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '24' || $sort =='51') &&  $flag=='0'){
						$flag = 1;
						$sorting = "m.payment_terms $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchExpected($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("25", $sort_arr) || in_array("52", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){

					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '25' || $sort =='52') &&  $flag=='0'){
						$flag = 1;
						$sorting = "DATEDIFF(m.expected_date, DATE(NOW())) $order ,";
				}
			}
		}
		return $sorting;
	}

	function getsearchTradeOpen($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("26", $sort_arr) || in_array("53", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];

				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '26' || $sort =='53') &&  $flag=='0'){
						$flag = 1;
						$sorting = " m.created_at $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchTradeClosing($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("27", $sort_arr) || in_array("54", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '27' || $sort =='54') &&  $flag=='0'){
						$flag = 1;
						//$sorting = "TIMEDIFF(m.trading_close_date, NOW()) $order ,";
						$sorting = " m.trading_close_date $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchDebtorSTRating($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting='';  $where ='';
		if (in_array("55", $sort_arr) || in_array("59", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '55' || $sort =='59')  && $flag == '0'){
					

						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE debtor_id = dm.debtor_master_id  LIMIT 1 ) = '1' ) ";
						$sorting = " dm.debtor_risk $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchDebtorLTRating($sort_arr, $sort_count,$order,$j){
		$flag =0; $flag1 =0; $flag2 =0;$sorting='';  $where ='';
		if (in_array("56", $sort_arr) || in_array("60", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '56' || $sort =='60')  && $flag == '0'){

						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE debtor_id = dm.debtor_master_id  LIMIT 1 ) = '1' ) ";
						$sorting = " dm.debtor_limit $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchTraderSTRating($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("57", $sort_arr) || in_array("61", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '57' || $sort =='58') &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE organisation_id = org.organisation_id  LIMIT 1 ) = '1' ) ";
						$sorting = " org.organisation_risk $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchTraderLTRating($sort_arr, $sort_count,$order,$j){
		$flag =0; $sorting=''; $where ='';
		if (in_array("58", $sort_arr) || in_array("62", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '61' || $sort =='62') &&  $flag=='0'){
						$flag = 1;
						$where = " && ( ( SELECT IF((provider1_credit_limit !='' || provider1_risk_score !=''),1,".
								" IF((provider2_credit_limit !='' || provider2_risk_score !=''),1,'2')) ".
							    " FROM risk_credit WHERE organisation_id = org.organisation_id  LIMIT 1 ) = '1' ) ";
						
						$sorting = " org.organisation_limit $order ,";
				}
			}
		}
		return $where."::".$sorting;
	}
	
	function getsearchCloseOnDate($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("63", $sort_arr) || in_array("65", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '63' || $sort =='65') &&  $flag=='0'){
						$flag = 1;
						$sorting = " && m.closing_type  = '2' ";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchCloseOnOffer($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("64", $sort_arr) || in_array("66", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '64' || $sort =='66') &&  $flag=='0'){
						$flag = 1;
						$sorting = " && m.closing_type  = '1' ";
				}
			}
		}
		return $sorting;
	}
	
	function getsearchInvestorID($sort_arr, $sort_count,$order,$j){
		$flag =0;$sorting='';
		if (in_array("67", $sort_arr) || in_array("70", $sort_arr)) {
			for($i=1;$i<=$sort_count;$i++){
				$sort = $_REQUEST["sort$j"];
				$order = $_REQUEST["ordr$j"];
				
				if($order == '1'){
					$order = 'desc';
				}else{
					$order = 'asc';
				}
				if(($sort == '67' || $sort =='70') &&  $flag=='0'){
						$flag = 1;
						$sorting = " investors_id $order ,";
				}
			}
		}
		return $sorting;
	}
	
	function getSort($sort_arr,$sort_count,$order,$j){
		
		$sort =  Model_MTradeFloor::getsearchFace($sort_arr,$sort_count,$order,$j);	
		$sorting = Model_MTradeFloor::getsearchOffer($sort_arr,$sort_count,$order,$j);	
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sort .= Model_MTradeFloor::getsearchReturn($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchYield($sort_arr,$sort_count,$order,$j);	
		
		
		
		$sorting = Model_MTradeFloor::getsearchNPYield($sort_arr,$sort_count,$order,$j);	
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchBid($sort_arr,$sort_count,$order,$j);	
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchDebtorSTRating($sort_arr,$sort_count,$order,$j);
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchDebtorLTRating($sort_arr,$sort_count,$order,$j);
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		
		$sorting = Model_MTradeFloor::getsearchDebtorRisk($sort_arr,$sort_count,$order,$j);	
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchDebtorCredit($sort_arr,$sort_count,$order,$j);	
		
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchTraderSTRating($sort_arr,$sort_count,$order,$j);
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchTraderLTRating($sort_arr,$sort_count,$order,$j);
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchTradeRisk($sort_arr,$sort_count,$order,$j);
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
		
		$sorting = Model_MTradeFloor::getsearchTradeCredit($sort_arr,$sort_count,$order,$j);
		$split = explode("::",$sorting);
		
		$where .= $split[0];
		$sort .= $split[1];
						
				
		
		$where .= Model_MTradeFloor::getsearchOutright($sort_arr,$sort_count,$order,$j);	
		$where .= Model_MTradeFloor::getsearchPerform($sort_arr,$sort_count,$order,$j);	
		$where .= Model_MTradeFloor::getsearchManaged($sort_arr,$sort_count,$order,$j);	
		$where .= Model_MTradeFloor::getsearchRevolving($sort_arr,$sort_count,$order,$j);	
		
		
		$sort .= Model_MTradeFloor::getsearchDebtorName($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchDebtorNacec($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchDebtorNaced($sort_arr,$sort_count,$order,$j);	
		
		$sort .= Model_MTradeFloor::getsearchTradeName($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchTradeNacec($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchTradeNaced($sort_arr,$sort_count,$order,$j);	
		
		$sort .= Model_MTradeFloor::getsearchPaymentTerms($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchExpected($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchTradeOpen($sort_arr,$sort_count,$order,$j);	
		$sort .= Model_MTradeFloor::getsearchTradeClosing($sort_arr,$sort_count,$order,$j);
		
		
		$sort .= Model_MTradeFloor::getsearchTradeClosing($sort_arr,$sort_count,$order,$j);
		$sort .= Model_MTradeFloor::getsearchTradeClosing($sort_arr,$sort_count,$order,$j);
		
		$where .= Model_MTradeFloor::getsearchCloseOnDate($sort_arr,$sort_count,$order,$j);
		$where .= Model_MTradeFloor::getsearchCloseOnOffer($sort_arr,$sort_count,$order,$j);
		
		$sort .= Model_MTradeFloor::getsearchInvestorID($sort_arr,$sort_count,$order,$j);
		
		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));

		
		
		$sorting = array();
		$sorting[0] = $where;
		$sorting[1] = $sort;
		
		
		
		return $sorting;
		
	}

	
	//Starts For Trade Floor Listing
	public function getAllTrade($id='', $myTrade=array() , $activeTrade=array(),$interface='investor'){

		$query=new Bin_Query();
		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}
		
		$sort_count = 3 + $_REQUEST['searchindex'];

		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[] = $_REQUEST["sort$j"];
		}
		
		$count = strlen($sort); //exit;
		for($j=1;$j<=$sort_count;$j++){
			//$sort_arr[0] = $_REQUEST["sort$j"];
			
			$sorting = Model_MTradeFloor::getSort($sort_arr,1,$order,$j);
			
			$where .= $sorting[0];
			$sort .=$sorting[1];
		}
		
		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));
				
				
		$sort = substr(trim($sort),0,$count-1);
		
		if($sort !=''){
			$sort = 'order by '.$sort;	
		}else{
			$sort = " order by m.trading_close_date asc ";
			// $sort = " order by m.invoice_id DESC ";
			
			$_REQUEST['sort1'] = 27;
			$_REQUEST['ordr1'] = 0;
		}

		if(is_numeric($id)) $where .= " && m.invoice_id =$id " ;


		if(count($_REQUEST['inv_all']) > 0 && ($_REQUEST['sort1'] == "0" || $_REQUEST['sort2'] == "0" || $_REQUEST['sort3'] == "0")){
			foreach($_REQUEST['inv_all'] as $key){

				$inv_id[] = " m.invoice_id = '".$key."' ";
			}
			
			$where .= " && (".implode(" || ",$inv_id).") ";
		}
		
		$where = " ".trim($where)." ";
		$interfaceSql = '';
		if($interface == 'trader'){
			
			$interfaceSql = " m.user_id ='".$_SESSION['user']['userid']."' && ";
		}
        
        $noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):CONFIG_ENTRIES_PER_PAGE;
        $start=(isset($_GET['page']))?(trim($_GET['page']-1) * $noofrec):0;
        
		$sql = "SELECT  SQL_CALC_FOUND_ROWS
		
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		
		m.*, 
		d.debtor_id,  dm.debtor_insurance_cost,
		dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		-- DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,
		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%Y-%m-%d') as authorisedday,

		-- DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		DATE_FORMAT(m.expected_date,'%Y-%m-%d') as expectedday,

		-- DATE_FORMAT(m.approved_date,'%d/%m/%Y') as approvedday,
		DATE_FORMAT(m.approved_date,'%Y-%m-%d') as approvedday,

		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id , org.organisation_risk, org.organisation_limit, d.currency_id, 		org.organisation_reference_id, org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case    , 
		( select invorg.organisation_reference_id from invoice_bidding as i , organisation_details as invorg  where i.invoice_id = m.invoice_id && invorg.user_id = i.user_id 
		ORDER BY 
		CASE m.sales_type WHEN '1' THEN i.min_advance END DESC,
		CASE m.sales_type WHEN '2' THEN i.max_thirty_reserve END ASC,
		CASE m.sales_type WHEN '3' THEN i.max_thirty_reserve END ASC  limit 1) as investors_id 	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , debtors_master as dm
		WHERE  $interfaceSql m.invoice_id NOT IN (SELECT DISTINCT (invoice_id) FROM  invoice_bidding) && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country 
		$where group by m.invoice_id $sort
         LIMIT ".$start.",".$noofrec;

		$query->executeQuery($sql);
		$trade = $query->records;
		
		$_SESSION['tf_all_trade'] = $trade;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;

	}//End of Function
	
	function getMyActiveTraderTrade(){
		
		$query=new Bin_Query();
		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}
		
		$sort_count = 3 + $_REQUEST['count'];
		$sort_count = (int)$sort_count;
		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[] = $_REQUEST["sort$j"];
		}
		
		$count = strlen($sort); //exit;
		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[0] = $_REQUEST["sort$j"];
			
			$sorting = Model_MTradeFloor::getSort($sort_arr,1,$order,$j);
			
			$where .= $sorting[0];
			$sort .=$sorting[1];
		}
		
		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));
				
				
		$sort = substr(trim($sort),0,$count-1);
		
		if($sort !=''){
			$sort = 'order by '.$sort;	
		}else{
			$sort = " order by m.trading_close_date asc ";
		}
		
		$noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):CONFIG_ENTRIES_PER_PAGE;
        $start=(isset($_GET['page']))?(trim($_GET['page']-1) * $noofrec):0;
        
		$sql = "SELECT  SQL_CALC_FOUND_ROWS
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id, dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes,
		
		-- DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,

		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%Y-%m-%d') as authorisedday,

		-- DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		DATE_FORMAT(m.expected_date,'%Y-%m-%d') as expectedday,

		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id , org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case  , 
		( select invorg.organisation_reference_id from invoice_bidding as i , organisation_details as invorg  where i.invoice_id = m.invoice_id && invorg.user_id = i.user_id 
		ORDER BY 
		CASE m.sales_type WHEN '1' THEN i.min_advance END DESC,
		CASE m.sales_type WHEN '2' THEN i.max_thirty_reserve END ASC,
		CASE m.sales_type WHEN '3' THEN i.max_thirty_reserve END ASC  limit 1) as investors_id
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , invoice_bidding as inv, debtors_master as dm
		
		WHERE  m.user_id ='".$_SESSION['user']['userid']."' && inv.invoice_id = m.invoice_id && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && 
		org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		
		$where group by m.invoice_id $sort
         LIMIT ".$start.",".$noofrec;
		
		$query=new Bin_Query();
		$query->executeQuery($sql);
		$trade = $query->records;
        
		$_SESSION['tf_my_trade'] = $trade;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;
	}
	
	function getActiveTraderTrade($trade=array()){
		
		
		$query=new Bin_Query();
		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}
		
		$sort_count = 3 + $_REQUEST['searchindex'];

		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[] = $_REQUEST["sort$j"];
		}
		
		$count = strlen($sort); //exit;
		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[0] = $_REQUEST["sort$j"];
			
			$sorting = Model_MTradeFloor::getSort($sort_arr,1,$order,$j);
			
			//print_r($sorting);
			$where .= $sorting[0];
			$sort .=$sorting[1];
		}
		
		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));
				
				
		$sort = substr(trim($sort),0,$count-1);
		
		if($sort !=''){
			$sort = 'order by '.$sort;	
		}else{
			$sort = " order by m.trading_close_date asc ";
		}

		if(count($trade) > 0){
			foreach($trade as $key){

				$invid[] 		= "m.invoice_id != '".$key['invoice_id']."' ";
			}
			$where 				.= " && (".implode(" && ",$invid).") ";
		}
		
        $noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):CONFIG_ENTRIES_PER_PAGE;
        $start=(isset($_GET['page']))?(trim($_GET['page']-1) * $noofrec):0;
		
		$sql = "SELECT  SQL_CALC_FOUND_ROWS
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id, dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		-- DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,

		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%Y-%m-%d') as authorisedday,

		-- DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		DATE_FORMAT(m.expected_date,'%Y-%m-%d') as expectedday,

		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) ,  
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id , org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case   , 
		( select invorg.organisation_reference_id from invoice_bidding as i , organisation_details as invorg  where i.invoice_id = m.invoice_id && invorg.user_id = i.user_id 
		ORDER BY 
		CASE m.sales_type WHEN '1' THEN i.min_advance END DESC,
		CASE m.sales_type WHEN '2' THEN i.max_thirty_reserve END ASC,
		CASE m.sales_type WHEN '3' THEN i.max_thirty_reserve END ASC  limit 1) as investors_id
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , invoice_bidding as inv, debtors_master as dm
		
		WHERE  m.user_id != '".$_SESSION['user']['userid']."' && inv.invoice_id = m.invoice_id && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		
		$where group by m.invoice_id $sort
         LIMIT ".$start.",".$noofrec;
		
		$query=new Bin_Query();
		$query->executeQuery($sql);
		$trade = $query->records;
		
		$_SESSION['tf_active_trade'] = $trade;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;

			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;
	}

	function getMyActiveInvestorTrade(){
		
		$query=new Bin_Query();
		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}
		
		$sort_count = 3 + $_REQUEST['searchindex'];

		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[] = $_REQUEST["sort$j"];
		}
		
		$count = strlen($sort); //exit;
		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[0] = $_REQUEST["sort$j"];
			
			$sorting = Model_MTradeFloor::getSort($sort_arr,1,$order,$j);
			
			//print_r($sorting);
			$where .= $sorting[0];
			$sort .=$sorting[1];
		}

		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));
		
		$sort = substr(trim($sort),0,$count-1);
		
		if($sort !=''){
			$sort = 'order by '.$sort;	
		}else{
			$sort = " order by m.trading_close_date asc ";
		}
		
        $noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):CONFIG_ENTRIES_PER_PAGE;
        $start=(isset($_GET['page']))?(trim($_GET['page']-1) * $noofrec):0;
		
		$sql = "SELECT  SQL_CALC_FOUND_ROWS
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id, dm.debtor_insurance_cost,
		dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		-- DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,
		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%Y-%m-%d') as authorisedday,

		-- DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		DATE_FORMAT(m.expected_date,'%Y-%m-%d') as expectedday,

		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id , org.organisation_reference_id,org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , invoice_bidding as inv , debtors_master as dm
		
		WHERE  inv.user_id ='".$_SESSION['user']['userid']."' && m.invoice_id = inv.invoice_id && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		
		$where group by m.invoice_id $sort
         LIMIT ".$start.",".$noofrec;
		
		$query=new Bin_Query();
		$query->executeQuery($sql);
		$trade = $query->records;
		
		$_SESSION['tf_my_trade'] = $trade;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;	
	}
	
	
	
	function getActiveInvestorTrade($myTrade=array()){
		
		
		
		$query=new Bin_Query();
		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}
		
		$sort_count = 3 + $_REQUEST['searchindex'];

		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[] = $_REQUEST["sort$j"];
		}
		
		$count = strlen($sort); //exit;
		for($j=1;$j<=$sort_count;$j++){
			$sort_arr[0] = $_REQUEST["sort$j"];
			
			$sorting = Model_MTradeFloor::getSort($sort_arr,1,$order,$j);
			
			$where .= $sorting[0];
			$sort .=$sorting[1];
		}
		
		$where = implode('&&',array_unique(explode('&&', $where)));
		
		$sort = implode(',',array_unique(explode(',', $sort)));
				
				
		$sort = substr(trim($sort),0,$count-1);
		
		if($sort !=''){
			$sort = 'order by '.$sort;	
		}else{
			$sort = " order by m.trading_close_date asc ";
		}
		
		if(count($myTrade) > 0){
			
			foreach($myTrade as $key){

				$invid[] = " m.invoice_id != '".$key['invoice_id']."' ";
			}
			
			if(count($invid) > 0){
				$where .= " && (".implode(" && ",$invid).") ";
			}
		}
		
		$noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):CONFIG_ENTRIES_PER_PAGE;
        $start=(isset($_GET['page']))?(trim($_GET['page']-1) * $noofrec):0;
		
		 
		$sql = "SELECT  SQL_CALC_FOUND_ROWS
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id,  dm.debtor_insurance_cost,
		dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id , org.organisation_reference_id, org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , invoice_bidding as inv, debtors_master as dm
		
		WHERE  inv.user_id !='".$_SESSION['user']['userid']."' && m.invoice_id = inv.invoice_id &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		
		$where group by m.invoice_id $sort
         LIMIT ".$start.",".$noofrec;
		
		$query=new Bin_Query();
		$query->executeQuery($sql);
		$trade = $query->records;
		
		$_SESSION['tf_active_trade'] = $trade;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		return $trade;
	}
	
	//Starts For Trade Floor Listing
	public function getBuyOutInvestorTrade($id=''){

		$query=new Bin_Query();

		$sort = " order by TIMEDIFF(m.trading_close_date, NOW()) asc ";

		if(is_numeric($id)) $where .= " && m.invoice_id =$id " ;


		if(count($_REQUEST['inv_all']) > 0){
			foreach($_REQUEST['inv_all'] as $key){

				$inv_id[] = "m.invoice_id ='".$key."' ";
			}
			
			$where .= " && (".implode(" || ",$inv_id).") ";
			
		}
		


		$sql = "SELECT  
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id, dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id ,  org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c	, debtors_master as dm
		WHERE   m.invoice_id = m.invoice_id && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		$where group by m.invoice_id $sort";
		//&& m.trading_close_date >= NOW() 
	
		$query->executeQuery($sql);
		$trade = $query->records;
		
	
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;

	}//End of Function
	//Starts For Trade Floor Listing
	public function getBuyAllTrade($id=''){

		$query=new Bin_Query();


		if($_REQUEST['order'] =='2') {
			$order = 'desc';
		}
		else {
			$order = 'asc';
			$_REQUEST['order'] ='1';
		}

		$sort = ''; $where ='';
		if($_REQUEST['sort1'] =="" && $_REQUEST['sort2'] =="" && $_REQUEST['sort3'] =="") {
			$sort = " order by TIMEDIFF(m.trading_close_date, NOW()) asc ";
		}
		else {
			
			$flag =1;
			
			for($inc=1;$inc <=3;$inc++){
				
				if($_REQUEST["sort$inc"] !='0'&& $_REQUEST["sort$inc"] !='' && $_REQUEST["sort$inc"] !='1' && $_REQUEST["sort$inc"] !='2' && $inc >= "2"){
					
						if($flag==0) { $sort .=' order by '; $flag =1; }
						else { $sort .=" , "; }
				}
				
				if($_REQUEST["sort$inc"] !='0'&& $_REQUEST["sort$inc"] !='' && $_REQUEST["sort$inc"] !='1' && $_REQUEST["sort$inc"] !='2' && $inc == "1"){
					$sort .=' order by ';
					$flag =1;
				}else if($inc == "1"){
						$flag=0;
				}
				
				if($_REQUEST["ordr$inc"] =='1') {
					$order = 'desc';
				}
				else {
					$order = 'asc';
					//$_REQUEST['ordr'] ='1';
				}
			
				switch ($_REQUEST["sort$inc"]) {
					case 3:
						$sort .= "m.yield $order";
						break;
					case 4:
						$sort .= "m.return $order";
						break;
					case 5:
						$where .="&& m.buy_out ='1' ";
						$sort .= "m.buy_yield $order";
						break;
					case 6:
						$where .="&& m.buy_out ='1' ";
						$sort .= "m.buy_return $order";
						break;
					case 7:
						$where .="&& m.bid_yield <> 0  ";
						$sort .= "m.bid_yield $order";
						break;
					case 8:
						$where .="&& m.bid_return <> 0 ";
						$sort .= "m.bid_return $order";
						break;
	
					/*case 2:
						$sort .= "d.debtor_name $order";
						break;*/
					case 10:
						$where .="&& m.sales_type ='1' ";
						$sort .= "m.min_advance $order";
						break;
					case 11:
						$where .="&& m.sales_type ='2' ";
						$sort .= "m.max_thirty_day_reserve $order";
						break;
					case 12:
						$where .="&& m.sales_type ='3' ";
						$sort .= "m.max_thirty_day_reserve $order";
						break;
					case 13:
						$where .="&& m.sales_type ='1' ";
						$sort .= "bid_min_case $order";
						break;
					case 14:
						$where .="&& m.sales_type ='2' ";
						$sort .= "bid_max_case $order";
						break;
					case 15:
						$where .="&& m.sales_type ='3' ";
						$sort .= "bid_max_case $order";
						break;
						
						
						
						
					case 17:
						$sort .= "d.debtor_name $order";
						break;
					case 18:
						$sort .= "d.nace_id $order";
						break;
					case 19:
						$sort .= "d.nace_group_id  $order";
						break;
					case 20:
						$sort .= "d.debtor_risk $order";
						break;
					case 21:
						$sort .= "d.debtor_limit $order";
						break;
			
						
					case 23:
						$sort .= "m.user_id $order";
						break;
					case 24:
						$sort .= "org.nace_id $order";
						break;
					case 25:
						$sort .= "org.nace_group_id  $order";
						break;
					case 26:
						$sort .= "risks $order";
						break;
					case 27:
						$sort .= "limits $order";
						break;		
						
			
					case 29:
						$sort .= "m.payment_terms $order";
						break;
					case 30:
						$sort .= "DATEDIFF(m.expected_date, DATE(NOW())) $order";
						break;
					case 31:
						$sort .= "DATEDIFF(m.modified_at, NOW()) $order";
						break;
					case 32:
						$sort .= "TIMEDIFF(m.trading_close_date, NOW()) $order";
						break;
				}
			}
		}

		if(is_numeric($id)) $where .= " && m.invoice_id =$id " ;

		

		if(count($_REQUEST['inv_all']) > 0 && ($_REQUEST['sort1'] == "1" || $_REQUEST['sort2'] == "1" || $_REQUEST['sort3'] == "1")){
			foreach($_REQUEST['inv_all'] as $key){

				$inv_id[] = "m.invoice_id ='".$key."' ";
			}
			
			$where .= " && (".implode(" || ",$inv_id).") ";
			
		}

		
		$sql = "SELECT  
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id,  dm.debtor_insurance_cost,
		dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,
		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		
		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,
		DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		org.organisation_name , org.organisation_id ,  d.currency_id ,  org.active_debtors,
		c.country_name , (select min_advance from invoice_bidding where invoice_id = m.invoice_id order by min_advance desc limit 1) as bid_min_case , (select max_thirty_reserve from invoice_bidding where invoice_id = m.invoice_id order by max_thirty_reserve asc limit 1) as bid_max_case
	 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c, invoice_bidding as inv , debtors_master as dm
		
		WHERE  m.user_id ='".$_SESSION['user']['userid']."' &&  inv.invoice_id = m.invoice_id && m.draft = 0 &&
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id && 
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		$where group by m.invoice_id $sort";
	
		$query->executeQuery($sql);
		$trade = $query->records;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[0]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}
		
		return $trade;

	}//End of Function


	//Starts For Trade Floor Listing
	public function getTrade($id){

		$query=new Bin_Query();

		
		if(is_numeric($id)) $where = " && m.invoice_id =$id " ;
		
		$sql = "SELECT   
		org.organisation_limit AS  limits, org.organisation_risk AS risks,
		m.*, 
		d.debtor_id,  dm.debtor_insurance_cost,
		dm.debtor_master_id, dm.debtor_name,dm.debtor_risk,dm.debtor_limit,dm.nace_id as d_nace_id,dm.nace_group_id as d_nace_group_id,
		t.doj, 
		org.nace_id as t_nace_id,org.nace_group_id as t_nace_group_id, 

		
		DATEDIFF( NOW( ),m.created_at ) AS c_days, 
		HOUR(TIMEDIFF( TIME(NOW( )),TIME( m.created_at ) )) AS c_hours, 
		MINUTE(TIMEDIFF( TIME( NOW( ) ),TIME( m.created_at ) )) AS c_minutes, 
		
		DATE_FORMAT(DATE_ADD(DATE(m.trading_close_date),INTERVAL 3 DAY),'%d/%m/%Y') as authorisedday,
		DATE_FORMAT(m.expected_date,'%d/%m/%Y') as expectedday,
		
		
		TIMEDIFF(m.trading_close_date, NOW()) as expire_date ,

		DATEDIFF( m.trading_close_date, NOW( ) ) AS days, 
		DATEDIFF( DATE_ADD(DATE(m.expected_date),INTERVAL m.payment_terms DAY), DATE(m.expected_date) ) AS exp_days, 
		HOUR(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS hours, 
		MINUTE(TIMEDIFF( TIME( m.trading_close_date ) , 
		TIME( NOW( ) ) )) AS minutes,  
		d.currency_id , org.organisation_id ,org.organisation_reference_id, org.active_debtors,
		c.country_name 
		
		FROM 
		`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, `debtors_detail` as d , 
		`invoice_master` as m , address_details as a , country_mas as c , debtors_master as dm
		
		WHERE  
		d.debtor_id = m.debtor_id && r.debtor_id = d.debtor_id && dm.debtor_master_id = d.parent_id && org.organisation_id =  r.organisation_id && m.draft = 0 &&
		t.user_id = m.user_id && m.invoice_status = 1 && 
		a.address_id = t.organization_address_id && c.country_id = a.address_country   
		$where group by m.invoice_id limit 1";
		//&& m.trading_close_date >= NOW() 
	
		$query->executeQuery($sql);
		$trade = $query->records;
		
		for($i=0;$i<count($trade);$i++)
		{
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['d_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['d_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['d_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['d_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$trade[$i]['t_nace_group_id']."' limit 1";
			$query1->executeQuery($sql1);
			$nace_group_id = $query1->records;
			
			$query2=new Bin_Query();
			$sql2 = "SELECT nace_id, nace_code FROM `categories` where nace_id = '".$trade[$i]['t_nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$trade[$i]['t_nace_id'] = $nace_id[0]['nace_code'];
			
			$trade[$i]['t_nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			
			$query3 =new Bin_Query();
			$sql3 = "SELECT type_name FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query3->executeQuery($sql3);
			$type = $query3->records;
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['type_name'] = 'Revolving ETR';
			}else{
				$trade[$i]['type_name'] = $type[0]['type_name'];
			}
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `currencies` where currency_id = '".$trade[$i]['currency_id']."' LIMIT 1 ";
			$query4->executeQuery($sql4);
			$currency = $query4->records;
			
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
			
			$query4=new Bin_Query();
			$sql4 = "SELECT * FROM `sales_types` where type_id = '".$trade[$i]['sales_type']."' limit 1";
			$query4->executeQuery($sql4);
			$sales_types = $query4->records;
			
			
			if($trade[$i]['revolving'] == '1'){
				$trade[$i]['sales'] = 'Revolving ETR';
			}else{
				$trade[$i]['sales'] = $sales_types[0]['type_name'];
			}
			
			
		}
		
		
		return $trade;
	}//End of Function
	
	function getPaging($paging,$prev,$next,$cur_page,$total){
		
		$output				.= '<B>Page '.$cur_page.'</B> of <B>'.$total.'</B> &nbsp;&nbsp;<strong>'.$prev.' '.$next.' &nbsp;';
		for($i=1;$i<=count($paging);$i++){
			$pagingvalues 	.= $paging[$i]." ";
		}
		$output 			.= $pagingvalues.' </strong>';
		
		return $output;
	}



	//Check Invoice Status Starts Here
	public function checkTradeStatus($id){

		$query=new Bin_Query();
		$sql = "SELECT m.invoice_id from `invoice_master` as m where m.invoice_id = '$id' && m.invoice_status = 1  limit 1";
		//&& m.trading_close_date >= NOW() 
		$query->executeQuery($sql);
		$invoice = $query->records;

		if(count($invoice) ==0){
			return 0;
		}else{
			return 1;
		}

	}//End of Function



	//Starts For Trade Floor Listing
	public function getTradeDocs($id){

		$query=new Bin_Query();

		//if(is_numeric($id)) $where = " && m.invoice_id =$id " ;
		
		$sql = "SELECT doc.* FROM `invoice_master` as m , `invoice_documents` as doc where doc.invoice_id = m.invoice_id";

		$query->executeQuery($sql);
		$docs = $query->records;
		return $docs[0];
	}//End of Function

	//Starts For Trade Floor Listing
	public function getDocs($id){

		$query=new Bin_Query();

		//if(is_numeric($id)) $where = " && m.invoice_id =$id " ;
		
		$sql = "SELECT doc.* FROM `invoice_master` as m , `invoice_documents` as doc where doc.invoice_id = '".$id."'";

		$query->executeQuery($sql);
		$docs = $query->records;
		return $docs[0];
	}//End of Function



	//Starts Checks Bid for Best Bid.
	public function CheckBid($id)
    {
        parent::checkTradeFloor(2);

		$query=new Bin_Query();
		$sql = "SELECT * FROM `invoice_bidding` where `invoice_id` = ".$id." order by min_advance desc limit 1";
		$query->executeQuery($sql);
		$invoice = $query->records;

		return $invoice;	
	
	}//End of Function
	
	function holidayCalc($id,$flg=1){
		
		if($_REQUEST['read'] == 'floor'){
			return 1;	
		}
		
		$query		= new Bin_Query();
		$sql 		= "SELECT s.* FROM `invoice_master` as m ".
					" LEFT JOIN `debtor_relation` as r ON r.debtor_id =  m.debtor_id ".
					" LEFT JOIN `organisation_details` as org ON org.organisation_id =  r.organisation_id ".
					" LEFT JOIN `address_details` as a ON a.address_id =  org.organisation_regoffice_id ".
					" RIGHT JOIN `site_settings` as s ON IF(a.address_country = 104,".
					" find_in_set( DATE( NOW()), ie_date_closed ) > 0, ".
					" IF(a.address_country = 222,find_in_set( DATE(NOW()) , uk_date_closed ) >0, uk_date_closed='nil')) ".
					" WHERE m.invoice_id = '$id' limit 1";
					

		$query->executeQuery($sql);
		$days 	= $query->records;
		

		$query	= new Bin_Query();
		$sql 	= "SELECT site_setting_id , inv_floor_status, DATE(NOW()) as today ". 
				" FROM `site_settings` WHERE   ".
				" TIME(NOW()) BETWEEN auction_start AND auction_end  limit 1";
		
		$query->executeQuery($sql);
		$time 	= $query->records;
		
		$dt = strtotime($time[0]['today']);
		$day1 = date("N", $dt);
		
		$query	= new Bin_Query();
		$sql 	= "SELECT inv_floor_status FROM `site_settings`  WHERE  site_setting_id =1 limit 1";
		$query->executeQuery($sql);
		$times 	= $query->records[0];
		
		

		if((count($days) == 0 && count($time) == 1 ) && $times['inv_floor_status'] !='1'){
			return 0;	
		}else{
			return 1;	
		}
		
	}
	

	
	function holidayRecurse($date, $ie_date_closed, $today, $start, $end){
		$dt = strtotime($date);
		$day1 = date("N", $dt);


		if(in_array($date,$ie_date_closed)){

			$query		= new Bin_Query();
			$sql 		= "SELECT DATE( DATE_ADD( '$date' , INTERVAL 1 DAY ) ) AS date2 ";
			$query->executeQuery($sql);
			$time 		= $query->records[0];
			return Model_MTradeFloor::holidayRecurse($time['date2'],$ie_date_closed, $today, $start, $end);
	  
		}elseif($day1 < $start || $day1 > $end){
		
			$query		= new Bin_Query();
			$sql 		= "SELECT DATE( DATE_ADD( '$date' , INTERVAL 1 DAY ) ) AS date2 ";
			$query->executeQuery($sql);
			$time 		= $query->records[0];
			return Model_MTradeFloor::holidayRecurse($time['date2'],$ie_date_closed, $today, $start, $end);
			
		}else{

			if($day1 == '1'){
				
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{
					$tmrw = 'Monday';	
				}
			}elseif($day1 == '2'){
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Tuesday';	
				}
				
			}elseif($day1 == '3'){
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Wednesday';
				}

				
			}elseif($day1 == '4'){
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Thursday';
				}
			}
			elseif($day1 == '5'){
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Friday';
				}
				
			}elseif($day1 == '6'){
				
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Saturday';
				}
				
			}elseif($day1 == '7'){
				
				if($day1 == $today){
					$tmrw = 'Today';
				}elseif($day1 == $today+1){
					$tmrw = 'Tomorrow';
				}else{$tmrw = 'Sunday';
				}
			}
			
			return $tmrw;
		}
	}
	
	
	public function stopAgain($id, $log){
		
		$user_id = $_SESSION['user']['userid'];
		
		$query=new Bin_Query();
		$sql 		= "SELECT  m.sales_type, m.min_advance ,m.debtor_id, m.max_thirty_day_reserve, m.face_value , t.currency_id				FROM 
					`temp_registration` as t, `organisation_details` as org, `debtor_relation` as r, 
					`invoice_master` as m					
					WHERE  m.invoice_id = '".$id."' && 	r.debtor_id = m.debtor_id && org.organisation_id =  r.organisation_id 
					group by m.invoice_id LIMIT 1";

		$query->executeQuery($sql);
		$inv = $query->records;

		$query4=new Bin_Query();
		$sql4 = "SELECT * FROM `currencies` where currency_id = '".$inv[0]['currency_id']."' LIMIT 1 ";
		$query4->executeQuery($sql4);
		$currency = $query4->records;
		
		$inv[0]['currency_code'] = $currency[0]['currency_code'];		
	
	
		if(count($inv) >0){
		if($inv[0]['sales_type'] == "1"){
				$orderby ="order by min_advance DESC ";
		}else{
				$orderby ="order by max_thirty_reserve ASC ";
				//$_POST['min_bid'] = $_POST['min_bid'] / 100;
		}
			
		$query1=new Bin_Query();
		$sql1 = "SELECT invoice_id, min_advance , user_id, max_thirty_reserve FROM `invoice_bidding` where `invoice_id` = '".$id."' $orderby limit 1"; 
		$query1->executeQuery($sql1);
		$invoice = $query1->records;
						
			$total = $_POST['min_bid'];// * $_POST['range'];
				
			if($log == "1"){
			
				if($total > $inv[0]['face_value'] && $inv[0]['sales_type'] == 1){
					$_SESSION['messages'] = " In accordance with <a target=\"_blank\" style=\"font-size:9px;\" href=\"".self::tokenUrl('/exchange-help/policy/bidding')."\">Exchange Policy</a> ".
													" , bidding on this Debtor must not be above Face Value";
					header('Location: index.php?do=tradewindow&trade_id='.$id);
					exit;
				}
			}else{
	
				if($_SESSION['user']['userid'] == $invoice[0]['user_id']){
					$_SESSION['messages'] = 'No Trade Needed | My Bid is Best';
					header('Location: index.php?do=tradewindow&trade_id='.$id);
					exit;
				}else if($total > $inv[0]['face_value'] && $inv[0]['sales_type'] == 1){
					$_SESSION['messages'] = " In accordance with <a target=\"_blank\" style=\"font-size:9px;\" href=\"".self::tokenUrl('/exchange-help/policy/bidding')."\">Exchange Policy</a> "." , bidding on this Debtor must not be above Face Value";
					header('Location: index.php?do=tradewindow&trade_id='.$id);
					exit;
				}
			}
			
			$total 		= $_POST['min_bid'];
			$sql 		= " SELECT dm.*  FROM `debtors_detail` as d, `debtors_master` as dm, `debtor_relation` as r ".
						" WHERE r.debtor_id = '".$inv[0]['debtor_id']."' && r.status ='1' ".
						" && d.debtor_id = r.debtor_id && d.parent_id != 0 ".
						" && dm.debtor_master_id = d.parent_id  limit 1 ";
			$query->executeQuery($sql);
			$debtor 	= $query->records;
			
			

			if(count($debtor) > 0){
					

				if($debtor[0]['debtor_max_bid'] =='0'){
					
					$debtor[0]['debtor_max_bid'] = "0.999";	
				}
				
				if($debtor[0]['debtor_min_offers'] =='0'){
					
					$debtor[0]['debtor_min_offers'] = "0.001";	
				}

				if($inv[0]['sales_type']=="1")
				{
		
					if($total !=''  && $inv[0]['face_value'] != ''){
						
						$max = round($inv[0]['face_value'] - (($debtor[0]['debtor_max_bid'] / 100 ) * $inv[0]['face_value'])); //6064
						$min = $inv[0]['face_value'] - (($debtor[0]['debtor_min_offers'] / 100 ) * $inv[0]['face_value']); //6072
						
						if($total > $max && $max != 0){
							
													
							$_SESSION['messages'] = " In accordance with <a target=\"_blank\" style=\"font-size:9px;\" href=\"".self::tokenUrl('/exchange-help/policy/bidding')."\">Exchange Policy</a> ".
													" , bidding on this Debtor must be at,".
													" or below, ".$inv[0]['currency_code'].number_format($max);	
												 	
							header('Location: index.php?do=tradewindow&trade_id='.$id);
							exit;					
						}
					}
				}else{
					

					
					if($total !='' && ($total > $debtor[0]['debtor_max_bid']) ){
						
						$max = $debtor[0]['debtor_max_bid']; 
						$min = $debtor[0]['debtor_min_offers']; 
						
							$_SESSION['messages'] = " In accordance with <a target=\"_blank\" style=\"font-size:9px;\" href=\"".self::tokenUrl('/exchange-help/policy/bidding')."\">Exchange Policy</a> ".
													" , bidding on this Debtor must be at,".
													" or below, ".number_format($max, 3, '.', '')."%";
													
							header('Location: index.php?do=tradewindow&trade_id='.$id);

							exit;
					}
				}
				
			}else{
				
				
				echo '<script>window.close();</script>';
				exit;
			}

		}else{
			
			echo '<script>window.close();</script>';
			exit;
		}	
	}


	//Starts Latest Invoice Bid By the Trader w.r.t Invoice
	public function getLatestTradeBid($id){

		$user_id = $_SESSION['user']['userid'];

		$query=new Bin_Query();
		$sql = "SELECT * FROM `invoice_bidding_history` where `invoice_id` = ".$id." &&  user_id = ".$user_id."  order by bid_time desc";
		$query->executeQuery($sql);
		$invoice = $query->records;

		return $invoice;		
	}//End of Function



	//Bid Accept / Reject By Trader
	public function changeBidStatus($id){

		$user_id = $_SESSION['user']['userid'];

		$query=new Bin_Query();
		$sql = "SELECT  inv.* FROM `invoice_bidding_history` as b ,`invoice_master` as m, `invoice_bidding` as inv where  b.history_id = $id && m.invoice_id = b.invoice_id && inv.invoice_bidding_id = b.invoice_bidding_id && m.user_id = ".$user_id."";
		$query->executeQuery($sql); 
		$bid = $query->records;

		$state = $_REQUEST['state'];	


		//Auction Accept Flow
		if($state ==1 && count($bid) > 0){

			$query=new Bin_Query();
			$closed_sql = "INSERT INTO `invoice_closed` (`invoice_id` ,`won_by` ,`min_advance` ,`max_thirty_reserve` ,`invoice_bidding_id` ,`payment_status` ,`close_time`)VALUES 
			('".$bid[0]['invoice_id']."', '".$bid[0]['user_id']."', '".$bid[0]['min_advance']."', '".$bid[0]['max_thirty_reserve']."', '".$bid[0]['invoice_bidding_id']."', '0', NOW())";


			$query->executeQuery($closed_sql);
			$closed_id 		= $query->insertid;
			$closed_sbid 	= $query->records;
			
			

			$clquery		= new Bin_Query();
			$closed_sql 	= " UPDATE 
							invoice_closed c 
							INNER JOIN (
								SELECT CONCAT(DATE_FORMAT(NOW(),'%Y-%m-%d-'),REPLACE(CONCAT('ss',(1000000 + COUNT( `close_id` ) )),'ss1','0')) as n FROM `invoice_closed` WHERE DATE(`close_time` ) = CURDATE()
							) r 
							SET 
								c.closed_ref_id = r.n
							WHERE
								c.close_id = '".$closed_id."' ";
			$clquery->executeQuery($closed_sql);
			
			
			$query=new Bin_Query();
			$invoice_sql = "UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$bid[0]['invoice_id']." LIMIT 1 ;";
			$query->executeQuery($invoice_sql);
			$invoice = $query->records;
			$output['invoice_id'] = $bid[0]['invoice_id'];
			$output['result'] ="Bid Accepted SuccessFully";
			
			
			
			return $output;

		}// Auction Accept Flow Ends here 
		else if($state ==0 && count(bid) > 0)
		{// Auction Reject Flow Starts here

			$query=new Bin_Query();
			$closed_sql = "UPDATE `invoice_bidding` SET `buy_out` = '1' , flag =1 WHERE `invoice_bidding_id` =".$bid[0]['invoice_bidding_id']." LIMIT 1 ;";
			$query->executeQuery($closed_sql);
			$closed_sbid = $query->records;

			$query=new Bin_Query();
			$invoice_sql = "UPDATE `invoice_master` SET `invoice_status` = '1' WHERE `invoice_id` =".$bid[0]['invoice_id']." LIMIT 1 ;";
			$query->executeQuery($invoice_sql);
			$invoice = $query->records;

			$output['invoice_id'] = $bid[0]['invoice_id'];
			$output['result'] ="Bid Rejected SuccessFully";
			
			
			return $output;
		}// Auction Reject Flow Ends here 

		return 0;
	
	}//End of Function
	
	
	
	public function acceptBid($id){


		$user_id = $_SESSION['user']['userid'];

		$query=new Bin_Query();
		$sql = "SELECT  sales_type, invoice_id FROM `invoice_master` where  invoice_id = '".$id."' && invoice_status = 1 && user_id = ".$user_id." limit 1";
		$query->executeQuery($sql);
		$invoice = $query->records;

		$state = $_REQUEST['state'];	


		//Auction Accept Flow
		if(count($invoice) > 0){
			
			
			if($invoice[0]['sales_type'] == "1"){
			
				$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice[0]['invoice_id']."' order by min_advance DESC limit 1";
			}else{
				$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice[0]['invoice_id']."' order by max_thirty_reserve ASC limit 1";
				
			}
			
			$query=new Bin_Query();
			$query->executeQuery($bid_sql);
			$bid = $query->records;
			
			
			if(count($bid) > 0){
				
				$query=new Bin_Query();
				$closed_sql = "INSERT INTO `invoice_closed` (`invoice_id` ,`won_by` ,`min_advance` ,`max_thirty_reserve` ,`invoice_bidding_id` ,`payment_status` ,`close_time`) VALUES 
				('".$bid[0]['invoice_id']."', '".$bid[0]['user_id']."', '".$bid[0]['min_advance']."', '".$bid[0]['max_thirty_reserve']."', '".$bid[0]['invoice_bidding_id']."', '0', NOW())";
				$query->executeQuery($closed_sql);
				$closed_id 		= $query->insertid;
				$closed_sbid 	= $query->records;

				
				$clquery		= new Bin_Query();
				$closed_sql 	= " UPDATE 
								invoice_closed c 
								INNER JOIN (
									SELECT CONCAT(DATE_FORMAT(NOW(),'%Y-%m-%d-'),REPLACE(CONCAT('ss',(1000000 + COUNT( `close_id` ) )),'ss1','0')) as n FROM `invoice_closed` WHERE DATE(`close_time` ) = CURDATE()
								) r 
								SET 
									c.closed_ref_id = r.n
								WHERE
									c.close_id = '".$closed_id."' ";
				$clquery->executeQuery($closed_sql);
	
				$query=new Bin_Query();
				$invoice_sql = "UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$bid[0]['invoice_id']." LIMIT 1 ;";
				$query->executeQuery($invoice_sql);
				$invoice = $query->records;
				
				$output['invoice_id'] = $bid[0]['invoice_id'];
				$output['result'] ="Bid Accepted SuccessFully";
			}

		}// Auction Accept Flow Ends here 
		
		return $output;
	
	}//End of Function




	//Starts If the Invoice has no Bid count , this Function will get executed
	function saveOpenBid()
	{
		$user_id = $_SESSION['user']['userid'];
		$inv_id = $_POST['inv_id'];
		

		$query=new Bin_Query();
		$temp_sql = "SELECT * FROM `invoice_master` where   invoice_id=".$inv_id." && trading_close_date > NOW() && invoice_status =1 limit 1";
		$query->executeQuery($temp_sql);
		$temp_reg = $query->records;
		
		//Check if the Invoice Id provided is valid 
		if(count($temp_reg) == 0) {
			echo "3";
			exit;
		}
		
		if($temp_reg[0]['sales_type'] == 1){
			$min_bid = $_POST['min_bid'];// * $_POST['range'];
			$reserve = 0;
		}else{
			$min_bid = 0;
			$reserve = $_POST['min_bid'];// * $_POST['range'];	
		}
		
		//Check Buy out 
		if(isset($_POST['buy'])) $buy =2; else $buy = 1;
		
		
		//Check Buy out is Not set
		if($buy == 1) {
			
			//Insert Bid
			$sql1=" INSERT INTO `invoice_bidding` (`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,
												   `buy_out` ,`auto_bid` ,`bid_time`)
				VALUES ('".$user_id."', '".$inv_id."', '".$min_bid."', '".$reserve."', '$buy', '2', NOW()) ";
			$query=new Bin_Query();
			$query->updateQuery($sql1);
			$bid = $query->insertid;
			
			if($temp_reg[0]['sales_type'] == 1 && $temp_reg[0]['closing_type'] =='1' && ($temp_reg[0]['min_advance'] == $min_bid || ($temp_reg[0]['min_advance']-1) == $min_bid)){
					
				//Frozen Process
				$query=new Bin_Query();
				$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
				$query->updateQuery($sql2);	
				
				Model_MTradeFloor::closeInvoice($inv_id);
				
			}else if($temp_reg[0]['sales_type'] !=1 && $temp_reg[0]['closing_type'] == '1'  && ($temp_reg[0]['max_thirty_day_reserve'] == $reserve || ($temp_reg[0]['max_thirty_day_reserve']-0.001) == $reserve)) {
				
	
				//Frozen Process
				$query=new Bin_Query();
				$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
				$query->updateQuery($sql2);	
				
				Model_MTradeFloor::closeInvoice($inv_id);
			}
	

		}else{	//Process If Buy Out Set

			if($temp_reg[0]['sales_type'] == 1){
					$sql1=" INSERT INTO `invoice_bidding` (`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,
														   `buy_out` ,`auto_bid` ,`bid_time`)
							VALUES ('".$user_id."', '".$inv_id."', '".$temp_reg[0]['buy_min_advance']."', 
							'0', '$buy', '2', NOW()) ";
			}else{
				$sql1=" INSERT INTO `invoice_bidding` (`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,
													   `buy_out` ,`auto_bid` ,`bid_time`)
						VALUES ('".$user_id."', '".$inv_id."', '0', 
								'".$temp_reg[0]['buy_max_thirty_day_reserve']."', '$buy', '2', NOW()) ";	
			}
		
			$query=new Bin_Query();
			$query->updateQuery($sql1);
			$bid = $query->insertid;
			
			Model_MTradeFloor::closeInvoice($inv_id);
			
			//Frozen Process
			$query=new Bin_Query();
			$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
			$query->updateQuery($sql2);
			
			

		}

		// Insert Bidding History
		$query=new Bin_Query();
		$existingBid_sql = "SELECT * FROM `invoice_bidding` WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." limit 1";
		$query->executeQuery($existingBid_sql);
		$existingBid = $query->records;
		if(count($existingBid) > 0){

			//Insert Bid History
			$query=new Bin_Query();
			$history_sql="INSERT INTO `invoice_bidding_history` (`invoice_bidding_id` ,`user_id` ,`invoice_id` ,
										`min_advance` ,`max_thirty_reserve` ,`buy_out` ,`auto_bid` ,`bid_time`)
							VALUES ('".$existingBid[0]['invoice_bidding_id']."', '".$existingBid[0]['user_id']."', 
									'".$existingBid[0]['invoice_id']."', '".$existingBid[0]['min_advance']."', 
									'".$existingBid[0]['max_thirty_reserve']."', '".$existingBid[0]['buy_out']."', 
									'".$existingBid[0]['auto_bid']."', '".$existingBid[0]['bid_time']."');";
			$query=new Bin_Query();
			$query->updateQuery($history_sql);

			//Enable Bid Notification fro Trader
			$history_sql="UPDATE `invoice_master` SET `bids` = '1' WHERE `invoice_id` = ".$existingBid[0]['invoice_id']." LIMIT 1 ;";
			$query=new Bin_Query();
			$query->updateQuery($history_sql);
			
			$sales_type 				= $temp_reg[0]['sales_type'];
			$debx 						= $temp_reg[0]['debx'];
			$face_value 				= $temp_reg[0]['face_value'];
			$min_advance				= $existingBid[0]['min_advance'];
			$max_thirty_day_reserve 	= $existingBid[0]['max_thirty_reserve'];
			$ex_date 					= $temp_reg[0]['expected_date'];
			$tr_date 					= $temp_reg[0]['trading_close_date'];
			$buy_min_advance 			= $temp_reg[0]['buy_min_advance'];
			$buy_max_thirty_day_reserve = $temp_reg[0]['buy_max_thirty_day_reserve'];
			$reg_id						= $existingBid[0]['invoice_id'];
			$actual_date 				= $temp_reg[0]['actual_date'];
			$reg_id 					= $temp_reg[0]['invoice_id'];


			
			if($sales_type =="1"){
				
				$result1 									= $face_value - 7;
				if($debx == "1")
					$result1 								= $result1	- 50; 
				
				$value 										= $min_advance;
				$tradeValues 								= $temp_reg[0];

				$tradeValues['min_advance'] 				= $value;
				$yield 										= Model_MHelpers::outrightYield($tradeValues);
				
				$temp_reg[0]['yield']						= $yield;
				$temp_reg[0]['min_advance']					= $min_advance;
				$temp_reg[0]['max_thirty_day_reserve']		= $max_thirty_day_reserve;
				$returnCalc 								= Model_MHelpers::outrightDiscountCalc($temp_reg[0]);
				$tPurchase									= number_format($min_advance,2, '.', ',');
				$discount									= $returnCalc['discount'];	
					
			}elseif($sales_type =="2"){
				
				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::managedYield($tradeValues, '2');
				
				$purchase_price 							= $face_value-($face_value*($tradeValues['max_thirty_day_reserve'] /100)*12*180/360);
				$discount									= $max_thirty_day_reserve;
				
			}elseif($sales_type =="5"){
				
				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::installmentYield($tradeValues);

				$query 		= new Bin_Query();
				$sql 		= "SELECT org.organisation_id, org.purchase_price FROM organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' LIMIT 1";
				$query->executeQuery($sql);
				$org = $query->records[0];
				
				$purchase_price 							= $org['purchase_price']/100;
				
				$discount									= $max_thirty_day_reserve;
				
			}else{
				

				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::performanceYield($tradeValues);
				$discount									= $max_thirty_day_reserve;
								
			}
			
			$purchase_price			= number_format($purchase_price,2, '.', '');
			
			//Insert Purchase Price If Trade is Closed
			$cls_query				= new Bin_Query();
			$cls_sql 				= " UPDATE invoice_closed SET purchase_price = '".$purchase_price."' ".
									" WHERE `invoice_id` = '".$existingBid[0]['invoice_id']."' LIMIT 1";
			$cls_query->executeQuery($cls_sql);
			
				
				
			//Insert Bid History
			$query=new Bin_Query();
			$history_sql="UPDATE `invoice_master` SET 
				`bid_yield` = '".$yield."',`bid_return` = '".$result1."' ,`discount_rate` = '".$discount."' 
				 WHERE `invoice_master`.`invoice_id` ='".$existingBid[0]['invoice_id']."' LIMIT 1";
			$query=new Bin_Query();
			$query->updateQuery($history_sql);
			

			if($buy ==2){
				if($_REQUEST['direct'] ==''){
					echo '<script>window.close();</script>';
					exit;
				}
				
				//exit;
			}
			
	
				
			}

		$reg_id = $query->insertid;
		if($reg_id) return true; else false;


	}//End of Function

	//Start If Bid is already for an Invoice This Function Will Execute
	function updateOpenBid()
	{
		
		$user_id = $_SESSION['user']['userid'];
		$inv_id = $_POST['inv_id'];

		$query=new Bin_Query();
		$temp_sql = "SELECT * FROM `invoice_master` where   invoice_id=".$inv_id." && trading_close_date > NOW() && invoice_status =1 limit 1";
		$query->executeQuery($temp_sql);
		$temp_reg = $query->records;

		//Check if the Invoice Id provided is valid 
		if(count($temp_reg) == 0) {
			echo "3";
			exit;
		}
		
		
		
		
		
		if($temp_reg[0]['sales_type'] == 1){
			$min_bid = $_POST['min_bid'];// * $_POST['range'];
			$reserve = 0;
		}else{
			$min_bid = 0;
			$reserve = $_POST['min_bid'];// * $_POST['range'];	
		}

		//Check Buy out 	
		if(isset($_POST['buy'])) $buy =2; else $buy = 1;

		$query=new Bin_Query();
		$existingBid_sql = "SELECT * FROM `invoice_bidding` WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." limit 1";
		$query->executeQuery($existingBid_sql);
		$existingBid = $query->records;
		
		

		//Checks If the the Trader has Already made a Bid
		if(count($existingBid) > 0){

			$query=new Bin_Query();
			$sql = "SELECT * FROM `invoice_bidding` where `invoice_id` = ".$inv_id." order by min_advance desc limit 1";
			$query->executeQuery($sql);
			$invoice = $query->records;

			//Increase and Decrease of Max Advance and Min Reserve.
			$max_advance = $_POST['min_bid'];// * $_POST['range']; //$invoice[0]['min_advance'] + $_POST['inc_max_adv'];
			$min_advance = $_POST['min_bid'];// * $_POST['range']; //$invoice[0]['max_thirty_reserve'] - $_POST['inc_min_adv'];			

			if($buy == 1) {
				
				$query=new Bin_Query();
				$sql1="UPDATE `invoice_bidding` SET `min_advance` = ".$min_bid.",
					`max_thirty_reserve` = ".$reserve.",
					`buy_out` = '".$buy."',
					`bid_time` = NOW() , flag= '0' WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." LIMIT 1 ;";  
				$query=new Bin_Query();
				$query->updateQuery($sql1);
				
				
				if($temp_reg[0]['sales_type'] == 1 && $temp_reg[0]['closing_type'] =='1' && ($temp_reg[0]['min_advance'] == $min_bid || ($temp_reg[0]['min_advance']-1) == $min_bid)){
					
					//Frozen Process
					$query=new Bin_Query();
					$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
					$query->updateQuery($sql2);	
					
					Model_MTradeFloor::closeInvoice($inv_id);
					
				}else if($temp_reg[0]['sales_type'] !=1 && $temp_reg[0]['closing_type'] == '1'  && ($temp_reg[0]['max_thirty_day_reserve'] == $reserve || ($temp_reg[0]['max_thirty_day_reserve']-0.001) == $reserve)) {
					
					//Frozen Process
					$query=new Bin_Query();
					$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
					$query->updateQuery($sql2);	
					
					Model_MTradeFloor::closeInvoice($inv_id);
				}
				
				
			}else{
		
				//Buyout Set tings is Executed
				$query=new Bin_Query();
				
				
				if($temp_reg[0]['sales_type'] == 1){
					
					$sql1="UPDATE `invoice_bidding` SET `min_advance` = '".$temp_reg[0]['buy_min_advance']."',
					`max_thirty_reserve` = '0',
					`buy_out` = '".$buy."',
					`bid_time` = NOW() , flag= '0' WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." LIMIT 1 ;";  
					
				}else{
					
					$sql1="UPDATE `invoice_bidding` SET `min_advance` = '0',
					`max_thirty_reserve` = '".$temp_reg[0]['buy_max_thirty_day_reserve']."',
					`buy_out` = '".$buy."',
					`bid_time` = NOW(), flag= '0' WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." LIMIT 1 ;";  
					
				}

					
				$query->updateQuery($sql1);
				
				//Frozen Process
				$query=new Bin_Query();
				$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
				$query->updateQuery($sql2);
				
				Model_MTradeFloor::closeInvoice($inv_id);

			}
		}else{
			if($buy == 1) {

				$query=new Bin_Query();
				$sql = "SELECT * FROM `invoice_bidding` where `invoice_id` = ".$inv_id." order by min_advance desc limit 1";
				$query->executeQuery($sql);
				$invoice = $query->records;
				
				//New User Join's the Bidding.		
				if(count($invoice) > 0){

					$max_advance = $invoice[0]['min_advance'] + $_POST['inc_max_adv'];
					$min_advance = $invoice[0]['max_thirty_reserve'] - $_POST['inc_min_adv'];
					
					//Insert Bid
					$query=new Bin_Query();
					
					
					if($temp_reg[0]['sales_type'] == 1){
					
						$sql1=" INSERT INTO `invoice_bidding` (`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,
															   `buy_out` ,`auto_bid` ,`bid_time`)
								VALUES ('".$user_id."', '".$inv_id."', '".$min_bid."', '".$reserve."', '$buy', '2', NOW()) ";
					
					}else{
						$sql1=" INSERT INTO `invoice_bidding` (`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,
															   `buy_out` ,`auto_bid` ,`bid_time`)
								VALUES ('".$user_id."', '".$inv_id."', '".$min_bid."', '".$reserve."', '$buy', '2', NOW()) ";
						
					}
					
					
					$query=new Bin_Query();
					$query->updateQuery($sql1);
					
					
					if($temp_reg[0]['sales_type'] == 1 && $temp_reg[0]['closing_type'] =='1' && ($temp_reg[0]['min_advance'] == $min_bid || ($temp_reg[0]['min_advance']-1) == $min_bid)){
					
						//Frozen Process
						$query=new Bin_Query();
						$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
						$query->updateQuery($sql2);	
						
						Model_MTradeFloor::closeInvoice($inv_id);
						
					}else if($temp_reg[0]['sales_type'] !=1 && $temp_reg[0]['closing_type'] == '1'  && ($temp_reg[0]['max_thirty_day_reserve'] == $reserve || ($temp_reg[0]['max_thirty_day_reserve']-0.001) == $reserve)) {
						
						//Frozen Process
						$query=new Bin_Query();
						$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
						$query->updateQuery($sql2);	
						
						Model_MTradeFloor::closeInvoice($inv_id);
					}

				}
			}else{	
			
				//Buyout Settings is Executed Before Any one Bid's the Invoice
				$query=new Bin_Query();

				if($temp_reg[0]['sales_type'] == 1){
					
					$sql1=" INSERT INTO `invoice_bidding` (	`user_id` ,`invoice_id` ,`min_advance` , `max_thirty_reserve` ,
														   `buy_out` ,`auto_bid` ,`bid_time`)
							VALUES ('".$user_id."', '".$inv_id."', '".$temp_reg[0]['buy_min_advance']."', 
									'0', '$buy', '2', NOW()) ";
				}else{
					
					$sql1=" INSERT INTO `invoice_bidding` (	`user_id` ,`invoice_id` ,`min_advance` , `max_thirty_reserve` ,
														   `buy_out` ,`auto_bid` ,`bid_time`)
							VALUES ('".$user_id."', '".$inv_id."', '0', 
									'".$temp_reg[0]['buy_max_thirty_day_reserve']."', '$buy', '2', NOW()) ";
				}

				$query->updateQuery($sql1);
				$query=new Bin_Query();

				//Frozen Process
				$sql2="UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$inv_id." LIMIT 1";
				$query->updateQuery($sql2);
				
				Model_MTradeFloor::closeInvoice($inv_id);

			}
		}

		
		$query=new Bin_Query();
		$existingBid_sql = "SELECT * FROM `invoice_bidding` WHERE `invoice_id` = ".$inv_id."  && `user_id` =".$user_id." limit 1";
		$query->executeQuery($existingBid_sql);
		$existingBid = $query->records;

		if(count($existingBid) > 0){
			
			//Insert Bid History
			$query=new Bin_Query();
			$history_sql="INSERT INTO `invoice_bidding_history` (`invoice_bidding_id` ,`user_id` ,`invoice_id` ,`min_advance` ,`max_thirty_reserve` ,`buy_out` ,`auto_bid` ,`bid_time`)VALUES ('".$existingBid[0]['invoice_bidding_id']."', '".$existingBid[0]['user_id']."', '".$existingBid[0]['invoice_id']."', '".$existingBid[0]['min_advance']."', '".$existingBid[0]['max_thirty_reserve']."', '".$existingBid[0]['buy_out']."', '".$existingBid[0]['auto_bid']."', '".$existingBid[0]['bid_time']."');";
			$query=new Bin_Query();
			$query->updateQuery($history_sql);
			
			
			//Enable Bid Notification for Trader
			$history_sql="UPDATE `invoice_master` SET `bids` = '1' WHERE `invoice_id` = ".$existingBid[0]['invoice_id']." LIMIT 1 ;";
			$query=new Bin_Query();
			$query->updateQuery($history_sql);

			$sales_type = $temp_reg[0]['sales_type'];
			$face_value = $temp_reg[0]['face_value'];
			$min_advance	= $existingBid[0]['min_advance'];
			$max_thirty_day_reserve = $existingBid[0]['max_thirty_reserve'];
			$ex_date = $temp_reg[0]['expected_date'];
			$tr_date = $temp_reg[0]['trading_close_date'];
			$buy_min_advance =  $temp_reg[0]['buy_min_advance'];
			$buy_max_thirty_day_reserve = $temp_reg[0]['buy_max_thirty_day_reserve'];
			$debx = $temp_reg[0]['debx'];
			$reg_id = $existingBid[0]['invoice_id'];
			$actual_date = $temp_reg[0]['actual_date'];
			
									
			if($sales_type == "1"){
				
				$bid_sql 				= "SELECT * FROM invoice_bidding WHERE invoice_id= ".$temp_reg[0]['invoice_id']." 
										order by min_advance DESC LIMIT 1";
								
				
				$bid_query				= new Bin_Query();
				$bid_query->executeQuery($bid_sql);
				$history 				= $bid_query->records;
				
				if($history[0]['min_advance'] > $existingBid[0]['min_advance']){
					echo '<script> window.close(); </script>';
					exit;
				}
								
			}else {
				
				$bid_sql 				= "SELECT * FROM invoice_bidding WHERE invoice_id= ".$temp_reg[0]['invoice_id']." 
										order by max_thirty_reserve ASC LIMIT 1";
				
				$bid_query				= new Bin_Query();
				$bid_query->executeQuery($bid_sql);
				$history 				= $bid_query->records;
				
				if($history[0]['max_thirty_reserve'] < $existingBid[0]['max_thirty_reserve']){
					echo '<script> window.close(); </script>';
					exit;
				}
			}
			
			
			if($sales_type =="1"){
				
				$result1 									= $face_value - 7;
				if($debx == "1")
					$result1 								= $result1	- 50; 
				
				$value 										= $min_advance;
				$tradeValues 								= $temp_reg[0];

				$tradeValues['min_advance'] 				= $value;
				$yield 										= Model_MHelpers::outrightYield($tradeValues);
				
				$temp_reg[0]['yield']						= $yield;
				$temp_reg[0]['min_advance']					= $min_advance;
				$temp_reg[0]['max_thirty_day_reserve']		= $max_thirty_day_reserve;
				$returnCalc 								= Model_MHelpers::outrightDiscountCalc($temp_reg[0]);
				$tPurchase									= number_format($min_advance,2, '.', ',');
				$discount									= $returnCalc['discount'];	
			}elseif($sales_type =="2"){
				
				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::managedYield($tradeValues, '2');
				
				$purchase_price 							= $face_value-($face_value*($tradeValues['max_thirty_day_reserve'] /100)*12*180/360);
			
				$discount									= $max_thirty_day_reserve;
				
			}elseif($sales_type =="5"){
				
				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::installmentYield($tradeValues);

				$query 		= new Bin_Query();
				$sql 		= "SELECT org.organisation_id, org.purchase_price FROM organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' LIMIT 1";
				$query->executeQuery($sql);
				$org = $query->records[0];
				
				$purchase_price 							= $org['purchase_price']/100;
				
				$discount									= $max_thirty_day_reserve;
				
			}else{
				

				$result1 									= $face_value - 7;
				$rebate_refund								= parent::getSiteSettings('rebate_refund');
				$value 										= $max_thirty_day_reserve;
				$tradeValues 								= $temp_reg[0];
				$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
				$yield 										= Model_MHelpers::performanceYield($tradeValues);
				$discount									= $max_thirty_day_reserve;
								
			}
			
			$purchase_price			= number_format($purchase_price,2, '.', '');
			
			//Insert Purchase Price If Trade is Closed
			$cls_query				= new Bin_Query();
			$cls_sql 				= " UPDATE invoice_closed SET purchase_price = '".$purchase_price."' ".
									" WHERE `invoice_id` = '".$existingBid[0]['invoice_id']."' LIMIT 1";
			$cls_query->executeQuery($cls_sql);
			
			
			//Insert Bid History
			$query=new Bin_Query();
			$history_sql="UPDATE `invoice_master` SET 
				`bid_yield` = '".$yield."',`bid_return` = '".$result1."',`discount_rate` = '".$discount."' 
				 WHERE `invoice_master`.`invoice_id` ='".$existingBid[0]['invoice_id']."' LIMIT 1";
			$query->updateQuery($history_sql);

			if($buy ==2){
			
				if($_REQUEST['direct'] ==''){
					echo '<script>window.close();</script>';
					exit;
				}

			}

			
		}
		$reg_id = $query->insertid;

		if($reg_id) return true; else false;

	}//End of Function
	
	function closeInvoice($id){

		$user_id = $_SESSION['user']['userid'];

		$query=new Bin_Query();
		$sql = "SELECT  sales_type, invoice_id FROM `invoice_master` where  invoice_id = '".$id."' limit 1";
		$query->executeQuery($sql);
		$invoice = $query->records;

		$state = $_REQUEST['state'];	


		//Auction Accept Flow
		if(count($invoice) > 0){
			
			
			if($invoice[0]['sales_type'] == "1"){
			
				$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice[0]['invoice_id']."' order by min_advance DESC limit 1";
			}else{
				$bid_sql = "SELECT * FROM invoice_bidding where invoice_id = '".$invoice[0]['invoice_id']."' order by max_thirty_reserve ASC limit 1";
				
			}
			
			$query=new Bin_Query();
			$query->executeQuery($bid_sql);
			$bid = $query->records;
			
			
			if(count($bid) > 0){
				
				$query=new Bin_Query();
				$closed_sql = "INSERT INTO `invoice_closed` (`invoice_id` ,`won_by` ,`min_advance` ,`max_thirty_reserve` ,`invoice_bidding_id` ,`payment_status` ,`close_time`) VALUES 
				('".$bid[0]['invoice_id']."', '".$bid[0]['user_id']."', '".$bid[0]['min_advance']."', '".$bid[0]['max_thirty_reserve']."', '".$bid[0]['invoice_bidding_id']."', '0', NOW())";
				$query->executeQuery($closed_sql);
				$closed_id 		= $query->insertid;
				$closed_sbid 	= $query->records;

				
				$clquery		= new Bin_Query();
				$closed_sql 	= " UPDATE 
								invoice_closed c 
								INNER JOIN (
									SELECT CONCAT(DATE_FORMAT(NOW(),'%Y-%m-%d-'),REPLACE(CONCAT('ss',(1000000 + COUNT( `close_id` ) )),'ss1','0')) as n FROM `invoice_closed` WHERE DATE(`close_time` ) = CURDATE()
								) r 
								SET 
									c.closed_ref_id = r.n
								WHERE
									c.close_id = '".$closed_id."' ";
				$clquery->executeQuery($closed_sql);
	
				$query=new Bin_Query();
				$invoice_sql = "UPDATE `invoice_master` SET `invoice_status` = '3' WHERE `invoice_id` =".$bid[0]['invoice_id']." LIMIT 1 ;";
				$query->executeQuery($invoice_sql);
				$invoice = $query->records;
			}
		}
	}
}
?>