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/MOriginatorApplication.php
<?php
include_once('admin/classes/Model/base_actions.php');
class Model_MOriginatorApplication extends Base_actions
{
	function showTraderCurrency()
	{
		$query = new Bin_Query();

		$query->executeQuery("SELECT oc.org_currency_id, a.organisation_name, a.organisation_trade_name, oc.currency_id ,a.submitted_date,a.application_step,a.application_status,cm.currency_code,cm.currency_code, a.organisation_id,is_main
                              FROM organisation_currency oc
                              LEFT JOIN organisation_details a ON oc.organisation_id=a.organisation_id
                              LEFT JOIN currencies cm ON cm.currency_id  = oc.currency_id  
                              WHERE oc.organisation_id='".$_SESSION['org_id']."'");
		$recordSet = $query->records;
        
        $query->executeQuery('SELECT FOUND_ROWS() as totalRecord');
        $totalRecord=$query->records[0]['totalRecord'];

		return Display_DOriginatorApplication::showTraderCurrency(1,$recordSet);
	}

	function showUserDetails()
    {
        $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;
            
		$qry 		= new Bin_Query();
		$sql 		= "SELECT SQL_CALC_FOUND_ROWS * 
                       FROM `organisation_users` 
                       WHERE parent_id='".$_SESSION['user']['userid']."' 
                       LIMIT ".$start.",".$noofrec;
		$qry->executeQuery($sql);
        $recordSet = $qry->records;

		$qry->executeQuery('SELECT FOUND_ROWS() as totalRecord');
        $totalRecord=$qry->records[0]['totalRecord'];

		return Display_DOriginatorApplication::showUserDetails(ceil($totalRecord/$noofrec),$recordSet);
	}

	function viewTraderCurrency()
	{
		$query = new Bin_Query();
		$sql="SELECT * FROM organisation_details  WHERE organisation_id='".intval($_GET['aid'])."' ";
		if($query->executeQuery($sql))
		$recordSet=$query->records[0];	
		return Display_DOriginatorApplication::viewTraderCurrency($recordSet);
	}

	function editTraderCurrency()
	{

		$query = new Bin_Query();
		$sql="SELECT * , organisation_limit AS  limits, organisation_risk AS risks FROM organisation_details WHERE organisation_id='".intval($_GET['aid'])."' ";
		if($query->executeQuery($sql))
		$recordSet=$query->records[0];	
		return Display_DOriginatorApplication::editTraderCurrency($recordSet);

	}

	public function getUserDetails(){
		
		$org_id 		= $_REQUEST['id'];
		$query			= new Bin_Query();
		$sql 			= "SELECT org.* FROM `organisation_details` as org where org.organisation_id = ".$org_id."  limit 1";
		$query->executeQuery($sql);

		$user 			= $query->records;
		return $user;	
	}

	public function saveOrganisation($post){
		
		$query			= new Bin_Query();
		$sql 			= "SELECT org.* FROM `organisation_details` as org where org.organisation_id = ".$_REQUEST['id']." LIMIT 1";
		$query->executeQuery($sql);
		$user 			= $query->records[0];
		
		$query=new Bin_Query();
		
		$sql="UPDATE `organisation_details` 
			SET 
				`organisation_name` 		= '".trim($_POST['org_organisationname'])."',
				`organisation_trade_name` 	= '".trim($_POST['org_organizationtradename'])."',
				`organisation_overview` 	= '".trim($_POST['org_orgoverview'])."',
				`nace_group_id` 			= '".trim($_POST['siccat'])."',
				`nace_id` 					= '".trim($_POST['sicgp'])."',
				`parent_company_name` 		= '".trim($_POST['org_pcdetail'])."',
				`business_entity_type` 		= '".trim($_POST['org_bentitytype'])."',
				`organisation_jurisdiction` = '".trim($_POST['org_jurorg'])."',
				`formation_year` 			= '".trim($_POST['org_form_year'])."',
				`share_capital` 			= '".trim($_POST['org_share_cap'])."',
				`website` 					= '".trim($_POST['org_website'])."',
				`organisation_type` 		= '".trim($_POST['org_orgtype'])."',
				`total_employee` 			= '".trim($_POST['org_totemp'])."',
				`previous_company_name` 	= '".trim($_POST['org_prev_co'])."',
				`other_changes` 			= '".trim($_POST['org_oth_cg'])."',
				`vat_number` 				= '".trim($_POST['org_vat'])."',
				`tax_number` 				= '".trim($_POST['org_ctn'])."',
				`other_details` 			= '".trim($_POST['org_odetail'])."' 
			WHERE 
				`organisation_id` 			= '".$_REQUEST['id']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		
		$query3		=new Bin_Query();
		$sql3		= "UPDATE `temp_registration` SET `organization_name` = '".addslashes($_POST['org_organisationname'])."' ".
					" WHERE `user_id` = '".$user['user_id']."' LIMIT 1";
		$query3->updateQuery($sql3);
		
		echo "<script> window.opener.location.href = window.opener.location.href; window.close();</script>"; exit;
	}

	public function getCountry(){
 
		$query			= new Bin_Query();
		$sql 			= "SELECT country_id, country_name FROM `country_mas` order by country_name asc";
		$query->executeQuery($sql);
		$country 		= $query->records;

		return $country;
	}//End of Function
	
	function getOrgAddress(){

		$address_id		= $_REQUEST['address'];

		$query			= new Bin_Query();
 		$sql 			= "SELECT * FROM `address_details` where `address_id` ='".$address_id."' ";
		$query->executeQuery($sql);
		$address 		= $query->records;

		return $address;
		
	}

	function getOrgbankAddress(){

		$address_id					= $_REQUEST['address'];
		$organisation_bank_id		= $_REQUEST['bank'];
		
		$query 			= new Bin_Query();
        $sql			= "SELECT *  FROM `organisation_bank_details` org, `address_details` as a WHERE org.organisation_bank_id='".$organisation_bank_id."' && a.address_id = org.address_id limit 1";
		$query->executeQuery($sql);
		$bank 			= $query->records;

		return $bank;
		
	}

	function getBankContact(){

		$id				= $_REQUEST['id'];
		
		$query 			= new Bin_Query();
        $sql			= "SELECT *  FROM `contact_details` as c, `address_details` as a WHERE c.contact_id='".$id."' && a.address_id = c.work_address_id limit 1";
		$query->executeQuery($sql);
		$contact 			= $query->records;

		return $contact;
		
	}

	function getBankAccount(){

		$id				= $_REQUEST['id'];

		$query 			= new Bin_Query();
        $sql			= "SELECT *  FROM `organisation_bank_account_details` WHERE account_id ='".$id."' limit 1";
		$query->executeQuery($sql);
		$account 		= $query->records;
		
		for($i=0;$i<count($account);$i++){
			if($account[$i]['change'] == '1'){
				
				$query1 		= new Bin_Query();
				$sql1			= "SELECT * FROM `bank_account_change_request` WHERE account_id ='".$account[$i]['account_id']."' limit 1";
				$query1->executeQuery($sql1);
				$change 		= $query1->records;
				if(count($change) >0){
					$account[$i]['account_name'] 	= $change[0]['account_name'];
					$account[$i]['account_no'] 		= $change[0]['account_no'];
					$account[$i]['sort_code']		= $change[0]['sort_code'];
					$account[$i]['iban_code'] 		= $change[0]['iban_code'];
					$account[$i]['swift_code'] 		= $change[0]['swift_code'];
				}
			}
		}
		return $account;
	}


	function saveOrgAddress($post){

			$query=new Bin_Query();
			
			$sql="UPDATE `address_details` 
				SET 
					`address_line_one` 			= '".$_POST['p_orgcaddr1']."',
					`address_line_two` 			= '".$_POST['p_orgc_addr2']."',
					`address_city` 				= '".$_POST['p_orgc_city']."',
					`address_state` 			= '".$_POST['p_orgc_state']."',
					`address_country` 			= '".$_POST['p_orgc_country']."',
					`address_zipcode` 			= '".$_POST['p_orgc_pc']."',
					`address_phone_country`		= '".$_POST['p_orgc_ph_country']."',
					`address_phone_code` 		= '".$_POST['p_orgc_ph_area']."',
					`address_phone` 			= '".$_POST['p_orgc_ph_pn']."',
					`address_fax_country` 		= '".$_POST['p_orgc_fn_country']."',
					`address_fax_code` 			= '".$_POST['p_orgc_fn_area']."',
					`address_fax` 				= '".$_POST['p_orgc_fn_pn']."',
					`address_email` 			= '".$_POST['p_orgc_email']."' 
				WHERE 
					`address_id` 			=".$_REQUEST['address']." LIMIT 1 ;";

			$query->updateQuery($sql);
		
		echo "<script> window.opener.location.href = window.opener.location.href; window.close();</script>"; exit;
	}

	function saveBankAddress($post){

		
		$query=new Bin_Query();
		
		$sql="UPDATE `address_details` 
			SET 
				`address_line_one` 			= '".$_POST['bank_orgcaddr1']."',
				`address_line_two` 			= '".$_POST['bank_orgc_addr2']."',
				`address_city` 				= '".$_POST['bank_orgc_city']."',
				`address_state` 			= '".$_POST['bank_orgc_state']."',
				`address_country` 			= '".$_POST['bank_orgc_country']."',
				`address_zipcode` 			= '".$_POST['bank_orgc_pc']."',
				`address_phone_country`		= '".$_POST['bank_orgc_ph_country']."',
				`address_phone_code` 		= '".$_POST['bank_orgc_ph_area']."',
				`address_phone` 			= '".$_POST['bank_orgc_ph_pn']."',
				`address_fax_country` 		= '".$_POST['bank_orgc_fn_country']."',
				`address_fax_code` 			= '".$_POST['bank_orgc_fn_area']."',
				`address_fax` 				= '".$_POST['bank_orgc_fn_pn']."',
				`address_email` 			= '".$_POST['bank_orgc_email']."' 
			WHERE 
				`address_id` 			=".$_REQUEST['address']." LIMIT 1 ;";

		$query->updateQuery($sql);

		if($_POST['bank_name'] == 0 || !is_numeric($_POST['bank_name'])) {

			if(!is_numeric($_POST['bank_name'])){
				$new = $_POST['bank_name'];
			}else{
				$new = $_POST['bank_new'];
			}

			$query=new Bin_Query();
			$sql="INSERT INTO bank_details (bank_name,bank_country,modified_at, modified_by)VALUES('".$new."','".$_POST['bank_orgc_country']."',NOW(),'".$_SESSION['user']['userid']."')";
			$query->updateQuery($sql);

			$_POST['bank_name'] = $query->insertid;
		}
		
		$sql="UPDATE `organisation_bank_details` 
			SET 
				`bank_id` 					= '".$_POST['bank_name']."'
			WHERE 
				`organisation_bank_id` 		= '".$_REQUEST['bank']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		
		echo "<script> window.opener.location.href = window.opener.location.href; window.close();</script>"; exit;
		
	}

	function saveBankContact($post){
		
		$contact = Model_MOriginatorApplication::getBankContact();
		
		
		$query=new Bin_Query();
		
		$sql="UPDATE `address_details` 
			SET 
				`address_phone_country`		= '".$_POST['bank_c_ph_country']."',
				`address_phone_code` 		= '".$_POST['bank_c_ph_area']."',
				`address_phone` 			= '".$_POST['bank_c_ph_pn']."',
				`address_email` 			= '".$_POST['bank_c_email']."' 
			WHERE 
				`address_id` 				= ".$contact[0]['address_id']." LIMIT 1 ;";

		$query->updateQuery($sql);

		$sql="UPDATE `contact_details` 
			SET 
				`first_name` 				= '".$_POST['bank_c_fname']."',
				`last_name` 				= '".$_POST['bank_c_lname']."'
			WHERE 
				`contact_id` 				= '".$contact[0]['contact_id']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}

	function saveBankAccount(){

		$sort 			= explode("-",$_POST['sort_code']);
		$sort_code 		= $sort[0].$sort[1].$sort[2];
				
		$query 			= new Bin_Query();
		$sql			= "SELECT * FROM `bank_account_change_request` WHERE account_id ='".$_REQUEST['id']."' limit 1";
		$query->executeQuery($sql);
		$change 		= $query->records;

		if(count($change) > 0){
			

			$query	= new Bin_Query();
			$sql	= "UPDATE `bank_account_change_request` 
					SET 
						`account_name`				= '".$_POST['account_name']."',
						`account_no`				= '".$_POST['account_no']."',
						`sort_code`					= '".$sort_code."',
						`iban_code`					= '".$_POST['iban_code']."',
						`swift_code`				= '".$_POST['swift_code']."'
					WHERE 
						`account_id` 				= ".$_REQUEST['id']." LIMIT 1 ;";
	
			$query->updateQuery($sql);
			
		}else{
			$query	= new Bin_Query();
			$sql	= "INSERT INTO `bank_account_change_request` (
					`account_name`,		`account_no` ,		`sort_code` ,
					`iban_code`,		`swift_code` ,		`account_id` ,
					`status` ,				`created`
					)
					VALUES (
					'".$_POST['account_name']."', '".$_POST['account_no']."', '".$sort_code."', 
					'".$_POST['iban_code']."', '".$_POST['swift_code']."', '".$_REQUEST['id']."', 
					'1', NOW()
					);";
		
			$query->updateQuery($sql);
		}
		
		$query	= new Bin_Query();
		$sql	= "UPDATE `organisation_bank_account_details` 
				SET 
					`change`				= '1'
				WHERE 
					`account_id` 				= ".$_REQUEST['id']." LIMIT 1 ;";

		$query->updateQuery($sql);

		// Save to organisation_currencies
		$bank_account = self::getBankAccount($_REQUEST['id']);

		$sql_organisation_info = "
			SELECT `o_d`.`user_id`, `o_d`.`organisation_reference_id` as `long_id`, `b_d`.`bank_country`, `o_b_d`.`currency_id`, `cur`.`currency_code` FROM `organisation_details` `o_d`
			LEFT JOIN `organisation_bank_details` `o_b_d` ON `o_b_d`.`organisation_id` = `o_d`.`organisation_id`
			LEFT JOIN `bank_details` `b_d` ON `b_d`.`bank_id` = `o_b_d`.`bank_id`
            LEFT JOIN `currencies` `cur` ON `cur`.`currency_id` = `o_b_d`.`currency_id`
			WHERE `o_d`.`organisation_id` = '" . $bank_account[0]['organisation_id'] . "'
			AND `o_b_d`.`organisation_bank_id` = '" . $bank_account[0]['organisation_bank_id'] . "'
			LIMIT 1
		";

		$query->executeQuery($sql_organisation_info);

		$organisation_info = $query->records;

		if ($organisation_info) {
			$sql_organisation_currencies = "
				SELECT `account_id` FROM `organisation_currencies`
				WHERE `organisation_id` = '" . (int) $bank_account[0]['organisation_id'] . "'
				AND `currency_id` = '" . $organisation_info[0]['currency_id'] . "'
			";

			$query->executeQuery($sql_organisation_currencies);

			$organisation_currencies = $query->records;

			$data = array(
				'organisation_id' 	=> $bank_account[0]['organisation_id'],
				'user_id' 			=> $organisation_info[0]['user_id'],
				'long_id' 			=> $organisation_info[0]['long_id'],
                'currency_code' 	=> $organisation_info[0]['currency_code'],
                'currency_id' 		=> $organisation_info[0]['currency_id'],
				'account_name' 		=> $bank_account[0]['account_name'],
				'iban_code' 		=> $bank_account[0]['iban_code'],
				'swift_code' 		=> $bank_account[0]['swift_code'],
			);

			// Update
			if ($organisation_currencies) {

				$data['account_id'] = $organisation_currencies[0]['account_id'];

				self::updateOrganisationCurrency($data);
			}
			// Insert
			else {
				self::createOrganisationCurrency($data);
			}
		}
		
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}

	function getContactDetails(){

		$contact		= $_REQUEST['id'];
		
		
		$query 			= new Bin_Query();
       	$sql			= "SELECT *  FROM `contact_details`  WHERE contact_id='".$contact."' limit 1";
		$query->executeQuery($sql);
		$contact 		= $query->records;

		return $contact;
		
	}

	function getContactAddress($id){

		$address_id					= $id;

		$query			= new Bin_Query();
 		$sql 			= "SELECT * FROM `address_details` where `address_id` ='".$address_id."' limit 1";
		$query->executeQuery($sql);
		$address 		= $query->records;

		return $address[0];
		
	}

	function getOwnerDetails(){

		$contact		= $_REQUEST['id'];
		$query 			= new Bin_Query();
		$sql			= "SELECT c.*, owner_id FROM owner_details as o , contact_details as c  WHERE ".
						" o.owner_id='".$contact."' && c.contact_id = o.contact_id limit 1";
		$query->executeQuery($sql);
		$contact 		= $query->records;

		return $contact;
		
	}

	function getTradeAccount(){
		
		$account_id		= $_REQUEST['id'];
		
		$query 			= new Bin_Query();
		$sql			= "SELECT *  FROM `trader_account_details`  WHERE trader_account_id='".$account_id."' limit 1";	
		$query->executeQuery($sql);
		$trade		= $query->records;

		return $trade;
		
	}

	function getTradeDoc(){
		
		$doc_id		= $_REQUEST['id'];
		
		$query 			= new Bin_Query();
		$sql			= "SELECT doc.organization_document_id , org.organisation_id, org.user_id  FROM `organisation_documents` as doc, organisation_details as org  WHERE doc.organization_document_id='".$doc_id."' && org.organisation_id = doc.organisation_id limit 1";	
		$query->executeQuery($sql);
		$doc		= $query->records;

		return $doc[0];
	}

	function saveContactDetails($post){
		
		$date 				= $_POST['year']."-".$_POST['month']."-".$_POST['date'];
		$mobile 			= $_POST['cntry']."-".$_POST['area']."-".$_POST['pn'];


		if(in_array(array('1','2'),$_POST['owner'])){
			echo "adfs";
		}

		if($_POST['owner'][0] !='' && $_POST['owner'][1] !=''){
			$owner 			= 3;
		}else if($_POST['owner'][0] !=''){
			$owner 			= $_POST['owner'][0];
		}else{
			$owner 			= 0;
		}
		
		$contact 			= Model_MOriginatorApplication::getContactDetails($_POST);
		$work				= Model_MOriginatorApplication::getContactAddress($contact[0]['work_address_id']);
		$home				= Model_MOriginatorApplication::getContactAddress($contact[0]['home_address_id']);

		$query=new Bin_Query();
		
		$sql="UPDATE `contact_details` 
			SET 
				`first_name` 				= '".$_POST['fname']."',
				`last_name` 				= '".$_POST['lname']."',
				`job_title` 				= '".$_POST['jt']."',
				`birth_date` 				= '".$date."',
				`percent_owned` 			= '".$_POST['owned']."',
				`ownership` 				= '".$owner."',
				`active_participation` 		= '".$_POST["participate"]."'
				
			WHERE 
				`contact_id` 				= '".$contact[0]['contact_id']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		
		$sql="UPDATE `address_details` 
			SET 
				`address_email` 			= '".$_POST['w_email']."' 
			WHERE 
				`address_id` 				= ".$contact[0]['work_address_id']." LIMIT 1 ;";

		$query->updateQuery($sql);
		
		
		$sql="UPDATE `address_details`
			SET 
				`address_email` 			= '".$_POST['email']."' 
			WHERE 
				`address_id` 				= ".$contact[0]['home_address_id']." LIMIT 1 ;";

		$query->updateQuery($sql);
		
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}

	function saveOwnerDetails($post){
		
		$date 				= $_POST['year']."-".$_POST['month']."-".$_POST['date'];

		if(in_array(array('1','2'),$_POST['owner'])){
			echo "adfs";
		}

		if($_POST['owner'][0] !='' && $_POST['owner'][1] !=''){
			$owner 			= 3;
		}else if($_POST['owner'][0] !=''){
			$owner 			= $_POST['owner'][0];
		}else{
			$owner 			= 0;
		}
		
		$owner1 			= Model_MOriginatorApplication::getOwnerDetails($_POST);
		$home				= Model_MOriginatorApplication::getContactAddress($owner1[0]['home_address_id']);

		$query=new Bin_Query();
		
		$sql="UPDATE `contact_details` 
			SET 
				`first_name` 				= '".$_POST['fname']."',
				`last_name` 				= '".$_POST['lname']."',
				`job_title` 				= '".$_POST['jt']."',
				`birth_date` 				= '".$date."',
				`percent_owned` 			= '".$_POST['owned']."',
				`passport_number` 			= '".$_POST['passport']."',
				`ownership` 				= '".$owner."',
				`active_participation` 		= '".$_POST["participate"]."'
			WHERE 
				`contact_id` 					= '".$owner1[0]['contact_id']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		
		$sql="UPDATE `address_details` 
			SET 
				`address_phone_country`		= '".$_POST['cntry']."',
				`address_phone_code` 		= '".$_POST['area']."',
				`address_phone` 			= '".$_POST['pn']."'
			WHERE 
				`address_id` 				= ".$home['address_id']." LIMIT 1 ;";

		$query->updateQuery($sql);
		
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	
	}

	function saveTradeAccount($post){
		
		$date 				= $_POST['f_year']."-".$_POST['f_month']."-".$_POST['f_date'];
		$query=new Bin_Query();
		
		$sql="UPDATE `trader_account_details` 
			SET 
				`fiscal_year_enddate` 		= '".$date."',
				`annual_revenue` 			= '".trim($_POST['f_revenue'])."',
				`debtors_balance` 			= '".trim($_POST['f_balance'])."',
				`average_invoice_value` 	= '".trim($_POST['f_invoice'])."',
				`payment_terms` 			= '".trim($_POST['f_terms'])."',
				`financing_relationship` 	= '".trim($_POST['f_relation'])."',
				`bill_allowance` 			= '".trim($_POST['f_allowance'])."',
				`bill_coustomer_pay_work`	= '".trim($_POST['f_paywork'])."',
				`bill_invoice_system` 		= '".trim($_POST['f_system'])."',
				`bill_sell_consignment` 	= '".trim($_POST['f_sell'])."',
				`bill_warranty` 			= '".trim($_POST['warranty'])."',
				`bill_return_rights`		= '".trim($_POST['f_return'])."',
				`bill_other_details`		= '".trim($_POST['f_details'])."'
			WHERE 
				`trader_account_id` 					= '".$_REQUEST['id']."' LIMIT 1 ;";

		$query->updateQuery($sql);
		
		//$_SESSION['mTradePopUp'] = 1;
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	
	}

	function saveTradeSubmittedBy(){
		
		$date 			= $_POST["year"]."-".$_POST["month"]."-".$_POST["date"]; 
  		$org_id 		= $_REQUEST['id'];
		$query			= new Bin_Query();
		$check_sql 		= "UPDATE `organisation_details` 
						SET 
							`submitter_firstname` = '".$_POST["fname"]."',
							`submitter_lastname` = '".$_POST["lname"]."',
							`submitted_date` = '".$date."',
							`submitter_legally_approved` = '".$_POST["legal"]."'
						WHERE 
							`organisation_id` =".$org_id." LIMIT 1 ;";
		$query->updateQuery($check_sql);
		
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}

	function saveTradeDocument(){

		
		$doc_id		= $_REQUEST['id'];
		$details 	= Model_MOriginatorApplication::getTradeDoc();		
		$uploadfile 		= array("c_csv","c_pdf","b_csv","b_pdf","d_csv","d_pdf","l_csv","l_pdf","s_csv","s_pdf","v_csv","v_pdf","p_csv","p_pdf");
		
		
		foreach($uploadfile as $key){

			//Upload PDF FIle
			$file = $key;
			if($_FILES[$key]['tmp_name'] !=''){

				$exp = explode('_',$key);
				$name = $details['organisation_id']."_".$details['user_id'];
				$dir = "../../documents/org/".$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
				
				if($exp[0] == 'c') $exp[1] = "Creditor"; if($exp[0] == 'b') $exp[1] = "Bank";if($exp[0] == 'd') $exp[1] = "Debtor"; if($exp[0] == 'l') $exp[1] = "LossAcc"; if($exp[0] == 's') $exp[1] = "BalanceSheet"; if($exp[0] == 'v') $exp[1] = "VAT"; if($exp[0] == 'p') $exp[1] = "Pay"; 
				
				//File Path assigning
				$path = pathinfo($_FILES[$file]["name"]);
				$file_name = $name."_".$exp[1]."_".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
				$filepath[$key] = "/documents/org/".$name."/".$file_name;

			}	
		}

		$update =array();
		if($filepath['d_pdf'] !=''){
			$update[] =	"`debtors_report_path` 		= '".$filepath['d_pdf']."' ";
		}
		if($filepath['d_csv'] !=''){
			$update[] =	"`debtors_report_csv` 		= '".$filepath['d_csv']."' ";
		}
		if($filepath['c_pdf'] !=''){
			$update[] =	"`creditors_report_path` 	= '".$filepath['c_pdf']."' ";
		}
		if($filepath['c_csv'] !=''){
			$update[] =	"`creditors_report_csv` 	= '".$filepath['c_csv']."' ";
		}
		if($filepath['b_pdf'] !=''){
			$update[] =	"`bank_report_path` 		= '".$filepath['b_pdf']."' ";
		}
		if($filepath['b_csv'] !=''){
			$update[] =	"`bank_report_csv` 			= '".$filepath['b_csv']."' ";
		}
		if($filepath['l_pdf'] !=''){
			$update[] =	"`loss_report_path` 		= '".$filepath['l_pdf']."' ";
		}
		if($filepath['l_csv'] !=''){
			$update[] =	"`loss_report_csv` 			= '".$filepath['l_csv']."' ";
		}
		if($filepath['s_pdf'] !=''){
			$update[] =	"`balance_report_path` 		= '".$filepath['s_pdf']."' ";
		}
		if($filepath['s_csv'] !=''){
			$update[] =	"`balance_report_csv` 		= '".$filepath['s_csv']."' ";
		}
		if($filepath['v_pdf'] !=''){
			$update[] =	"`vat_report_path` 			= '".$filepath['v_pdf']."' ";
		}
		if($filepath['v_csv'] !=''){
			$update[] =	"`vat_report_csv` 			= '".$filepath['v_csv']."' ";
		}
		if($filepath['p_pdf'] !=''){
			$update[] =	"`paye_report_path` 		= '".$filepath['p_pdf']."' ";
		}
		if($filepath['p_csv'] !=''){
			$update[] =	"`paye_report_csv` 			= '".$filepath['p_csv']."' ";
		}

		if(count($update) >0){
		
			$data = implode(",",$update);
			$query=new Bin_Query();
			$sql="UPDATE `organisation_documents` 
				SET 
					".$data."
				WHERE 
					`organization_document_id` 					= '".$details['organization_document_id']."' LIMIT 1 ;"; 
	
			$query->updateQuery($sql);
			$query->updateQuery($check_sql);	
		}
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}

	
	function saveAuditForm5($post){
		
		$yr=$_POST['fye_year1'];
		$yr1=$yr;
		$yr2=$yr-1;

		if(!empty($_FILES['sign']['name']))
		{
			$img2=$_FILES['sign']['name'];
			srand();
			$rad1=substr(md5(rand(0,1000)),0,5); 
			$img2=urlencode($img2);
			$date_con=date("Y-m-d"); 
			$img_name2="$date_con"."_"."$rad1"."_"."$img2";
			$cl_csv="documents/$img_name2";
			$cl_csv1="../../documents/$img_name2";

			move_uploaded_file($_FILES['sign']['tmp_name'],$cl_csv1);
			chmod ("$cl_csv1",0755); 
		}
		$preperation_date=$_POST['fye_year'].'-'.$_POST['fye_month'].'-'.$_POST['fye_date'];
		
		$query20 = new Bin_Query();
		$sql20="SELECT *  FROM trader_profit_loss_master WHERE orgainsation_id='".$_REQUEST['id']."'  order by trader_profit_loss_master_id ASC limit 2";
		$query20 ->executeQuery($sql20);
		$profitlossmaster = $query20->records;
		
		if(count($profitlossmaster)>0){
			$inc ='';
			for($m=0;$m<count($profitlossmaster);$m++){
				
				if($m == 1){
					$yr1 = $yr2;	
				}
				if($m > 0){
					$inc =1;
				}
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_profit_loss_master` 
							SET 
								`account_year` = '".$yr1."',
								`date_of_preperation` = '".$preperation_date."'
							WHERE 
								`trader_profit_loss_master_id` =".$profitlossmaster[$m]['trader_profit_loss_master_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
				
				$query21 = new Bin_Query();
				$sql21="SELECT *  FROM trader_profit_loss WHERE trader_profit_loss_master_id='".$profitlossmaster[$m]['trader_profit_loss_master_id']."'";
				$query21 ->executeQuery($sql21);
				$profitloss = $query21->records[0];
				
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_profit_loss` 
							SET 
								`turnover` 					= '".trim($_POST["turnover$inc"])."',
								`sales_cost` 				= '".trim($_POST["costofsale$inc"])."',
								`sales_expense` 			= '".trim($_POST["sales_exp$inc"])."',
								`general_expense` 			= '".trim($_POST["general_exp$inc"])."',
								`hire_lease` 				= '".trim($_POST["hire$inc"])."',
								`rent` 						= '".trim($_POST["rent$inc"])."',
								`administration_expense` 	= '".trim($_POST["admin_exp$inc"])."',
								`wages_salary` 				= '".trim($_POST["wages$inc"])."',
								`social_security_cost` 		= '".trim($_POST["social$inc"])."',
								`pension_insurance` 		= '".trim($_POST["pension$inc"])."',
								`depriciation` 				= '".trim($_POST["depreciation$inc"])."',
								`interest_payable` 			= '".trim($_POST["interest$inc"])."',
								`corporation_tax` 			= '".trim($_POST["ctax$inc"])."',
								`brought_forward` 			= '".trim($_POST["new$inc"])."'

							WHERE 
								`trader_profit_loss_id` =".$profitloss['trader_profit_loss_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
				
				
			}
		}
		
		$yr=$_POST['fye_year1'];
		$yr1=$yr;
		$yr2=$yr-1;
		
		$query23 = new Bin_Query();
		$sql23="SELECT *  FROM trader_balance_details WHERE orgainsation_id='".$_REQUEST['id']."'";
		$query23 ->executeQuery($sql23);
		$audited = $query23->records;

		if(count($audited)>0)
		{
			$inc ='';
			for($n=0;$n<count($audited);$n++)
			{
				if($n == 1){
					$yr1 = $yr2;	
				}
				if($n > 0){
					$inc =1;
				}
				
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_balance_details` 
							SET 
								`account_year` = '".$yr1."',
								`date_of_preperation` = '".$preperation_date."',
								`attached_accounts` = '".$cl_csv."'
							WHERE 
								`trader_balance_id` =".$audited[$n]['trader_balance_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
					
				$query24 = new Bin_Query();
				$sql24=  "SELECT *  FROM trader_balancet_sheet WHERE trader_balance_id='".$audited[$n]['trader_balance_id']."'";
				$query24 ->executeQuery($sql24);
				$auditedbalance = $query24->records[0];
				
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_balancet_sheet` 
							SET 
								`tangible_assets` 			= '".trim($_POST["tang_assest$inc"])."',
								`debtors` 					= '".trim($_POST["debtors$inc"])."',
								`cash` 						= '".trim($_POST["cashatbank$inc"])."',
								`stock` 					= '".trim($_POST["stock$inc"])."',
								`falling_due_one_year` 		= '".trim($_POST["amount_oneyear$inc"])."',
								`falling_due_other_years` 	= '".trim($_POST["amount_moreyear$inc"])."',
								`liablities` 				= '".trim($_POST["liabilities$inc"])."',
								`share_capital` 			= '".trim($_POST["called_up$inc"])."',
								`fixed_assets` 				= '".trim($_POST["fixed_assest$inc"])."'
							WHERE 
								`trader_balance_sheet_id` =".$auditedbalance['trader_balance_sheet_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
				$m++;
			}
		}
		//$_SESSION['mTradePopUp'] = 1;
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
			
	}

	function saveAuditForm5_Two($post){
		
		$yr=$_POST['fye_year1'];
		$yr1=$yr;
		$yr2=$yr-1;

		$preperation_date=$_POST['fye_year'].'-'.$_POST['fye_month'].'-'.$_POST['fye_date'];
		
		$query20 = new Bin_Query();
		$sql20="SELECT *  FROM trader_profit_loss_master WHERE orgainsation_id='".$_REQUEST['id']."'  order by trader_profit_loss_master_id DESC limit 1";
		$query20 ->executeQuery($sql20);
		$profitlossmaster = $query20->records;
		
		if(count($profitlossmaster)>0){
			$inc ='';
			for($m=0;$m<count($profitlossmaster);$m++){
				
				if($m == 1){
					$yr1 = $yr2;	
				}
				
				if($m > 0){
					$inc =1;
				}
				
				/*`account_year` = '".$yr1."',*/
				
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_profit_loss_master` 
							SET 
								`date_of_preperation` = '".$preperation_date."'
							WHERE 
								`trader_profit_loss_master_id` =".$profitlossmaster[$m]['trader_profit_loss_master_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
				
				$query21 = new Bin_Query();
				$sql21="SELECT *  FROM trader_profit_loss WHERE trader_profit_loss_master_id='".$profitlossmaster[$m]['trader_profit_loss_master_id']."'";
				$query21 ->executeQuery($sql21);
				$profitloss = $query21->records[0];
				
				$query		= new Bin_Query();
				$check_sql 	= "UPDATE `trader_profit_loss` 
							SET 
								`turnover` 					= '".trim($_POST["turnover$inc"])."',
								`sales_cost` 				= '".trim($_POST["costofsale$inc"])."',
								`sales_expense` 			= '".trim($_POST["sales_exp$inc"])."',
								`general_expense` 			= '".trim($_POST["general_exp$inc"])."',
								`hire_lease` 				= '".trim($_POST["hire$inc"])."',
								`rent` 						= '".trim($_POST["rent$inc"])."',
								`administration_expense` 	= '".trim($_POST["admin_exp$inc"])."',
								`wages_salary` 				= '".trim($_POST["wages$inc"])."',
								`social_security_cost` 		= '".trim($_POST["social$inc"])."',
								`pension_insurance` 		= '".trim($_POST["pension$inc"])."',
								`depriciation` 				= '".trim($_POST["depreciation$inc"])."',
								`interest_payable` 			= '".trim($_POST["interest$inc"])."',
								`corporation_tax` 			= '".trim($_POST["ctax$inc"])."',
								`brought_forward` 			= '".trim($_POST["new$inc"])."'
							WHERE 
								`trader_profit_loss_id` =".$profitloss['trader_profit_loss_id']." LIMIT 1 ;";
				$query->updateQuery($check_sql);
			}
		}

		//$_SESSION['mTradePopUp'] = 1;
		echo "<script> window.opener.location.href = window.opener.location.href;  window.close();</script>"; exit;
	}
	
	function getOrganisation(){

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

		return $organisation;

	}

	function getFreeCurrencies()
    {
		$qry 	= new Bin_Query();
		$qry->executeQuery('SELECT currencies.currency_id, currencies.currency_code, currencies.currency_code
                            FROM currencies
                            LEFT JOIN organisation_currency ON organisation_currency.currency_id = currencies.currency_id AND organisation_currency.organisation_id='.$_SESSION['org_id'].'
                            WHERE is_active=1 AND organisation_currency.org_currency_id IS NULL');
		return $qry->records;
	}

	function saveOriginatorCurrency(){

		include_once('classes/Model/MHelpers.php');

		$query16 			= new Bin_Query();
		$sql16				="SELECT orgbank.* , b.bank_name, c.last_name, c.first_name, c.work_address_id, c.contact_id,org.user_id  FROM `organisation_bank_details` orgbank, `bank_details` as b, contact_details as c,organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' AND org.organisation_id=orgbank.organisation_id && c.contact_id = orgbank.contact_id && c.position = '1'  && b.bank_id = orgbank.bank_id order by orgbank.organisation_bank_id ASC limit 1";			
		if($query16->executeQuery($sql16))
		$bank 				= $query16->records[0];


		$bankdet = Model_MOriginatorApplication::getMyBankDetails();


		if($_POST['bank_account']=='1'){


			$bank_orgcaddr1 = $bankdet['bank_address']['address_line_one'];
			$bank_orgc_addr2 = $bankdet['bank_address']['address_line_two'];
			$bank_orgc_city = $bankdet['bank_address']['address_city'];
			$bank_orgc_state = $bankdet['bank_address']['address_state'];
			$bank_orgc_country = $bankdet['bank_address']['address_country'];
			$bank_orgc_pc = $bankdet['bank_address']['address_zipcode'];
			$bank_orgc_ph_country = $bankdet['bank_address']['address_phone_country'];
			$bank_orgc_ph_area = $bankdet['bank_address']['address_phone_code'];
			$bank_orgc_ph_pn = $bankdet['bank_address']['address_phone'];
			$bank_orgc_fn_country = $bankdet['bank_address']['address_fax_country'];
			$bank_orgc_fn_area = $bankdet['bank_address']['address_fax_code'];
			$bank_orgc_fn_pn = $bankdet['bank_address']['address_fax'];
			$bank_orgc_email = $bankdet['bank_address']['address_email'];


			$bank_name = $bankdet['branch_one']['bank_name'];

			$bank_c_ph_country = $bankdet['bank_contact_address']['address_phone_country'];
			$bank_c_ph_area = $bankdet['bank_contact_address']['address_phone_code'];
			$bank_c_ph_pn = $bankdet['bank_contact_address']['address_phone'];
			$bank_c_email = $bankdet['bank_contact_address']['address_email'];


			$bank_c_fname = $bankdet['branch_one']['first_name'];
			$bank_c_lname = $bankdet['branch_one']['last_name'];

			$account_name = $bankdet['other_bank_account'][0]['account_name'];
			$account_no = $bankdet['other_bank_account'][0]['account_no'];
			$sort_code = $bankdet['other_bank_account'][0]['sort_code'];
			$iban_code = $bankdet['other_bank_account'][0]['iban_code'];
			$swift_code = $bankdet['other_bank_account'][0]['swift_code'];

			// $currency_bank_id = $bankdet['branch_one']['organisation_bank_id'];

		}else{

			$bank_orgcaddr1 = $_POST['bank_orgcaddr1'];
			$bank_orgc_addr2 = $_POST['bank_orgc_addr2'];
			$bank_orgc_city = $_POST['bank_orgc_city'];
			$bank_orgc_state = $_POST['bank_orgc_state'];
			$bank_orgc_country = $_POST['bank_orgc_country'];
			$bank_orgc_pc = $_POST['bank_orgc_pc'];
			$bank_orgc_ph_country = $_POST['bank_orgc_ph_country'];
			$bank_orgc_ph_area = $_POST['bank_orgc_ph_area'];
			$bank_orgc_ph_pn = $_POST['bank_orgc_ph_pn'];
			$bank_orgc_fn_country = $_POST['bank_orgc_fn_country'];
			$bank_orgc_fn_area = $_POST['bank_orgc_fn_area'];
			$bank_orgc_fn_pn = $_POST['bank_orgc_fn_pn'];
			$bank_orgc_email = $_POST['bank_orgc_email'];


			$bank_name = $_POST['bank_name'];

			$bank_c_ph_country = $_POST['bank_c_ph_country'];
			$bank_c_ph_area = $_POST['bank_c_ph_area'];
			$bank_c_ph_pn = $_POST['bank_c_ph_pn'];
			$bank_c_email = $_POST['bank_c_email'];


			$bank_c_fname = $_POST['bank_c_fname'];
			$bank_c_lname = $_POST['bank_c_lname'];

			$account_name = $_POST['account_name'];
			$account_no = $_POST['account_no'];
			$sort 			= explode("-",$_POST['sort_code']);
			$sort_code 		= $sort[0].$sort[1].$sort[2];
			$iban_code = $_POST['iban_code'];
			$swift_code = $_POST['swift_code'];

		}


			$query				=new Bin_Query();
			$bank_sql 			="INSERT INTO `address_details` (`address_line_one` ,`address_line_two` ,`address_area` ,`address_city` ,`address_state` ,`address_country` ,`address_zipcode` ,`address_phone_country` ,`address_phone_code` ,`address_phone` ,`address_mobile_country` ,`address_mobile_code` ,`address_mobile` ,`address_fax_country` ,`address_fax_code` ,`address_fax` ,`address_email` ,`address_all_details`,`modified_at` ,`modified_by`)
                                VALUES ('".addslashes($bank_orgcaddr1)."', '".addslashes($bank_orgc_addr2)."', 'NULL', '".$bank_orgc_city."', '".$bank_orgc_state."', '".$bank_orgc_country."', '".$bank_orgc_pc."', '".$bank_orgc_ph_country."', '".$bank_orgc_ph_area."', '".$bank_orgc_ph_pn."', 'NULL', 'NULL', 'NULL', '".$bank_orgc_fn_country."', '".$bank_orgc_fn_area."', '".$bank_orgc_fn_pn."', '".$bank_orgc_email."','NULL',NOW(), '".$_SESSION['user']['userid']."');";

			$query->updateQuery($bank_sql);
			$bank_address_id 		= $query->insertid;

			if($bank_name == 0 || !is_numeric($bank_name)) {

				if(!is_numeric($bank_name)){
					$new 		= $bank_name;
				}else{
					$new 		= $_POST['bank_new'];
				}

				$query			=new Bin_Query();
				$sql			="INSERT INTO bank_details (bank_name,bank_country,modified_at, modified_by,bank_status)VALUES('".$new."','".$bank_orgc_country."',NOW(),'".$_SESSION['user']['userid']."','0')";

				$query->updateQuery($sql);

				$_POST['bank_name'] 	= $query->insertid;
			}

			$query11				=new Bin_Query();
			$bank_sql11 			="INSERT INTO `address_details` (`address_line_one` ,`address_line_two` ,`address_area` ,`address_city` ,`address_state` ,`address_country` ,`address_zipcode` ,`address_phone_country` ,`address_phone_code` ,`address_phone` ,`address_mobile_country` ,`address_mobile_code` ,`address_mobile` ,`address_fax_country` ,`address_fax_code` ,`address_fax` ,`address_email` ,`address_all_details`,`modified_at` ,`modified_by`)VALUES ('', '', 'NULL', '', '', '', '','".$bank_c_ph_country."', '".$bank_c_ph_area."', '".$bank_c_ph_pn."', 'NULL', 'NULL', '', '', '','', '".$bank_c_email."','NULL',NOW(), '".$_SESSION['user']['userid']."');"; 

			$query11->updateQuery($bank_sql11);
			$contact_address_id 		= $query11->insertid;


			$qry21 					= new Bin_Query();
			$qry21->updateQuery("INSERT INTO `contact_details` (`organisation_id` ,`bank_id`,`first_name`,`last_name`,`work_address_id`,`home_address_id`,`hq_address_id`,`position` )
                                 VALUES ('".$_POST['organisation_id']."','".$_POST['bank_name']."','".$bank_c_fname."','".$bank_c_lname."','".$contact_address_id."','".self::addEmptyAddress()."','".self::addEmptyAddress()."','1')");
			$contact_id 				= $qry21->insertid;


			$qry22					=new Bin_Query();
			$index_sql22 				="INSERT INTO `organisation_bank_details` (`organisation_id` ,`address_id` ,`bank_id`,`contact_id`, `currency_id` )VALUES ('".$_POST['organisation_id']."', '".$bank_address_id."','".$_POST['bank_name']."','".$contact_id."','".$_POST['currency_id']."')";
			$qry22->updateQuery($index_sql22);
			$_POST['organisation_bank_id'] 		= $qry22->insertid;

			$qry23 					= new Bin_Query();
			$sql23 					= "INSERT INTO `organisation_bank_account_details` (`account_name`,`account_no`,`sort_code`,`iban_code`,`swift_code`,`organisation_id`,`organisation_bank_id`,`account_status`,`created`) VALUES ('".$account_name."','".$account_no."','".$sort_code."','".$iban_code."','".$swift_code."','".$_POST['organisation_id']."','".$_POST['organisation_bank_id']."','1',NOW())"; 
			$qry23->updateQuery($sql23);	

			$currency_bank_id = $_POST['organisation_bank_id'];


			$qry24 	= new Bin_Query();
			$sql24 	= "INSERT INTO organisation_currency (organisation_id,currency_id,bank_account_type,currency_bank_id,created_at) 
                                VALUES ('".$_POST['organisation_id']."','".$_POST['currency_id']."','".$_POST['bank_account']."','".$currency_bank_id."',NOW()) ";

			if($qry24->updateQuery($sql24)){

				$currency_info = Model_MHelpers::getCurrency($_POST['currency_id']);
				$organisation_details = Model_MHelpers::getOrganisationDetails($_POST['organisation_id']);

				$organisation_currencies_data = array(
					'organisation_id' 	=> $organisation_details['organisation_id'],
					'user_id' 			=> $_SESSION['user']['userid'],
					'long_id' 			=> $organisation_details['organisation_reference_id'],
					'currency_code' 	=> $currency_info['currency_code'],
					'currency_id' 		=> $currency_info['currency_id'],
					'account_name' 		=> $account_name,
					'iban_code' 		=> $iban_code,
					'swift_code' 		=> $swift_code
				);

				self::createOrganisationCurrency($organisation_currencies_data);

				$_SESSION['result'] = 'Currency has been added successfully';

				if(isset($_REQUEST['flg'])){

					$_SESSION['country_id'] = $_POST['country_id'];
					header("Location: index.php?do=createdebtor");
				}else{
					header("Location: index.php?do=addoriginatorcurrency");
				}
				exit();
			}
	}

	function getOriginatorCurrency()
    {
		$qry 		= new Bin_Query();
		$qry->executeQuery("SELECT c.* 
                            FROM organisation_currency oc 
                            LEFT JOIN currencies c ON oc.currency_id=c.currency_id 
                            WHERE  oc.org_currency_id='".$_REQUEST['cid']."' AND oc.organisation_id= '".$_SESSION['org_id']."'
                            LIMIT 1");
		return $qry->records[0];
	}

	function getCurrencyBankDetails()
    {
		$query16 			= new Bin_Query();
		$sql16				="SELECT orgbank.* , b.bank_name, c.last_name, c.first_name, c.work_address_id, c.contact_id,org.user_id  
                              FROM `organisation_bank_details` orgbank, `bank_details` as b, contact_details as c,organisation_details org,organisation_currency oc 
                              WHERE oc.org_currency_id='".$_REQUEST['cid']."' && org.user_id='".$_SESSION['user']['userid']."' AND org.organisation_id=orgbank.organisation_id && oc.organisation_id=org.organisation_id && oc.currency_bank_id = orgbank.organisation_bank_id && c.contact_id = orgbank.contact_id && c.position = '1'  && b.bank_id = orgbank.bank_id 
                              order by orgbank.organisation_bank_id ASC 
                              limit 1";			
                              
		$query16->executeQuery($sql16);
		$bank 				= $query16->records;

		foreach($bank as $branch_one)
        {
					$query 			= new Bin_Query();
					$sql 			= "SELECT a.*, c.country_name  FROM `address_details` a, `country_mas` c WHERE a.address_id ='".$branch_one['address_id']."' AND c.country_id=a.address_country";
					$query->executeQuery($sql);
					$bank_address 		=$query->records[0];
					
					$query 			= new Bin_Query();
					$sql 			= "SELECT a.*, c.country_name  FROM `address_details` a LEFT JOIN `country_mas` c ON c.country_id=a.address_country WHERE a.address_id ='".$branch_one['work_address_id']."' LIMIT 1 ";
					$query->executeQuery($sql);
					$bank_contact_address =$query->records[0];
					
					
					$query 			= new Bin_Query();
					$sql 			= "SELECT * FROM `organisation_bank_account_details`  WHERE organisation_bank_id ='".$branch_one['organisation_bank_id']."' order by account_id DESC";
					$query->executeQuery($sql);
					$other_bank_account 	=$query->records;
		

					for($i=0;$i<count($other_bank_account);$i++){
					if($other_bank_account[$i]['change'] == '1'){
						
						$query1 		= new Bin_Query();
						$sql1			= "SELECT * FROM `bank_account_change_request` WHERE account_id ='".$other_bank_account[$i]['account_id']."' limit 1";
						$query1->executeQuery($sql1);
						$change 		= $query1->records;
						if(count($change) >0){
							$other_bank_account[$i]['account_name'] 	= $change[0]['account_name'];
							$other_bank_account[$i]['account_no'] 		= $change[0]['account_no'];
							$other_bank_account[$i]['sort_code']		= $change[0]['sort_code'];
							$other_bank_account[$i]['iban_code'] 		= $change[0]['iban_code'];
							$other_bank_account[$i]['swift_code'] 		= $change[0]['swift_code'];
						}
					}
				}

			}

			$bankdet 	= array("branch_one"=>$branch_one,"bank_address"=>$bank_address,"bank_contact_address"=>$bank_contact_address,"other_bank_account"=>$other_bank_account);

			return $bankdet;
	}


	function getMyBankDetails()
    {
			$query16 			= new Bin_Query();
			$sql16				="SELECT orgbank.* , b.bank_name, c.last_name, c.first_name, c.work_address_id, c.contact_id,org.user_id  FROM `organisation_bank_details` orgbank, `bank_details` as b, contact_details as c,organisation_details org WHERE org.user_id='".$_SESSION['user']['userid']."' AND org.organisation_id=orgbank.organisation_id && c.contact_id = orgbank.contact_id && c.position = '1'  && b.bank_id = orgbank.bank_id order by orgbank.organisation_bank_id ASC limit 1";			
			if($query16->executeQuery($sql16))
			$bank 				= $query16->records;


			foreach($bank as $branch_one){
				

				$query 			= new Bin_Query();
				$sql 			= "SELECT a.*, c.country_name  FROM `address_details` a, `country_mas` c WHERE a.address_id ='".$branch_one['address_id']."' AND c.country_id=a.address_country";
				$query->executeQuery($sql);
				$bank_address 		=$query->records[0];
				
				$query 			= new Bin_Query();
				$sql 			= "SELECT a.*, c.country_name  FROM `address_details` a LEFT JOIN `country_mas` c ON c.country_id=a.address_country WHERE a.address_id ='".$branch_one['work_address_id']."' LIMIT 1 ";
				$query->executeQuery($sql);
				$bank_contact_address =$query->records[0];
				
				
				$query 			= new Bin_Query();
				$sql 			= "SELECT * FROM `organisation_bank_account_details`  WHERE organisation_bank_id ='".$branch_one['organisation_bank_id']."' order by account_id DESC";
				$query->executeQuery($sql);
				$other_bank_account 	=$query->records;
	

				for($i=0;$i<count($other_bank_account);$i++){
				if($other_bank_account[$i]['change'] == '1'){
					
					$query1 		= new Bin_Query();
					$sql1			= "SELECT * FROM `bank_account_change_request` WHERE account_id ='".$other_bank_account[$i]['account_id']."' limit 1";
					$query1->executeQuery($sql1);
					$change 		= $query1->records;
					if(count($change) >0){
						$other_bank_account[$i]['account_name'] 	= $change[0]['account_name'];
						$other_bank_account[$i]['account_no'] 		= $change[0]['account_no'];
						$other_bank_account[$i]['sort_code']		= $change[0]['sort_code'];
						$other_bank_account[$i]['iban_code'] 		= $change[0]['iban_code'];
						$other_bank_account[$i]['swift_code'] 		= $change[0]['swift_code'];
					}
				}
			}

		}


		$bankdet 	= array("branch_one"=>$branch_one,"bank_address"=>$bank_address,"bank_contact_address"=>$bank_contact_address,"other_bank_account"=>$other_bank_account);

		return $bankdet;
	}

	function viewUserDetails(){

		$qry 		= new Bin_Query();
		$sql 		= "SELECT * FROM organisation_users WHERE temp_user_id='".$_REQUEST['id']."' AND parent_id='".$_SESSION['user']['userid']."' LIMIT 1 ";
		$qry->executeQuery($sql);
		$records 	= $qry->records[0];

		if(count($records)<1){

			if($_SESSION['user']['usertype']=='3'){
				header('Location: index.php?do=showoriginatorcurrency');
			}elseif($_SESSION['user']['usertype']=='2'){
				$header('Location: index.php?do=showinvestorcurrency');
			}elseif($_SESSION['user']['usertype']=='5'){
				header('Location: index.php?do=showintermediarycurrency');
			}elseif($_SESSION['user']['usertype']=='6'){
				header('Location: index.php?do=showretailercurrency');
			}
			exit();
		}

		return $records;
	}
    
    function deleteOriginatorCurrency()
    {
        if (empty($_REQUEST['cid']))
        {
            $_SESSION['error']='Error';
            return FALSE;
        }
        
        $_REQUEST['cid']=(int)$_REQUEST['cid'];
        
        include_once('admin/classes/Model/originator_actions.php');
        $originator  = new Originator_actions();
        return $originator->deleteCurrency($_REQUEST['cid'],$_SESSION['org_id']);
    }

	function createOrganisationCurrency(array $data = array())
	{
		if (!$data) {
			return false;
		}

		$query = new Bin_Query();

		$sql = "
			INSERT INTO `organisation_currencies`
			(
				`organisation_id`,
				`user_id`,
				`long_id`,
				`currency_code`,
				`currency_id`,
				`account_name`,
				`iban_code`,
				`swift_code`
			)
			VALUES (
				'" . (int) $data['organisation_id'] . "',
				'" . (int) $data['user_id'] . "',
				'" . $data['long_id'] . "',
				'" . $data['currency_code'] . "',
				'" . (int) $data['currency_id'] . "',
				'" . $data['account_name'] . "',
				'" . $data['iban_code'] . "',
				'" . $data['swift_code'] . "'
			)
		";

		$query->executeQuery($sql);

		return $query->insertid;
	}

	function updateOrganisationCurrency(array $data = array())
	{
		if (!$data) {
			return false;
		}

		$query = new Bin_Query();

		$sql = "
			UPDATE `organisation_currencies`
			SET
				`organisation_id` = '" . (int) $data['organisation_id'] . "',
				`user_id` = '" . (int) $data['user_id'] . "',
				`long_id` = '" . $data['long_id'] . "',
				`currency_code` = '" . $data['currency_code'] . "',
				`currency_id` = '" . (int) $data['currency_id'] . "',
				`account_name` = '" . $data['account_name'] . "',
				`iban_code` = '" . $data['iban_code'] . "',
				`swift_code` = '" . $data['swift_code'] . "'
			WHERE `account_id` = '" . $data['account_id'] . "'
		";

		return $query->updateQuery($sql);

	}

    /**
     * @param $originatorId
     * @return bool
     */
    public function isOrpaEnabled($originatorId)
    {
        $db = Bin_Db::connect();
        $checkOrpaEnabledSql = "SELECT orpa_enabled FROM organisation_details WHERE user_id = ':user_id' LIMIT 1";
        $result = $db->query($checkOrpaEnabledSql, array(':user_id' => $originatorId));
        $resultArray = $result->getResultArray();

        return (bool)array_get($resultArray[0], 'orpa_enabled');
    }
}
?>