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/MTradeUser.php
<?php
include_once('admin/classes/Model/base_actions.php');
class Model_MTradeUser extends Base_actions
{ 
	var $output = array();

	/*----- Gets Help Links fro Form Function Starts here -----*/
	public function getHelpLinks($id){

		$query=new Bin_Query();
		$sql = "SELECT content FROM `help_tips_settings` where 	help_title_id =$id order by help_tip_id asc";
		$query->executeQuery($sql);
		$help_links = $query->records;

		return $help_links;

	}//End of Function

	//Starts Get Debtor w.r.t Traders
	public function getMyDebtor(){

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

		$query=new Bin_Query();
		$sql = "SELECT d.debtor_id, d.debtor_name , IF(d.trade_name='',d.debtor_name, d.trade_name) as orderings  FROM `debtors_detail` as d, `debtor_relation` as r where r.trader_id =". $user_id." && d.debtor_id = r.debtor_id order by orderings ASC";
		$query->executeQuery($sql);
		$debtor = $query->records;

		return $debtor;

	}//End Of Get Debtor w.r.t Traders<br>

	//Starts Get MyAccount Trade List 
	public function getMyTrade(){


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

		$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 0:
						$sort .= "order by TIMEDIFF(m.trading_close_date, NOW()) desc";
						break;*/
					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($sort ==' order by  , ') $sort = ''; */

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

		$qry 	= new Bin_Query();
		$sql 	= "SELECT instalment_etr FROM organisation_details WHERE user_id='".$_SESSION['user']['userid']."' ";
		$qry->executeQuery($sql);
		$instalment = $qry->records[0]['instalment_etr'];


		if($instalment =='1'){

			$ins_where = 'm.draft = 0 && m.instalment_draft=0 && m.instalment=1 ';
		}else{
			$ins_where = 'm.draft = 0  && m.root_invoice_id > 0 ';
		}

		
        $noofrec         = (isset($_GET['show']) && ctype_digit($_GET['show']))?trim($_GET['show']):100;
        $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,d.currency_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( 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,  
		
		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,
		DATE_FORMAT(m.approved_date,'%Y-%m-%d') as approvedday,
		
		org.organisation_name , org.organisation_reference_id,  org.active_debtors,
		, (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, `debtors_detail` as d , 
		`invoice_master` as m , currencies as c , debtors_master as dm
		
		WHERE  m.user_id = '".$user_id."' && m.invoice_id = m.invoice_id && $ins_where &&
		d.debtor_id = m.debtor_id && dm.debtor_master_id = d.parent_id
		&& org.user_id =  m.user_id &&
		t.user_id = m.user_id  && 
		c.currency_id = d.currency_id
		$where group by m.invoice_id order by m.invoice_status  
        LIMIT ".$start.",".$noofrec; 

		$query->executeQuery($sql);
		$trade         = $query->records;
        $recordSize = $query->totrows;
        
        $query->executeQuery('SELECT FOUND_ROWS() as totalRecord');
        $totalRecord=$query->records[0]['totalRecord'];
		
		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]['root_invoice_id'] !=0){
				$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'];
			$trade[$i]['currency_code'] = $currency[0]['currency_code'];
		}

		if($_SESSION['user']['usertype'] == 1 || $_SESSION['user']['usertype'] == 2)
        {
			return Display_DTradeUser::getInvestorFloor(ceil($totalRecord/$noofrec),$trade);
		}
        else
        {
			return Display_DTradeUser::getTraderBook(ceil($totalRecord/$noofrec),$trade);
		}
	}
	
	function getMyDraftById($id){
		
		if($_REQUEST['id'] !='' && is_numeric($_REQUEST['id'])){
			$id = $_REQUEST['id'];	
		}else{
			header('location: index.php?do=opentrade');	
		}
		
		$query=new Bin_Query();
		
		$sql 		= "SELECT m.* , d.invoice_document_path,d.invoice_support_document_path,d.purchase_order_document_path,  ".
					" DATE_FORMAT(m.created_at,'%d/%m/%y') as created FROM invoice_master as m , invoice_documents as d ".
					" WHERE m.invoice_id ='".$id."' AND m.draft='1' && d.invoice_id = m.invoice_id  LIMIT 1";
		$query->executeQuery($sql);
		$draft = $query->records;
		
		
		if(count($draft) == 0){
			header('location: index.php?do=opentrade');	
		}
		
		return $draft;
	
	}

	function getInstalmentDraftById($id){
		
		if($_REQUEST['id'] !='' && is_numeric($_REQUEST['id'])){
			$id = $_REQUEST['id'];	
		}else{
			header('location: index.php?do=instalment_etr');	
		}
		
		$query=new Bin_Query();
		
		$sql 		= "SELECT m.* , d.invoice_document_path,d.invoice_support_document_path,d.purchase_order_document_path,  ".
					" DATE_FORMAT(m.created_at,'%d/%m/%y') as created FROM invoice_master as m , invoice_documents as d ".
					" WHERE m.invoice_id ='".$id."' AND m.instalment_draft='1' && d.invoice_id = m.invoice_id  LIMIT 1";
		$query->executeQuery($sql);
		$draft = $query->records;
		
		
		if(count($draft) == 0){
			header('location: index.php?do=instalment_etr');	
		}
		
		return $draft;
	
	}
	
	function updateTrader()
    {	
		//echo $_REQUEST['id']; exit;
		
		if($_REQUEST['id'] !='' && is_numeric($_REQUEST['id'])){
			$id = $_REQUEST['id'];	
		}else{
			header('location: index.php?do=opentrade');	
		}
		
		$user_id		 	= $_SESSION['user']['userid'];

		$sales_type					= $_POST['sales_type'];
		$sales_arr					= explode("-",$sales_type);
		$sales_type					= $sales_arr[0];
		$fieldSet					= $sales_arr[1];

		//Checking the User Details		
		$query=new Bin_Query();
		$temp_sql 			= "SELECT `nace_group_id`,`nace_id` FROM `temp_registration` where user_id=".$user_id." limit 1";
		$query->executeQuery($temp_sql);
		$temp_reg 			= $query->records;
	
		if(count($temp_reg) == 0){
			header('Location: index.php?do=opentrade');
		}

		//Getting Debtor Details
		$query				= new Bin_Query();
		$debt_sql 			= "SELECT * FROM `debtors_detail` where debtor_id=".$_POST['debtor_id']." limit 1";
		$query->executeQuery($debt_sql);

		$debtor 			= $query->records;
		if(count($debtor) 	== 0){
			header('Location: index.php?do=opentrade');
		}
		

		//imploding the date's
		if($sales_type!='4'){

			$ac_date 			= $_POST['ac_year']."-".$_POST['ac_month']."-".$_POST['ac_date'];
			$ex_date 			= $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];
			$invoice_date 			= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
			$tr_date 			= $_POST['tr_year']."-".$_POST['tr_month']."-".$_POST['tr_date']." ".$_POST['hours'].":".$_POST['mins'].":00";
		}else{

			$ac_date 			= date('Y-m-d');
			$invoice_date 		= date('Y-m-d');

			if($_POST['etr_months']=='0'){

				$etr_days 			= 1 * 30;
			}else{
				
				$etr_days 			= $_POST['etr_months'] * 30;
			}


			$d = new DateTime();
			$d->modify($etr_days." days");
			$ex_date = $d->format("Y-m-d");

			$t = new DateTime();
			$t->modify("15 days");
			$tr_date = $t->format("Y-m-d");
		}


		//Buyout Setting
		if($_POST['buyout'] =='') $buyout =2; else $buyout =$_POST['buyout'];

		$min_advance				=0;
		$buy_min_advance			=0;
		$max_thirty_day_reserve		=0;
		$buy_max_thirty_day_reserve	=0;

		
		

		if($fieldSet=="model1"){
			$min_advance					= $_POST['purchase_price'];
			if($_POST['buyout']=="1"){
				$buy_min_advance			= $_POST['buyout_price'];
			}
		}
		else if($fieldSet=="model2"){
			$max_thirty_day_reserve			= $_POST['discount_price'];
			if($_POST['buyout']=="1"){
				$buy_max_thirty_day_reserve	= $_POST['buyout_discount_price'];
			}
		}
		else if($sales_type =="4"){

			$max_thirty_day_reserve			= $_POST['discount_price'];

			// if($_POST['buyout']=="1"){
					$buy_max_thirty_day_reserve	= $_POST['buyout_discount_price'];
			// }

			$sales_revolving				= 1;	
			
		}


		$result11 			= '';
		$result1 			= '';
		
		$draft 				= 0;
		
		if($_POST['save']  == 'Save'){
			$draft 			= 1;	
		}


		$query 		= new Bin_Query();
		$sql 		= "SELECT org.organisation_id, org.organisation_reference_id FROM organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' LIMIT 1";
		$query->executeQuery($sql);
		$org = $query->records[0];
		
		$facevalue 		= $_REQUEST['etr_face_value'];
								
		if($sales_type=="4"){
							
			$sql 				= "UPDATE `invoice_master` SET `po_id` = '".$_POST['po']."',
								`invoice_no` = '".trim($_POST['invoice_no'])."',
								`root_invoice_id` = '0',	
								`debtor_id` = '".$_POST['debtor_id']."',	
								`face_value`='".$facevalue."',
								`revolving` = '1',
								`revolving_total` = '".$_POST['etr_no']."',
								`revolving_months` = '".$_POST['etr_months']."',
								`buy_out` = '".$buyout."',
								`description` = '".$_POST['desc']."',
								`payment_terms` = '".$_POST['payment']."',
								`actual_date` = '".$invoice_date."',
								`approved_date` = '".$invoice_date."',
								`expected_date` = '".$ex_date."',
								`trading_close_date` = '".$tr_date."',
								`min_advance` = '".$min_advance."',
								`max_thirty_day_reserve` = '".$max_thirty_day_reserve."',
								`buy_min_advance` = '".$buy_min_advance."',
								`buy_max_thirty_day_reserve` = '".$buy_max_thirty_day_reserve."',
								`debx` = '".$_POST['debx']."',
								`draft` = '".$draft."',
								`closing_type` = '".$_POST['closing']."',
								`modified_at` = NOW(),
								`is_synced` = '0',
								`etr_type` = '" . ETR_TYPE_RSA . "',
								`sales_type` = '".$_POST['etr_type']."' WHERE `invoice_id` ='".$_REQUEST['id']."' LIMIT 1 ;";
							
			$_POST['face_value'] 	= $_POST['etr_face_value'];
			$sales_type 			= $_POST['etr_type'];
			
		}else{
			$sql 				= "UPDATE `invoice_master` SET `po_id` = '".$_POST['po']."',
								`invoice_no` = '".trim($_POST['invoice_no'])."',
								`root_invoice_id` = '0',	
								`debtor_id` = '".$_POST['debtor_id']."',	
								`face_value`='".$facevalue."',
								`buy_out` = '".$buyout."',
								`description` = '".$_POST['desc']."',
								`payment_terms` = '".$_POST['payment']."',
								`actual_date` = '".$invoice_date."',
								`approved_date` = '".$invoice_date."',
								`expected_date` = '".$ex_date."',
								`trading_close_date` = '".$tr_date."',
								`min_advance` = '".$min_advance."',
								`max_thirty_day_reserve` = '".$max_thirty_day_reserve."',
								`buy_min_advance` = '".$buy_min_advance."',
								`buy_max_thirty_day_reserve` = '".$buy_max_thirty_day_reserve."',
								`debx` = '".$_POST['debx']."',
								`draft` = '".$draft."',
								`closing_type` = '".$_POST['closing']."',
								`modified_at` = NOW(),
								`etr_type` = '" . ETR_TYPE_RSA . "',
								`sales_type` = '".$sales_type."' WHERE `invoice_id` ='".$_REQUEST['id']."' LIMIT 1 ;";
		}
		
		$query				= new Bin_Query();
		$query->updateQuery($sql);
		$reg_id 			= $_REQUEST['id'];
		
		
		
		$query=new Bin_Query();
		$temp_sql = "SELECT * FROM `invoice_master` where   invoice_id=".$reg_id." 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	= $temp_reg[0]['min_advance'];
		$max_thirty_day_reserve = $temp_reg[0]['max_thirty_day_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 = $temp_reg[0]['invoice_id'];
		$actual_date = $temp_reg[0]['actual_date'];
		
		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'];	
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['min_advance'] 			= $buy_min_advance;
				$ann_yield 								= Model_MHelpers::outrightYield($tradeValues);
			}
				
		}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);
			$discount									= $max_thirty_day_reserve;
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['max_thirty_day_reserve'] 		= $buy_max_thirty_day_reserve;
				$ann_yield 									= Model_MHelpers::managedYield($tradeValues);
			}	
			
		}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;
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['max_thirty_day_reserve'] 		= $buy_max_thirty_day_reserve;
				$ann_yield 									= Model_MHelpers::performanceYield($tradeValues);
			}	
							
		}

		
		//Insert Bid History
		//$query1=new Bin_Query(); `non_perform` ='".$non_yield."'
		$history_sql		= "UPDATE `invoice_master` SET `yield` = '".$yield."', `buy_yield` = '".$ann_yield."',".
							" `return` = '".$result1."', `buy_return` = '".$result11."',`discount_rate` = '".$discount."' ,".
							" bid_yield =0 , bid_return =0 WHERE `invoice_id` ='".$reg_id."' LIMIT 1";
		$query				= new Bin_Query();
		$query->updateQuery($history_sql);
		

		$ta = new Trade_actions();
        $ta->updateInvoiceFilesInStorage($reg_id,$_SESSION['user']['userid'],$_SESSION['user']['org_ref_id'],true,null);

		$query						= new Bin_Query();
		$sql 						= "SELECT address_email FROM address_details where ".
									" address_id = '".$debtor[0]['contact_address_id']."'  limit 1";
		$query->executeQuery($sql);
		$debtorAddress 				= $query->records;

		if($_POST['ack_notice']	 == "1" && $debtorAddress[0]['address_email']  != "" && $draft != '1' && $notice !='3'){
			//Getting Debtor Relation Details
		}
        
		if($reg_id) return true; else false;
	}
	
	
	//Starts Get MyDraft Listing 
	public function getMyDraftListing(){

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

		$qry 		= new Bin_Query();
		$sql 		= "SELECT instalment_etr FROM organisation_details WHERE user_id = '".$_SESSION['user']['userid']."' LIMIT 1 ";
		$qry->executeQuery($sql);
		$instalment_etr = $qry->records[0]['instalment_etr'];

		if($instalment_etr=='1')
		{
			$query		= new Bin_Query();
			$sql 		= "SELECT * ,".
						" DATE_FORMAT(created_at,'%d/%m/%y') as created FROM invoice_master ".
						" WHERE user_id='".$_SESSION['user']['userid']."' AND instalment_draft='1' && draft=0 && revolving_draft = 0";
			$query->executeQuery($sql);
			$draft 		= $query->records;
		}else{
			$query		= new Bin_Query();
			$sql 		= "SELECT * ,".
						" DATE_FORMAT(created_at,'%d/%m/%y') as created FROM invoice_master ".
						" WHERE user_id='".$_SESSION['user']['userid']."' AND draft='1' && revolving_draft = 0 && instalment_draft=0 ";
			$query->executeQuery($sql);
			$draft 		= $query->records;
		}
		
		for($i=0;$i<count($draft);$i++)
		{
			
			$query=new Bin_Query();
			$sql = "SELECT * FROM debtors_detail  where debtor_id = ".$draft[$i]['debtor_id']." limit 1";
			$query->executeQuery($sql);
			$debtor = $query->records;
			
			$draft[$i]['debtor_name'] = $debtor[0]['debtor_name'];
			$draft[$i]['trade_name'] = $debtor[0]['trade_name'];
			
			$query1=new Bin_Query();
			$sql1 = "SELECT nace_group_id, nace_group_code 	FROM `category_group` 
							where nace_group_id = '".$debtor[0]['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 = '".$debtor[0]['nace_id']."' limit 1";
			$query2->executeQuery($sql2);
			$nace_id = $query2->records;
			
			$draft[$i]['nace_id'] = $nace_id[0]['nace_code'];
			
			$draft[$i]['nace_group_id'] =  str_replace("Section","",$nace_group_id[0]['nace_group_code']).substr($nace_id[0]['nace_code'],0,2);	
			

		}
		
		return $draft;

	}//End of Get MyDraft Listing 
	

	//Starts Get MyAccount Trade List 
	public function getMyTradeHistory(){

		$user_id = $_SESSION['user']['userid'];
		
		//Sorting for Trade
		$sort ='';
		if($_REQUEST['sort'] =='') {
			$sort = 'order by m.trading_close_date DESC';
		}
		else {
			if($_REQUEST['sort'] == 'name') $sort = 'order by d.debtor_name asc';
			if($_REQUEST['sort'] == 'face') $sort = 'order by m.face_value asc';
			if($_REQUEST['sort'] == 'adv') $sort = 'order by m.min_advance asc';
			if($_REQUEST['sort'] == 'res') $sort = 'order by m.max_thirty_day_reserve asc';
			
		}
		//End of Sorting for Trade

		$query=new Bin_Query();
		$sql = "SELECT  m.*, d.debtor_id, d.debtor_name,d.debtor_risk,d.debtor_limit,d.nace_id as d_nace_id,d.nace_group_id as d_nace_group_id, TIMEDIFF(m.trading_close_date, NOW()) as expire_date FROM `debtors_detail` as d , `invoice_master` as m where  m.user_id = ".$user_id." && d.debtor_id = m.root_invoice_id $sort";
		$query->executeQuery($sql);
		$trade = $query->records;
		
		return $trade;

	}//End of Get MyAccount Trade List 

	// function stat to get the details for draft Trades
	public function getMySMBDraftTrade($userdetails)
	{

		//set POST variables
		$url = 'http://stage1.as01.demo.agiletech.ie/api/json/company/list';
		$fields = array(
		'hash' => $userdetails['partner_hashkey']
				);
		$fields_string='hash='.$userdetails['partner_hashkey'];
		
		//open connection
		$ch = curl_init($url);
		
		//set the url, number of POST vars, POST data
		//curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 360);
		curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, count($fields));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
		
		//execute post
		$result = curl_exec($ch);
		$result = json_decode($result);
		$orgid = $result->response[0]->id;
		//close connection
		curl_close($ch);

		//set POST variables
		$url = 'http://stage1.as01.demo.agiletech.ie/api/json/sale/list';
		$fields = array(
		'hash' => $userdetails['partner_hashkey'],
		'system_id' => $orgid
				);
		$fields_string='hash='.$userdetails['partner_hashkey'].'&system_id='.$orgid;
		
		//open connection
		$ch = curl_init($url);
		
		//set the url, number of POST vars, POST data
		//curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 360);
		curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST, count($fields));
		curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
		
		//execute post
		$result = curl_exec($ch);
		$result = json_decode($result);
		//close connection
/*		echo "<pre>";
		print_r($result);*/
		curl_close($ch);

		$rescount = count($result->response);
/*		ini_set('error_reporting',E_ALL);
		ini_set('display_errors',1);*/
		$response=$result->response;
		$output = array();
		$j=0;
		for($i=0;$i<$rescount;$i++)
		{
			$sqlinv = "SELECT STI.smb_invoice_id, SC.debtor_id FROM smb_temp_invoice AS STI, smb_customers SC WHERE STI.status='1' AND STI.smb_invoice_id='".$response[$i]->id."' AND STI.debtor_id='".$response[$i]->contractor_to."' AND STI.debtor_id=SC.customer_id";
			$qryinv = new Bin_Query();
			$qryinv->executeQuery($sqlinv);
			if(count($qryinv->records)>0)
			{
				$sqldeb = "SELECT debtor_name FROM debtors_detail WHERE debtor_id='".$qryinv->records[0]['debtor_id']."'";
				$qrydeb = new Bin_Query();
				$qrydeb->executeQuery($sqldeb);
				$output[$j]['debtorname'] = $qrydeb->records[0]['debtor_name'];
				foreach($response[$i] as $key=>$value)
					$output[$j][$key] = trim($response[$i]->$key);
				$j++;
			}
		}
		return $output;
	}// End function

	/*----- Gets Invoice/Trade Bid History Function Starts here -----*/
	public function getMyTradeBidHistory($id){
		
		

		$user_id 		= $_SESSION['user']['userid'];
		$query			= new Bin_Query();
		$sql 			= "SELECT  * FROM `invoice_master` where  user_id = ".$user_id." && invoice_id = $id LIMIT 1";
		$query->executeQuery($sql);
		$invoice 		= $query->records;

		$query			= new Bin_Query();
		if($invoice[0]['sales_type'] == '1'){
			
			$sql 		= "SELECT  b.* , m.sales_type , m.min_advance as advance, m.max_thirty_day_reserve as reserve, ".
						" m.buy_min_advance as buyadvance, m.buy_max_thirty_day_reserve as buyreserve, bid.flag, ".
						" org.organisation_reference_id, m.trade_reference_id FROM ".
						" `invoice_bidding_history` as b ,`invoice_master` as m ,invoice_bidding as bid,organisation_details as org ".
						" WHERE m.user_id = ".$user_id." && m.invoice_id = $id && b.invoice_id = m.invoice_id ".
						" && bid.invoice_id = b.invoice_id && org.user_id = b.user_id GROUP BY b.history_id ORDER BY b.min_advance DESC ";
			
		}else{
			
			$sql 		= "SELECT  b.* , m.sales_type , m.min_advance as advance, m.max_thirty_day_reserve as reserve, ".
						" m.buy_min_advance as buyadvance, m.buy_max_thirty_day_reserve as buyreserve, bid.flag, ".
						" org.organisation_reference_id, m.trade_reference_id FROM ".
						" `invoice_bidding_history` as b ,`invoice_master` as m ,invoice_bidding as bid,organisation_details as org ".
						" WHERE m.user_id = ".$user_id." && m.invoice_id = $id && b.invoice_id = m.invoice_id ".
						" && bid.invoice_id = b.invoice_id && org.user_id = b.user_id GROUP BY b.history_id ORDER BY b.max_thirty_reserve ";
		}

		$query->executeQuery($sql);
		$bid 			= $query->records;
		
		//Turn Off Invoice bidding Notification for Trader in Trade Floor
		$query			= new Bin_Query();
		$history_sql	= "UPDATE `invoice_master` SET `bids` = '0' WHERE `invoice_id` = ".$id." LIMIT 1 ;";
		$query			= new Bin_Query();
		$query->updateQuery($history_sql);

		return $bid;

	}//End of Function

	/*----- Gets Invoice Status Function Starts here -----*/
	public function getInvoiceStatus($id){

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

		$query=new Bin_Query();
		$sql = "SELECT  invoice_status FROM `invoice_master` where  user_id = ".$user_id." && invoice_id = $id ";
		$query->executeQuery($sql);
		$invoice = $query->records;
		
		//Various Invoice Status
		if($invoice[0]['invoice_status'] ==1){
			$output['status'] =1;
			$output['inline'] = 'Published';
		}else if($invoice[0]['invoice_status'] ==2){
			$output['status'] =2;
			$output['inline'] = 'Frozen';
		}else if($invoice[0]['invoice_status'] ==3){
			$output['status'] =3;
			$output['inline'] = 'Closed';
		}else{
			$output['status'] =0;
			$output['inline'] = 'InActive';
		}
		return $output;

	}//End of Function

	/*----- Gets Winner of Auction Function Starts here -----*/
	public function getInvoiceWonBy($id){

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

		$query=new Bin_Query();
		$sql = "SELECT  c.won_by,u.username,u.organization_name  FROM `invoice_closed` as c , `temp_registration` as u where  c.invoice_id = $id && u.user_id = c.won_by limit 1";

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

		return $won[0];

	}//End of Function


	public function getMyProfile()
    {
		$query=new Bin_Query();
		$query->executeQuery("SELECT t.*,a.*,IFNULL(state_name,a.address_state)  as address_state, IFNULL(state_master.state_id,a.address_state) as state_id, c.country_name
                              FROM `temp_registration` as t
                              LEFT JOIN `address_details` as a ON a.address_id = t.organization_address_id
                              LEFT JOIN `country_mas` as c ON c.country_id=a.address_country  
                              LEFT JOIN state_master ON state_master.state_id = a.address_state
                              WHERE t.user_id = ".$_SESSION['user']['userid']."
                              LIMIT 1");
        
        $result=$query->records[0];
        
        
        if ($result['user_type']=='6')
        {
            require_once ROOT_FOLDER.'/admin/classes/Model/MRetailInvestor.php';
            $result['additional_names']=Model_MRetailInvestor::getInvestorAdditionalNames($result['temp_reg_id']);
        }
        
		return $result;
	}


	/*----- Updates Trader's Profile Function Starts here -----*/
	public function updateMyProfile(){

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

		//Fetch user details
		$query=new Bin_Query();
 		$sql = "SELECT t.temp_reg_id, t.organization_address_id FROM `temp_registration` as t,  `address_details` as a, `country_mas` as c where t.user_id = ".$user_id." && a.address_id = t.organization_address_id && c.country_id=a.address_country  limit 1";
		$query->executeQuery($sql);
		$profile = $query->records;
		

		$temp_reg_id	= $profile[0]['temp_reg_id'];
		$organization_address_id	= $profile[0]['organization_address_id'];

		//Update address
		$query=new Bin_Query();
		$sql = "UPDATE `address_details` SET `address_line_one` = '".$_POST['org_addr']."',`address_line_two` = '".$_POST['org_addr1']."',`address_city` = '".$_POST['org_city']."',`address_state` = '".$_POST['org_state']."',`address_country` = '".$_POST['org_country']."',`address_zipcode` = '".$_POST['org_code']."',`address_phone_country` = '".$_POST['org_ph_country']."',`address_phone_code` = '".$_POST['org_ph_area']."',`address_phone` = '".$_POST['org_ph_phone']."',`address_mobile_country` = '".$_POST['org_m_country']."',`address_mobile_code` = '".$_POST['org_m_area']."',`address_mobile` = '".$_POST['org_m_phone']."',`address_fax_country` = '".$_POST['address_fax_country']."',`address_fax_code` = '".$_POST['address_fax_code']."',`address_fax` = '".$_POST['address_fax']."',`address_email` = '".$_POST['email']."',`modified_at` = NOW(),`modified_by` = '".$user_id."' WHERE `address_id` =".$organization_address_id." LIMIT 1 ;";
		$query->updateQuery($sql);

		//Update User Profile
		$query=new Bin_Query();
		$sql = "UPDATE `temp_registration` SET `first_name` = '".$_POST['f_name']."',`last_name` ='".$_POST['l_name']."',`job_title` = '".$_POST['job']."',`organization_name` = '".$_POST['org_name']."',`nace_group_id` ='".$_POST['siccat']."',`nace_id` = '".$_POST['sicgp']."' WHERE `temp_reg_id` =$temp_reg_id LIMIT 1 ;";
		$query->updateQuery($sql);

	}//End of Function


	public function updateMyPassword()
    {
		$user_id = $_SESSION['user']['userid'];
		
		$query=new Bin_Query();
		$query->updateQuery("UPDATE `user_login` 
                             SET `user_password` = '" . Bin_Security::hashPassword(trim($_POST["passwd"])) . "' 
                             WHERE `user_id` =$user_id 
                             LIMIT 1 ;");

		$query->updateQuery("UPDATE `temp_registration` 
                             SET `password` = '" . Bin_Security::hashPassword(trim($_POST["passwd"])) . "',
                             password_expire_date = DATE_ADD(CURDATE(), INTERVAL " . PASSWORD_EXPIRED_INTERVAL . " DAY)
                             WHERE `user_id` =$user_id 
                             LIMIT 1 ;");
	}


	/*----- Gets Secret Question Function Starts here -----*/
	public function getSecretQuestion(){
		$query=new Bin_Query();

 		$sql = "SELECT * FROM `labels_settings` where label_type =4";
		$query->executeQuery($sql);
		$secret_quest = $query->records;

		return $secret_quest;

	}//End of Function


	public function updateMyQuestion()
    {
		$user_id = $_SESSION['user']['userid'];

		$query=new Bin_Query();
		$query->updateQuery("UPDATE `temp_registration` 
                             SET `secret_question_id` = '".$_POST['secret_quest']."' , `secret_answer` ='".$_POST['secret_answer']."' 
                             WHERE `user_id` =$user_id 
                             LIMIT 1 ;");
	}
	
	/*----- Gets Secret Question Function Starts here -----*/
	public function getPrevBankDetails($id){
		
		$user_id = $_SESSION['user']['userid'];
		
		$query 			= new Bin_Query();
        $sql			= "SELECT b.*  FROM `organisation_bank_account_details` as b , organisation_details as org ".
						" WHERE account_id ='".$id."' && org.organisation_id = b.organisation_id && ".
						" org.user_id = '".$user_id."'  limit 1";
		$query->executeQuery($sql);
		$account 		= $query->records;
		
		if(count($account) == 0){
			header('Location: index.php?do=issuerhome');
			exit;
		}else{
			$query=new Bin_Query();
			$sql 		= "SELECT b.*,a.*, c.country_name FROM `organisation_bank_details` as b,  `address_details` as a,".
						" `country_mas` as c ".
						" WHERE b.organisation_bank_id = ".$account[0]['organisation_bank_id']." && ".
						" a.address_id = b.address_id && c.country_id=a.address_country  LIMIT 1";
			$query->executeQuery($sql);
			$profile = $query->records;
			
			$output ='';
			
			if($profile[0]['address_line_one']!=''){ 
				$output .= $profile[0]['address_line_one']."<br>";
			}
			if($profile[0]['address_line_two']!=''){ 
				$output .= $profile[0]['address_line_two']."<br>";
			}			
			if($profile[0]['address_area'] !='' && $profile[0]['address_area']!='NULL'){ 
				$output .= $profile[0]['address_area']."<br>";
			}	
			if($profile[0]['address_state']!='' || $profile[0]['address_zipcode']!='') { 
				$output .= $profile[0]['address_city']." ".$profile[0]['address_state']." ".$profile[0]['address_zipcode']."<br>";
			}			
			if($profile[0]['country_name']!=''){				
				$output .= $profile[0]['country_name']."<br>";
			}
	
			$account[0]['address'] = $output;
		}
		return $account[0];
	}//End of Function
	
	
	/*----- Gets Secret Question Function Starts here -----*/
	public function getChangesBankDetails($id){
		
		$query 					= new Bin_Query(); 
		$sql 					= "SELECT *, HOUR(TIMEDIFF(NOW(),modified)) as diff FROM `bank_account_change_request` ".
								" WHERE request_id ='".$id."' limit 1"; 
		$query->executeQuery($sql);
		$list 					= $query->records[0];
		
		if($list['diff'] > 72 || $list['status'] == 5){
			header('Location: index.php?do=issuerhome');
			exit;
		}
		
		return $list;

	}//End of Function
	
	/*----- Gets Secret Question Function Starts here -----*/
	public function updateBankRequest($id,$request,$previous){
		
		if($_POST['Authorise'] == 'Authorise'){
		
			$query 				= new Bin_Query();
			$sql 				= " UPDATE `bank_account_change_request` SET
								`status` = 4,
								`h_account_name` = '".$previous['account_name']."',
								`h_account_no` = '".$previous['account_no']."',
								`h_sort_code` = '".$previous['sort_code']."',
								`h_iban_code` = '".$previous['iban_code']."',
								`h_swift_code` = '".$previous['swift_code']."',
								`modified` = NOW() WHERE `request_id` =1 LIMIT 1;";
			$query->updateQuery($sql);	
			
			$query 				= new Bin_Query();
			$sql 				= " UPDATE `organisation_bank_account_details` SET
								`account_name` = '".$request['account_name']."',
								`account_no` = '".$request['account_no']."',
								`sort_code` = '".$request['sort_code']."',
								`iban_code` = '".$request['iban_code']."',
								`swift_code` = '".$request['swift_code']."' 
								 WHERE `account_id` = '".$previous['account_id']."' LIMIT 1;";
			$query->updateQuery($sql);
			
		}elseif($_POST['Cancel'] == 'Cancel'){
			
			$query 				= new Bin_Query();
			$sql 				= " UPDATE `bank_account_change_request` SET
								`status` = 5,
								`log` = 1 WHERE `request_id` =1 LIMIT 1;";
			$query->updateQuery($sql);	
			
			$query 				= new Bin_Query();
			$sql 				= " UPDATE `organisation_bank_account_details` SET
								`account_name` = '".$request['h_account_name']."',
								`account_no` = '".$request['h_account_no']."',
								`sort_code` = '".$request['h_sort_code']."',
								`iban_code` = '".$request['h_iban_code']."',
								`swift_code` = '".$request['h_swift_code']."' 
								 WHERE `account_id` = '".$previous['account_id']."' LIMIT 1;";	
			$query->updateQuery($sql);	
		}

	}//End of Function
	
	

	/*----- Gets One State's Information Function Starts here -----*/
	public function getState($id){
		if($id !='' && is_Numeric($id)){
			$where = "where `state_id` = '$id' limit 1";
		}
		$query=new Bin_Query();
 		$sql = "SELECT * FROM `state_master` $where";
		$query->executeQuery($sql);
		$state = $query->records;

		return $state[0];

	}//End of Function


	//Gets All Nace Categtories Info
	public function getNace($id=''){

		$where ='';
		if($id !='' && is_numeric($id)){ $where = " where nace_id ='".$id."'";  }

		$query=new Bin_Query();
		$sql = "SELECT  nace_id, nace_title FROM `categories` $where order by nace_title asc";
		$query->executeQuery($sql);
		$naced = $query->records;

		return $naced;

	}//End of Function


	//Gets All Nace Categfory Group INfo
	public function getNaced($id=''){

		$where ='';
		if($id !='' && is_numeric($id)){ $where = " where nace_group_id ='".$id."'";  }

		$query=new Bin_Query();
	 	$sql = "SELECT nace_group_id,  nace_group_title FROM `category_group` $where order by   	nace_group_title asc";
		$query->executeQuery($sql);
		$nace = $query->records;

		return $nace;
	}//End of Function



	function validateTraderCompose()
	{
		$date=date('Y-m-d h:i:s');
		$user_id = $_SESSION['user']['userid'];
		$sql="SELECT address_id FROM address_details WHERE address_email='".$_POST["to_email"]."'";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$addr_id=$query->records[0]['address_id'];

		$sql1="SELECT user_id FROM temp_registration WHERE organization_address_id='".$addr_id."'";
		$query1 = new Bin_Query();
		$query1->executeQuery($sql1);
		$to_user_id=$query1->records[0]['user_id'];	
		$query2 = new Bin_Query();
		$sql2="INSERT INTO messages (message_from,message_to,message_title,message,message_created_date,message_flag)VALUES('".$user_id."','".$to_user_id."','".$_POST['subject']."','".$_POST['message']."','".$date."','1')";
		if($query2->updateQuery($sql2))
		{
			$_SESSION['message']='Message sent successfully';	
		}
		header('Location:?do=tradercompose');

	}


	function showTraderInbox()
	{
		$user_id = $_SESSION['user']['userid'];
		$sql="SELECT * FROM messages WHERE message_to='".$user_id."' AND message_flag!='3' Order By message_id DESC";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$records=$query->records;
		return Display_DTradeUser::showTraderInbox($records);
	}



	function ViewTraderMessage()
	{
		$user_id = $_SESSION['user']['userid'];
		$sql2="UPDATE messages  SET message_flag='2' WHERE message_id='".intval($_GET['mid'])."'";
		$query2 = new Bin_Query();
		$query2->updateQuery($sql2);

		$sql="SELECT * FROM messages WHERE message_id='".intval($_GET['mid'])."'";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$records=$query->records;

		$query1=new Bin_Query();
		$sql1="SELECT first_name FROM temp_registration WHERE user_id='".$records[0]['message_from']."'";
		$query1->executeQuery($sql1);
		$fname=$query1->records[0]['first_name'];
		$res=array(0=>$records[0]['message_title'],1=>$fname,2=>$records[0]['message'],3=>$records[0]['message_id']);
		return $res;
	}



	function showTraderInboxDelete()
	{
		$date=date('Y-m-d h:i:s');
		$user_id = $_SESSION['user']['userid'];
		
		if(isset($_POST['delete']))
		{
			if($_GET['mid']!='')
			{
				$_POST['checkbox']=array(0=>$_GET['mid']);
			}
			$count = count($_POST['checkbox']);			
			$obj=new Bin_Query();
			if($count > 0)
			{			
				foreach($_POST['checkbox'] as $key=>$value)
				{
					 $sql1="DELETE FROM  messages  WHERE  message_id='".$value."' ";
				
					if($obj->updateQuery($sql1))
					{
						$_SESSION['message']='Message Deleted Sucessfully';
						header('Location:?do=traderinbox');
					}					
					else
					{
						$_SESSION['message']='Please select the Message(s) to be Deleted';
						header('Location:?do=traderinbox');
					}	
				}
			}
			else
			{
				$_SESSION['message']='Select Any One Message For Deletion';
				header('Location:?do=traderinbox');
			}
		}


	}



	function traderMsgReply()
	{
		$user_id = $_SESSION['user']['userid'];

		$sql="SELECT * FROM messages WHERE message_id='".intval($_GET['mid'])."'";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$records=$query->records;

		$query1=new Bin_Query();
		$sql1="SELECT first_name FROM temp_registration WHERE user_id='".$records[0]['message_to']."'";
		$query1->executeQuery($sql1);
		$fname=$query1->records[0]['first_name'];
		$res=array(0=>$records[0]['message_title'],1=>$fname,3=>$records[0]['message_id'],4=>$records[0]['message'],5=>$records[0]['message_created_date']);
		return $res;
	}



	function insertTraderReply()
	{
		$date=date('Y-m-d h:i:s');
		$user_id = $_SESSION['user']['userid'];

		$sql3="SELECT * FROM messages WHERE message_id='".intval($_GET['mid'])."'";
		$query3 = new Bin_Query();
		$query3->executeQuery($sql3);
		$records1=$query3->records;

		$query2 = new Bin_Query();
		$sql2="INSERT INTO messages (message_from,message_to,message_title,message,message_created_date,message_flag)VALUES('".$records1[0]['message_to']."','".$records1[0]['message_from']."','".$records1[0]['message_title']."','".$_POST['message']."','".$date."','1')";
		if($query2->updateQuery($sql2))
		{
			$_SESSION['message']='Message sent successfully';	
		}
		header('Location:?do=viewtradermessage&mid='.$_GET['mid']);

	}


	function traderSent()
	{
		$user_id = $_SESSION['user']['userid'];
		$sql="SELECT * FROM messages WHERE message_from='".$user_id."' AND message_flag!='3' Order By message_id DESC";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$records=$query->records;
		return Display_DTradeUser::traderSent($records);
	}


	function ViewTraderSent()
	{
		$user_id = $_SESSION['user']['userid'];
		$sql="SELECT * FROM messages WHERE message_id='".intval($_GET['mid'])."'";
		$query = new Bin_Query();
		$query->executeQuery($sql);
		$records=$query->records;

		$query1=new Bin_Query();
		$sql1="SELECT first_name FROM temp_registration WHERE user_id='".$records[0]['message_to']."'";
		$query1->executeQuery($sql1);
		$fname=$query1->records[0]['first_name'];
		$res=array(0=>$records[0]['message_title'],1=>$fname,2=>$records[0]['message'],3=>$records[0]['message_id']);
		return $res;
	}
	
	
	public function getRevMyDraftListing($flg)
    {
		$user_id 	= $_SESSION['user']['userid'];
		$query		= new Bin_Query();
		if($flg=='1')
        {
			$sql 		= "SELECT * ,".
					" DATE_FORMAT(created_at,'%d/%m/%y') as created FROM invoice_master ".
					" WHERE user_id='".$_SESSION['user']['userid']."' AND revolving_draft='1' ";
		}
        else
        {
			$sql 		= "SELECT * ,".
					" DATE_FORMAT(created_at,'%d/%m/%y') as created FROM invoice_master ".
					" WHERE user_id='".$_SESSION['user']['userid']."' AND draft='1' ";
		}
		$query->executeQuery($sql);
		$draft 		= $query->records;
		
		for($i=0;$i<count($draft);$i++)
		{
			
			$query=new Bin_Query();
			$sql = "SELECT * FROM debtors_detail  where debtor_id = ".$draft[$i]['debtor_id']." limit 1";
			$query->executeQuery($sql);
			$debtor = $query->records;
			
			$draft[$i]['debtor_name'] = $debtor[0]['debtor_name'];
            $draft[$i]['trade_name'] = $debtor[0]['trade_name'];
			$draft[$i]['type'] = $debtor[0]['type'];
		}
		
		return $draft;

	}//End of Get MyDraft Listing
	
	function updateRevolvingTrade($link='revolvingtrade')
	{
        Bin_Config::requireAdminModel('MDebtor', 'MRsa', 'MOriginator', 'MActivityLogs', 'MInvoiceHistory');

        $query=new Bin_Query();
        $user_id		 	= $_SESSION['user']['userid'];
		$invoice_id			= $_REQUEST['id'];
        $query->executeQuery("SELECT * FROM `invoice_master` WHERE user_id=" . $user_id . " &&  invoice_id ='" . $invoice_id . "' LIMIT 1 ");
        $trade = $query->records[0];
        $isRejected = $trade['log_status'] == 2;
		
		$invoice_id			= $_POST['debtor_id'];

        if ($link=='revolvingtrade')
        {
		    $query->executeQuery("SELECT * 
                                  FROM `invoice_master`
                                  WHERE user_id=".$user_id." &&  invoice_id ='".$invoice_id."'  
                                  LIMIT 1 ");
        }
        else
        {
            $query->executeQuery('SELECT debtor_relation.debtor_id,nace_id, nace_group_id,1 as buy_out, "" as description, 0 as min_advance,0 as max_thirty_day_reserve, 0 as buy_min_advance,0 as buy_max_thirty_day_reserve, 0 as sales_type, 0 as closing_type
                                  FROM debtor_relation
                                  LEFT JOIN debtors_detail ON debtors_detail.debtor_id  = debtor_relation.debtor_id
                                  WHERE debtor_relation.debtor_id="'.$invoice_id.'" AND trader_id='.$user_id);
        }
		$trade 			= $query->records[0];
	
		if(count($trade) == 0)
        {
			header('Location: index.php?do='.$link);
		}

		//Getting Debtor Details
		$query				= new Bin_Query();
        $query->executeQuery("SELECT dd.debtor_id,
                                dd.currency_id,
                                dd.debtor_name,
                                dd.contact_address_id,
                                dd.address_id,
                                dd.debtor_contact_first_name,
                                dd.debtor_contact_last_name,
                                dd.`type`,
                                dd.`etr_type`,
                                dd.`override_180_day_rule`,
                                IFNULL(dd.ldc_premium, IF(dd.type = 'debtor', od.ldc_premium, od.creditor_ldc_premium)) as ldc_premium,
                                IFNULL(dd.agent_commission, IF(dd.type = 'debtor', od.agent_commission, od.creditor_agent_commission)) as agent_commission,
                                IF(dd.type = 'debtor', IF(od.credebt_facility_type = 'fixed', IFNULL(dd.face_value_charge, od.face_value_charge), 0), IF(dd.face_value_charge > 0, dd.face_value_charge, IF(od.creditor_face_value_charge > 0, od.creditor_face_value_charge, 0))) as face_value_charge,
                                IF(dd.type = 'debtor' AND od.credebt_facility_type = 'fixed', 1, IF(dd.type = 'creditor' AND (dd.face_value_charge > 0 OR od.creditor_face_value_charge > 0), 1, 0)) as face_value_charge_applied,
                                od.organisation_id
                              FROM `debtors_detail` dd
                              LEFT JOIN debtor_relation dr ON dd.debtor_id = dr.debtor_id
                              LEFT JOIN organisation_details od ON od.user_id = dr.trader_id
                              where  dd.debtor_id='".$trade['debtor_id']."' 
                              limit 1");
		$debtor 			= $query->records;
		
		if(count($debtor) 	== 0)
        {
			header('Location: index.php?do='.$link);
		}

        $orpaId = !empty($_POST['orpa_id']) ? $_POST['orpa_id'] : null;
        $rerouted = ($debtor[0]['type'] === TYPE_DEBTOR and $orpaId) ? 1 : 0;

        if ($link == 'revolvingtrade') {
            $rsaModel = new Model_MRsa();
            $trade = $rsaModel->getRsaForDebtor($_SESSION['user']['userid'], $debtor[0]['debtor_id'], $orpaId);

            if (empty($trade)) {
                header('Location: index.php?do=' . $link);
                return FALSE;
            }
            $invoice_id = $trade['invoice_id'];
        }

        
        if ($debtor[0]['type']=='debtor')
        {
            $_POST['payment_discount']=0;
        }
        else
        {
            $_POST['payment']=0;
        }
        
		//imploding the date's
		$ac_date 			= date("Y-m-d");
		$ex_date= $_POST['ex_year']."-".$_POST['ex_month']."-".$_POST['ex_date'];
		$invoice_date= $_POST['invoice_year']."-".$_POST['invoice_month']."-".$_POST['invoice_date'];
		$tr_date= date("Y-m-d H:i:s");

		//Buyout Setting
		$buyout = $trade['buy_out'];

        $query->executeQuery('SELECT * FROM organisation_details WHERE user_id = '.$_SESSION['user']['userid']);
        $organisation_details = $query->records[0];

		$min_advance				=$trade['min_advance'];
		$buy_min_advance			=$trade['buy_min_advance'];
        $max_thirty_day_reserve = ($debtor[0]['type'] == 'debtor') ? $trade['max_thirty_day_reserve'] : $organisation_details['credit_agreed_rate'];
        $buy_max_thirty_day_reserve = ($debtor[0]['type'] == 'debtor') ? $trade['buy_max_thirty_day_reserve'] : $organisation_details['credit_agreed_rate'];

		$sales_type			= $trade['sales_type'];
		$result11 			= '';
		$result1 			= '';
		
		$po					= $_REQUEST['po'];
        if ($debtor[0]['type'] === TYPE_DEBTOR and $orpaId and !empty($_POST['po_no'])) {
            $modelUserOrpa = new Model_MUserOrpa();
            $poModel = $modelUserOrpa->getPoById($_POST['po_no']);
            $po = $poModel['po_no'];
        }
		// $debtor_id			= $trade['debtor_id'];
		$debtor_id			= $trade['debtor_id'];
		$nace_id			= $trade['nace_id'];
		$nace_group_id		= $trade['nace_group_id'];
		$desc				= $trade['description'];
		
        if(isset($_POST['save']))
        {
			$revolving_draft=$draft=1;
		}
        else
        {
			$revolving_draft=$draft= 0;
		}
		$closing			= $trade['closing_type'];
		$face_value 		= $_POST['face_value'];
		

		//Update Data's Into Invoice Master

		$query 		= new Bin_Query();
		$sql 		= "SELECT org.organisation_id,org.organisation_reference_id FROM organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' LIMIT 1";
		$query->executeQuery($sql);
		$org = $query->records[0];
		
		$facevalue 		= $_REQUEST['face_value'];

        $query->executeQuery("SELECT * FROM invoice_master WHERE invoice_id = " . (int)$_REQUEST['id']);
        $currentInvoice = $query->records[0];

		$sql= "UPDATE invoice_master SET po_id='".addslashes($po)."',".
				"invoice_no='".trim($_POST['invoice_no'])."', ".
				"root_invoice_id='".$invoice_id."', ".
				"debtor_id='".$debtor_id."', ".
				"user_id='".$user_id."', ".
				"face_value='".$facevalue."', ".
				"revolving='0', ".
				"buy_out='".$buyout."', ".
				"description='".$desc."', ".
				"payment_terms='".$_POST['payment']."', ".
				"actual_date='".$invoice_date."', ".
				"approved_date='".$invoice_date."', ".
				"expected_date='".$ex_date."', ".
				"trading_close_date='".$tr_date."', ".
				"min_advance='".$min_advance."', ".
				"max_thirty_day_reserve='".$max_thirty_day_reserve."', ".
				"buy_min_advance='".$buy_min_advance."', ".
				"buy_max_thirty_day_reserve='".$buy_max_thirty_day_reserve."', ".
				"debx='".$_POST['debx']."', ".
				"invoice_status='1', ".
				"invoice_authorise='0', ".
				"modified_at='".date('Y-m-d H:i:s')."', ".
				"modified_by='".$user_id."', ".
				"sales_type='".$sales_type."', ".
				"draft='".$draft."', ".
				"revolving_draft='".$revolving_draft."', ".
				"closing_type='".$closing."', ".
				" log_status = 0, ".
				" logapprove_date='0000-00-00 00:00:00', ".
				" rejected_date='0000-00-00 00:00:00',
                  payment_discount='".$_POST['payment_discount']."',
                  orpa_id = '" . $orpaId . "',
                  rerouted = '" . $rerouted . "',
                  vat_included = '" . (empty($_POST['vat_included']) ? 0 : 1) . "',
                  unscheduled_cetr = '" . (empty($_POST['unscheduled_cetr']) ? 0 : 1) . "',
                  `is_synced` = '0',
                  `etr_type` = '" . ($debtor[0]['type'] === TYPE_DEBTOR ? ETR_TYPE_D : $debtor[0]['etr_type']) . "',
                  `face_value_charge` = '".$debtor[0]['face_value_charge']."',
                  `face_value_charge_applied` = '".$debtor[0]['face_value_charge_applied']."',
                  `ldc_premium` = '".$debtor[0]['ldc_premium']."',
                  `agent_commission` = '".$debtor[0]['agent_commission']."',
                  `purchase_price_percent` = " . self::getPurchasePricePercentForInvoice($debtor[0]['organisation_id'], $debtor_id, $orpaId) . "
                  WHERE invoice_id='".$_REQUEST['id']."' ";
		$query				= new Bin_Query();
		$query->updateQuery($sql);
		// $reg_id 			= $query->insertid;
		$reg_id 			= $_REQUEST['id'];

        $activityLogs = new Model_MActivityLogs();
        if (round($currentInvoice['ldc_premium'], 3) != round($debtor[0]['ldc_premium'], 3)) {
            $activityLogs->activityLogs(
                'UPDATE_INVOICE_LDC_PREMIUM',
                'originator',
                array(
                    'element_id' => (int)$reg_id,
                    'old_value' => array_get($debtor[0], 'ldc_premium'),
                )
            );
        }
        if (round($currentInvoice['agent_commission'], 3) != round($debtor[0]['agent_commission'], 3)) {
            $activityLogs->activityLogs(
                'UPDATE_INVOICE_AGENT_COMMISSION',
                'originator',
                array(
                    'element_id' => (int)$reg_id,
                    'old_value' => array_get($debtor[0], 'agent_commission'),
                )
            );
        }
        
		$query=new Bin_Query();
		$temp_sql = "SELECT * FROM `invoice_master` where   invoice_id=".$reg_id." 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	= $temp_reg[0]['min_advance'];
		$max_thirty_day_reserve = $temp_reg[0]['max_thirty_day_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 = $temp_reg[0]['invoice_id'];
		$actual_date = $temp_reg[0]['actual_date'];
		
		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'];	
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['min_advance'] 			= $buy_min_advance;
				$ann_yield 								= Model_MHelpers::outrightYield($tradeValues);
			}
				
		}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);
			$discount									= $max_thirty_day_reserve;
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['max_thirty_day_reserve'] 		= $buy_max_thirty_day_reserve;
				$ann_yield 									= Model_MHelpers::managedYield($tradeValues);
			}	
			
		}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;
			
			if($temp_reg[0]['buy_out']=="1")
			{
				$result1 = $face_value - 7;
			
				$result11 = $result1;
				
				$tradeValues['max_thirty_day_reserve'] 		= $buy_max_thirty_day_reserve;
				$ann_yield 									= Model_MHelpers::performanceYield($tradeValues);
			}	
							
		}
 
		$history_sql		= "UPDATE `invoice_master` SET `yield` = '".$yield."', `buy_yield` = '".$ann_yield."',".
							" `return` = '".$result1."', `buy_return` = '".$result11."',`discount_rate` = '".$discount."' ,".
							" bid_yield =0 , bid_return =0 WHERE `invoice_id` ='".$reg_id."' LIMIT 1";
		$query				= new Bin_Query();
		$query->updateQuery($history_sql);
		
		$dateString			= date("Ymd");
		$leadingDigits		= "00000";
		$trade_reference_id	= $dateString.$leadingDigits.$reg_id;

		$sql				= "update `invoice_master` set ".
							" trade_reference_id=(CONCAT(DATE_FORMAT(created_at,'%y%m%d'), '000000') + invoice_id)".
							" where invoice_id='".$reg_id."'";
 		$query				= new Bin_Query();
 	 	$query->updateQuery($sql);

//		//Uploading all the Needed Documents for the Invoice
//		$uploadfile 		= array('file_invoice','file_support','file_po');
//		foreach($uploadfile as $key)
//        {
//
//			//Upload PDF FIle
//			$file 			= $key;
//
//			if($file=='file_invoice'){
//				$upload_file = 'invoicefile';
//			}elseif($file=='file_po'){
//				$upload_file = 'pofile';
//			}elseif($file=='file_support'){
//				$upload_file = 'supportfile';
//			}
//
//
//				if(isset($_SESSION[$upload_file])){
//
//					$filepath[$key] = $_SESSION[$upload_file];
//				}else{
//
//					if($_FILES[$key]['tmp_name'] !=''){
//
//						$user_id	= $_SESSION['user']['userid'];
//						$exp 		= explode('_',$key);
//						$name 		= $user_id;
//						$ref_id 	= $org['organisation_reference_id'];
//						$dir 		= "../documents/debtor/".$name; //Creating Folder W.r.t Debtor Name and Trader Id
//
//
//						if(!is_dir($dir)){
//							mkdir($dir, 0777);//Folder Path assigning
//						}
//
//						$type 		= $_FILES[$file]['type'];
//
//						chmod($dir, 0777);  //Folder Permission assigning
//
//
//						if(!is_dir('../documents/debtor/'.$name."/".date('Y'))){
//							mkdir('../documents/debtor/'.$name."/".date('Y'), 0777);
//						}
//
//						if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'))){
//							mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m'), 0777);
//						}
//
//						if(!is_dir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'))){
//							mkdir('../documents/debtor/'.$name."/".date('Y').'/'.date('m').'/'.date('d'), 0777);
//						}
//
//						$file_date_dir = date('Y').'/'.date('m').'/'.date('d');
//
//						//File Path assigning
//						$path 		= pathinfo($_FILES[$file]["name"]);
//						$file_name 	= $ref_id.'_'.$key."_".time().".".$path['extension'];
//						$dir_path 	= $dir."/".$file_date_dir."/".$file_name;
//
//						$ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);
//
//						//Uploading File
//						if(!empty($_FILES[$file]["tmp_name"])){
//
//							move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
//							chmod($dir."/".$file_date_dir."/".$file_name, 0777); //File Permission assigning
//
//						}
//
//
//						if($file_name!='')
//						$filepath[$key] 	= "/documents/debtor/".$name."/".$file_date_dir."/".$file_name;
//
//					}
//				}
//
//
//			}

        $ta = new Trade_actions();
        $ta->updateInvoiceFilesInStorage($reg_id,$_SESSION['user']['userid'],$_SESSION['user']['org_ref_id'],true,$debtor[0]['type']);

//		if($filepath['file_invoice'] !=''){
//
//			$_POST['invoicefile'] =  $filepath['file_invoice'];
//
//		}elseif($_POST['invoicefile'] !='' && $_POST['invoiceflag']=='1'){
//
//			$_POST['invoicefile'] = '/documents/debtor/'.$_POST['invoicefile'];
//		}
//
//		if($filepath['file_support'] !=''){
//
//			$_POST['supportfile'] =  $filepath['file_support'];
//
//		}elseif($_POST['supportfile'] !=''){
//
//			$_POST['supportfile'] ='/documents/debtor/'.$_POST['supportfile'];
//		}
//
//		if($filepath['file_po'] !=''){
//
//			$_POST['pofile'] =  $filepath['file_po'];
//
//		}elseif($_POST['pofile'] !='' && $_POST['poflag']=='1'){
//
//			$_POST['pofile'] = '/documents/debtor/'.$_POST['pofile'];
//		}

//		//Updating Data's Into Invoice Documents
//		$query				= new Bin_Query();
//
//		$sql1 				= "UPDATE invoice_documents SET ".
//							" invoice_document_path='".$_POST['invoicefile']."',".
//							" invoice_support_document_path='".$_POST['supportfile']."', ".
//							" purchase_order_document_path='".$_POST['pofile']."', ".
//							" modified_at='".date('Y-m-d H:i:s')."', ".
//							" modified_at='".$user_id."' ".
//							" WHERE invoice_id='".$_REQUEST['id']."' ";
// 		$query->updateQuery($sql1);

        $requestedDocuments = Model_MOriginator::getRequestedDocuments($_SESSION['org_id']);
        $requestedDocumentNames = array();
        foreach ($requestedDocuments as $requestedDocument) {
            $requestedDocumentNames[$requestedDocument['id']] = $requestedDocument['name'];
        }
        if (isset($_REQUEST['requested_document'])) {
            $documents = $_REQUEST['requested_document'];
            //Reorganize multiple uploaded files
            foreach ($_FILES['requested_document'] as $key => $files) {
                foreach ($files as $filesDetailKey => $filesDetailValues) {
                    foreach ($filesDetailValues as $fileId => $filedsValue) {
                        $documents[$filesDetailKey][$fileId][$key] = $filedsValue;
                    }
                }
            }
            foreach ($documents as $key => $requestedDocument) {
                if (empty($requestedDocument['id'])) {
                    $documentId = Model_MDebtor::requestPostTradeDocument($_REQUEST['id'],
                        $requestedDocumentNames[$key], new DateTime(), false);
                } else {
                    $documentId = $requestedDocument['id'];
                }
                $document = Model_MDebtor::getUnapprovedInvoiceDocument($_REQUEST['id'], $documentId);
                if ($document) {
                    Model_MDebtor::updatePostTradeDocument(
                        $documentId,
                        $requestedDocumentNames[$key],
                        new DateTime(),
                        $requestedDocument['amount']
                    );
                    if ($requestedDocument['file']['error'] == 0) {
                        Model_MDebtor::addPostTradeDocument($documentId, $requestedDocument['file']);
                    }
                }
            }
        }

 		$query 			= new Bin_Query();
 		$sql 			= "SELECT reject_id FROM invoice_reject_log WHERE invoice_id='".$_REQUEST['id']."' ORDER BY reject_id DESC LIMIT 1 ";
 		$query->executeQuery($sql);
 		$reject_id 		= $query->records[0]['reject_id'];


 		if($reject_id!='' && $_POST['save']!='Save')
 		{
 			$query 			= new Bin_Query();
 			$sql 			= "INSERT INTO invoice_rejected (reject_id,po_id,invoice_no,root_invoice_id,debtor_id,user_id,face_value,revolving,buy_out,description,payment_terms,actual_date,approved_date,expected_date,trading_close_date,min_advance,max_thirty_day_reserve,buy_min_advance,buy_max_thirty_day_reserve,debx,sales_type,invoice_document_path,created_at) VALUES ('".$reject_id."','".addslashes($po)."','".$_POST['invoice_no']."','".$invoice_id."','".$debtor_id."','".$user_id."','".$facevalue."','0','".$buyout."','".$desc."','".$_POST['payment']."','".$invoice_date."','".$invoice_date."','".$ex_date."','".$tr_date."','".$min_advance."','".$max_thirty_day_reserve."','".$buy_min_advance."','".$buy_max_thirty_day_reserve."','".$_POST['debx']."','".$sales_type."','".$_POST['invoicefile']."',NOW()) ";
 			$query->updateQuery($sql);
 		}

		$query				= new Bin_Query();
		$sql 				= "SELECT address_email FROM address_details where ".
							" address_id = '".$debtor[0]['contact_address_id']."'  limit 1";
		$query->executeQuery($sql);
		$debtorAddress 		= $query->records;
		
		
		if($_REQUEST['save'] == 'Save')
        {
			$action='saved';
		}
        else
        {
            $action='submited';
			$query=new Bin_Query();
			$temp_sql 			= "SELECT * FROM `invoice_closed` where invoice_id ='".$trade['invoice_id']."'  LIMIT 1 ";
			$query->executeQuery($temp_sql);
			$closed 			= $query->records[0];

			$qry 		= new Bin_Query();
			$sql 		= "SELECT user_type FROM user_login WHERE user_id='".$closed['won_by']."' LIMIT 1";
			$qry->executeQuery($sql);
			$investor 	= $qry->records[0]['user_type'];
			

			if($investor=='2')
            {
				$query=new Bin_Query();
				$temp_sql 			= "SELECT * FROM `invoice_bidding` where invoice_bidding_id  ='".$closed['invoice_bidding_id']."'  LIMIT 1 ";
				$query->executeQuery($temp_sql);
				$bid 				= $query->records[0];
		
				$qry 		= new Bin_Query();
				$sql 		= "SELECT * FROM invoice_bidding WHERE invoice_id='".$reg_id."' && user_id='".$closed['won_by']."' " ;
				$qry->executeQuery($sql);
				$invoice_bidding = $qry->records[0]['invoice_bidding_id'];
				
				if($trade['sales_type'] == 1)
                {
					$sql1 				= "UPDATE invoice_bidding SET user_id='".$closed['won_by']."',min_advance='".$closed['min_advance']."',max_thirty_reserve='0',buy_out='".$bid['buy_out']."',auto_bid='2',bid_time=NOW() WHERE invoice_id='".$reg_id."' ";
				}
                else
                {
					$sql1 				= "UPDATE invoice_bidding SET user_id='".$closed['won_by']."',min_advance='0',max_thirty_reserve='".$closed['max_thirty_reserve']."',buy_out='".$bid['buy_out']."',auto_bid='2',bid_time=NOW() WHERE invoice_id='".$reg_id."' ";
				}
				
				$query				= new Bin_Query();
				$query->updateQuery($sql1);
		
				$query				= new Bin_Query();
				$closed_sql 				= "UPDATE invoice_closed SET won_by='".$closed['won_by']."',min_advance='".$closed['min_advance']."',max_thirty_reserve='".$closed['max_thirty_reserve']."',invoice_bidding_id='".$invoice_bidding."',payment_status='0',close_time=NOW() WHERE invoice_id='".$reg_id."' ";
				
				$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` =".$reg_id." LIMIT 1 ;";
				$query->executeQuery($invoice_sql);
				$invoice = $query->records;

				
				// Insert Bidding History
				$query=new Bin_Query();
				$existingBid_sql = "SELECT * FROM `invoice_bidding` WHERE `invoice_bidding_id` = ".$invoice_bidding." limit 1";
				$query->executeQuery($existingBid_sql);
				$existingBid = $query->records;
				if(count($existingBid) > 0)
                {
					$query				= new Bin_Query();
					$sql 				= "SELECT m.* FROM  `invoice_master` as m WHERE  m.invoice_id = '".$reg_id."' limit 1";
					
					$query->executeQuery($sql);
					$trade				= $query->records[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 				= $trade['sales_type'];
					$debx 						= $trade['debx'];
					$face_value 				= $trade['face_value'];
					$min_advance				= $existingBid[0]['min_advance'];
					$max_thirty_day_reserve 	= $existingBid[0]['max_thirty_reserve'];
					$ex_date 					= $trade['expected_date'];
					$tr_date 					= $trade['trading_close_date'];
					$buy_min_advance 			= $trade['buy_min_advance'];
					$buy_max_thirty_day_reserve = $trade['buy_max_thirty_day_reserve'];
					$reg_id						= $existingBid[0]['invoice_id'];
					$actual_date 				= $trade['actual_date'];
					$reg_id 					= $trade['invoice_id'];
		
		
					
					if($sales_type =="1"){
						
						$result1 									= $face_value - 7;
						if($debx == "1")
							$result1 								= $result1	- 50; 
						
						$value 										= $min_advance;
						$tradeValues 								= $trade;
		
						$tradeValues['min_advance'] 				= $value;
						$yield 										= Model_MHelpers::outrightYield($tradeValues);
						
						$trade['yield']								= $yield;
						$trade['min_advance']						= $min_advance;
						$trade['max_thirty_day_reserve']			= $max_thirty_day_reserve;
						$returnCalc 								= Model_MHelpers::outrightDiscountCalc($trade);
						$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 								= $trade;
						$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
						$yield 										= Model_MHelpers::managedYield($tradeValues);
						$discount									= $max_thirty_day_reserve;
						
					}else{
						
		
						$result1 									= $face_value - 7;
						$rebate_refund								= parent::getSiteSettings('rebate_refund');
						$value 										= $max_thirty_day_reserve;
						$tradeValues 								= $trade;
						$tradeValues['max_thirty_day_reserve'] 		= $max_thirty_day_reserve;
						$yield 										= Model_MHelpers::performanceYield($tradeValues);
						$discount									= $max_thirty_day_reserve;
										
					}
		
						
				//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 ($debtor[0]['type']=='debtor')
            {
                Model_MTradeFloor::sendStampedInvoice($reg_id, 0, true);
                if (!$isRejected) {
                    Model_MDebtor::requestPostTradeDocuments($_REQUEST['id']);
                }
            }
		}
		
        $query->executeQuery('SELECT noa_link, etr_link, invoice_document_path, purchase_order_document_path,is_auto_send
                              FROM invoice_master
                              LEFT JOIN invoice_documents ON invoice_documents.invoice_id = invoice_master.invoice_id
                              WHERE invoice_master.invoice_id='.$reg_id);
        $invoice=$query->records[0];
        
        $query->executeQuery('SELECT etr_pod_mandatory
                              FROM organisation_details
                              WHERE user_id='.$_SESSION['user']['userid']);
        
        $organisation_details=$query->records[0];
        
        if ((!$invoice['noa_link'] AND $debtor[0]['type']=='debtor') OR (!$invoice['etr_link'] AND $debtor[0]['type']=='debtor') OR !$invoice['invoice_document_path'] OR (!$invoice['purchase_order_document_path'] AND $organisation_details['etr_pod_mandatory']=='1'))
        {
            $query->updateQuery('UPDATE invoice_master SET 
                                    revolving_draft=1,
                                    draft=1
                                 WHERE invoice_id='.$reg_id);
            
            $_SESSION['error_message']='Revolving ETR was not '.$action.' as PDF files were not processed';
            
            header('Location: index.php?do='.$link);
            exit();   
        }
        MInvoiceHistory::addHistoryRecord($reg_id, MInvoiceHistory::INVOICE_HISTORY_ACTION_SUBMIT, MInvoiceHistory::INVOICE_HISTORY_TYPE_ORIGINATOR);
        
		if($reg_id) return true; else false;
	}
	
	function getRevolvingDraftById($id){
		
		if($_REQUEST['id'] !='' && is_numeric($_REQUEST['id'])){
			$id = $_REQUEST['id'];	
		}else{
			header('location: index.php?do=revolvingtrade');	
		}
		
		$query=new Bin_Query();
		$query->executeQuery("SELECT m.* , d.invoice_document_path,d.invoice_support_document_path,d.purchase_order_document_path, DATE_FORMAT(m.created_at,'%d/%m/%y') as created 
                              FROM invoice_master as m , invoice_documents as d 
                              WHERE m.invoice_id ='".$id."' && (m.revolving_draft='1' || m.log_status='2')  && d.invoice_id = m.invoice_id  LIMIT 1");
		$draft = $query->records;
		
		if(count($draft) == 0){
			header('location: index.php?do=revolvingtrade');	
		}
		
		return $draft;
	
	}

	function deleteTrade(){

		$qry 		= new Bin_Query();
		$sql 		= "DELETE FROM invoice_documents WHERE invoice_id='".$_REQUEST['id']."' ";
		$qry->updateQuery($sql);

		$qry 		= new Bin_Query();
		$sql 		= "DELETE FROM invoice_master WHERE invoice_id='".$_REQUEST['id']."' ";
		if($qry->updateQuery($sql)){

			$_SESSION['result'] = 'Trade has been deleted successfully';

			if(isset($_REQUEST['view'])){
				header('Location: index.php?do=revolvingtradedraft');
			}else{
				header('Location: index.php?do=mytradedraft');
			}
			exit;
		}


	}


	function updateInstalmentTrade(){
	
		if($_REQUEST['id'] !='' && is_numeric($_REQUEST['id'])){
			$id = $_REQUEST['id'];	
		}else{
			header('location: index.php?do=instalment_etr');	
		}
		
		$user_id		 	= $_SESSION['user']['userid'];

		$sales_type					= $_POST['sales_type'];
		$sales_arr					= explode("-",$sales_type);
		$sales_type					= $sales_arr[0];
		$fieldSet					= $sales_arr[1];

		//Checking the User Details		
		$query=new Bin_Query();
		$temp_sql 			= "SELECT `nace_group_id`,`nace_id` FROM `temp_registration` where user_id=".$user_id." limit 1";
		$query->executeQuery($temp_sql);
		$temp_reg 			= $query->records;
	
		if(count($temp_reg) == 0){
			header('Location: index.php?do=instalment_etr');
		}

		//Getting Debtor Details
		$query				= new Bin_Query();
		$debt_sql 			= "SELECT * FROM `debtors_detail` where debtor_id=".$_POST['debtor_id']." limit 1";
		$query->executeQuery($debt_sql);

		$debtor 			= $query->records;
		if(count($debtor) 	== 0){
			header('Location: index.php?do=instalment_etr');
		}
 

			$ac_date 			= date('Y-m-d');
			$invoice_date 		= date('Y-m-d');

			$etr_days 		= $_POST['payments_remaining'] * 30;

			$d = new DateTime();
			$d->modify($etr_days." days");
			$ex_date = $d->format("Y-m-d");

			$t = new DateTime();
			$t->modify("30 days");
			$tr_date = $t->format("Y-m-d");
		// }

		if($_POST['buyout'] =='') $buyout =2; else $buyout =$_POST['buyout'];

		$min_advance				=0;
		$buy_min_advance			=0;
		$max_thirty_day_reserve		=0;
		$buy_max_thirty_day_reserve	=0;

		
		

		if($fieldSet=="model1"){
			$min_advance					= $_POST['purchase_price'];
			if($_POST['buyout']=="1"){
				$buy_min_advance			= $_POST['buyout_price'];
			}
		}
		else if($fieldSet=="model2"){
			$max_thirty_day_reserve			= $_POST['discount_price'];
			if($_POST['buyout']=="1"){
				$buy_max_thirty_day_reserve	= $_POST['buyout_discount_price'];
			}
		}
		else if($sales_type =="4" || $sales_type =="5"){

			$max_thirty_day_reserve			= $_POST['discount_price'];

			// if($_POST['buyout']=="1"){
					$buy_max_thirty_day_reserve	= $_POST['buyout_discount_price'];
			// }

			$sales_revolving				= 1;	
			
		}


		$result11 			= '';
		$result1 			= '';
		
		$draft 				= 0;
		
		if($_POST['save']  == 'Save'){
			$draft 			= 1;	
		}
		
		$query 		= new Bin_Query();
		$sql 		= "SELECT org.organisation_id, org.purchase_price,org.agreed_rate FROM organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' LIMIT 1";
		$query->executeQuery($sql);
		$org = $query->records[0];

		$document_value = $_POST['etr_face_value'];

		$_POST['payment'] = $_POST['payments_remaining']*30;

		$purchase_discount 	= $org['purchase_price']/100;

		$sell_rate 			= $org['agreed_rate']/100;		

		$facevalue 		= ($document_value-$document_value*(1-$org['purchase_price']/100))/$_POST['no_of_instalments']*$_POST['payments_remaining'];

		$per_instalment_amt = (($document_value-($document_value*(1-$purchase_discount)))-(($document_value-($document_value*(1-$purchase_discount)))/$_POST['no_of_instalments']*($_POST['no_of_instalments']-$_POST['payments_remaining'])))*$sell_rate*pow((1+$sell_rate),$_POST['payments_remaining'])/(pow((1+$sell_rate),$_POST['payments_remaining'])-1);
						
		$sql= "UPDATE `invoice_master` SET `po_id` = '".$_POST['po']."',
							`invoice_no` = '".trim($_POST['invoice_no'])."',
							`root_invoice_id` = '0',	
							`debtor_id` = '".$_POST['debtor_id']."',	
							`face_value`='".$facevalue."',
							`document_value`='".$document_value."',
							`revolving` = '0',
							`revolving_total` = '".$_POST['etr_no']."',
							`revolving_months` = '".$_POST['etr_months']."',
							`instalment` = '1',
							`per_instalment_amt`='".$per_instalment_amt."',
							`no_of_instalments` = '".$_POST['no_of_instalments']."',
							`payments_remaining` = '".$_POST['payments_remaining']."',
							`paid_to_debtors` = '".$_POST['paid_to_debtors']."',
							`buy_out` = '".$buyout."',
							`description` = '".$_POST['desc']."',
							`payment_terms` = '".$_POST['payment']."',
							`actual_date` = '".$invoice_date."',
							`approved_date` = '".$invoice_date."',
							`expected_date` = '".$ex_date."',
							`trading_close_date` = '".$tr_date."',
							`min_advance` = '".$min_advance."',
							`max_thirty_day_reserve` = '".$max_thirty_day_reserve."',
							`buy_min_advance` = '".$buy_min_advance."',
							`buy_max_thirty_day_reserve` = '".$buy_max_thirty_day_reserve."',
							`debx` = '".$_POST['debx']."',
							`instalment_draft` = '".$draft."',
							`closing_type` = '".$_POST['closing']."',
							`modified_at` = NOW(),
							`sales_type` = '".$_POST['etr_type']."' WHERE `invoice_id` ='".$_REQUEST['id']."' LIMIT 1 ;";
						
		$_POST['face_value'] 	= $_POST['etr_face_value'];
		$sales_type 			= $_POST['etr_type'];
			
		
		
		$query				= new Bin_Query();
		$query->updateQuery($sql);
		$reg_id 			= $_REQUEST['id'];
		
		
		
		$query=new Bin_Query();
		$temp_sql = "SELECT * FROM `invoice_master` where invoice_id=".$reg_id." 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	= $temp_reg[0]['min_advance'];
		$max_thirty_day_reserve = $temp_reg[0]['max_thirty_day_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 = $temp_reg[0]['invoice_id'];
		$actual_date = $temp_reg[0]['actual_date'];
		

		$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);
		$query = new Bin_Query();
        $sql = "SELECT * FROM exchange_rate ORDER BY exchange_id DESC ";
        $query->executeQuery($sql);
        
        $yield = $query->records[0]['buyrate']/100;

		$discount									= $max_thirty_day_reserve;
		
		if($temp_reg[0]['buy_out']=="1")
		{
			$result1 = $face_value - 7;
		
			$result11 = $result1;
			
			$tradeValues['max_thirty_day_reserve'] 		= $buy_max_thirty_day_reserve;
			// $ann_yield 									= Model_MHelpers::performanceYield($tradeValues);
			$ann_yield = $yield;
		}	

		$history_sql		= "UPDATE `invoice_master` SET `yield` = '".$yield."', `buy_yield` = '".$ann_yield."',".
							" `return` = '".$result1."', `buy_return` = '".$result11."',`discount_rate` = '".$discount."' ,".
							" bid_yield =0 , bid_return =0 WHERE `invoice_id` ='".$reg_id."' LIMIT 1";
		$query				= new Bin_Query();
		$query->updateQuery($history_sql);
		
		
		
		//Uploading all the Needed Documents for the Invoice
		$uploadfile 			= array('file_invoice','file_support','file_po');
		foreach($uploadfile as $key){
		
			//Upload PDF FIle
			$file = $key;
			if($_FILES[$key]['tmp_name'] !=''){

				$exp 				= explode('_',$key);
				$name 				= $user_id;
				$dir 				= "../documents/debtor/".$name; //Creating Folder W.r.t Debtor Name and Trader Id

				if(!is_dir($dir)){
					mkdir($dir, 0777);//Folder Path assigning
				}
				
				chmod($dir, 0777);  //Folder Permission assigning

				//File Path assigning
				$path 				= pathinfo($_FILES[$file]["name"]);
				$file_name 			= $user_id.'_'.$key."_".time().".".$path['extension'];
				$dir_path 			= $dir."/".$file_name;

				//Uploading File
				if(!empty($_FILES[$file]["tmp_name"])){
					
					move_uploaded_file($_FILES[$file]["tmp_name"],$dir_path);
				}

				chmod($dir."/".$file_name, 0777); //File Permission assigning

				if($file_name!='')
				$filepath[$key] 	= "/documents/debtor/".$name."/".$file_name;

			}	
		}

		$update ='';
		
		if($filepath['file_support'] !=''){
			
			$update .= "`invoice_support_document_path` = '".$filepath['file_support']."' , ";		
			
		}elseif($_POST['supportfile'] !=''){
		
			$update .= "`invoice_support_document_path` = '/documents/debtor/".str_replace("/documents/debtor/","",$_POST['supportfile'])."' , ";
		}

		//Inserting Data's Into Invoice Documents		
		if($update !=''){
			$query						= new Bin_Query();
			$sql1						= "UPDATE `invoice_documents` SET ".
											" $update ".
											" `modified_at` = '".date('Y-m-d H:i:s')."' ".
											" WHERE `invoice_id` ='".$reg_id."' LIMIT 1 ; ";

			$query->updateQuery($sql1);
		}


		$query						= new Bin_Query();
		$sql 						= "SELECT address_email FROM address_details where ".
									" address_id = '".$debtor[0]['contact_address_id']."'  limit 1";
		$query->executeQuery($sql);
		$debtorAddress 				= $query->records;

		// send mail with pdf attachment
		if($_POST['ack_notice']	 == "1" && $debtorAddress[0]['address_email']  != "" && $draft != '1' && $notice !='3'){
			
		
		}
		
		if($reg_id) return true; else false;	
	}

	public static function submitAllEtr($agreement = true, $user_id = null, $credebtod_id = null) {

        require_once(ROOT_FOLDER.'classes/Model/MTradeApplication.php');
        require_once(ROOT_FOLDER.'classes/Model/MTradeFloor.php');
        require_once(ROOT_FOLDER.'classes/Model/MHome.php');

        $user_id = (isset($_SESSION['user']['userid']) && $user_id === null) ?
            (int)$_SESSION['user']['userid'] :
            (int)$user_id;

        $query = new Bin_Query();
        $sql = /** @lang MySQL */ "SELECT 
            organisation_id 
            FROM organisation_details 
            WHERE user_id = " . $user_id;
        $query->executeQuery($sql);
        $org_id = $query->records[0]['organisation_id'];

        $app = new Model_MTradeApplication();
        $check_directors = $app->checkDirectors($user_id, $org_id);
        $check_application = Model_MHome::checkApplicationStatus($org_id);

		if (!$agreement) {

            $check_consent_status = /** @lang MySQL */ "SELECT 
                consent_status 
                FROM user_login 
                WHERE user_id = " . $user_id;
            $query->executeQuery($check_consent_status);

            $agreement = (isset($query->records[0]['consent_status']) && (int)$query->records[0]['consent_status'] === 1);
        }

        if (!$check_directors && $check_application && $agreement) {

            $debtors = array();

            if (!is_null($credebtod_id)) {

                $debtors[] = $credebtod_id;

            } else {

                $approve_debtors_list = /** @lang MySQL */ "SELECT 
                    dd.debtor_id 
                    FROM debtor_relation as dr 
                        LEFT JOIN debtors_detail as dd ON dd.debtor_id = dr.debtor_id 
                    WHERE dr.trader_id = " . $user_id . " 
                    AND dr.status = 8";
                    $query->executeQuery($approve_debtors_list);

                foreach ($query->records as $debtor) {

                    $debtors[] = $debtor['debtor_id'];
                }
            }

            $update_sql = /** @lang MySQL */ "UPDATE invoice_master SET 
                draft = 0,
                revolving_draft = 0 
                WHERE user_id = " . $user_id . " 
                AND draft = 1 
                AND debtor_id IN (" . implode(',', $debtors) . ")";
            $query->updateQuery($update_sql);

            $select_invoice = /** @lang MySQL */ "SELECT * 
                FROM invoice_master 
                WHERE user_id = " . $user_id . " 
                AND revolving_draft = 1 
                AND debtor_id IN(" . implode(',', $debtors) . ")";
            $query->executeQuery($select_invoice);

            foreach($query->records as $etr) {

                Model_MTradeFloor::sendStampedInvoice($etr['invoice_id']);

            }
        }
    }

    public static function getNotApprovedList($userId)
    {
        $db = Bin_Db::connect();
        $selectQuery = "SELECT dd.debtor_reference_id, IF(dd.trade_name != '', dd.trade_name, dd.debtor_name) AS debtor_name, im.trade_reference_id, im.face_value,
        im.actual_date, im.expected_date, im.invoice_no, dd.debtor_id, dd.type
        FROM invoice_master im
        JOIN debtors_detail dd ON dd.debtor_id = im.debtor_id
        WHERE im.user_id = ':user_id' AND im.invoice_status < 3 AND im.log_status IN (0,1)
        AND im.draft = 0 AND im.root_invoice_id > 0";

        return $db->query($selectQuery, array(':user_id' => $userId))->getResultArray();
    }
}
?>