<?php
/**********************************************************************
Copyright (C) Evolve Techniologies
Created By : Danushka Widanage
Email : info@evolve-sl.com
Company : Evolve Technologies(pvt)Ltd
***********************************************************************/

$page_security = 'SA_BANKTRANSVIEW';
$path_to_root = "..";
include_once($path_to_root . "/includes/session.inc");

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/gl/includes/gl_db.inc");


include_once($path_to_root . "/includes/data_checks.inc");

$js = "";
if ($use_popup_windows)
	$js .= get_js_open_window(1200, 1200);
if ($use_date_picker)
	$js .= get_js_date_picker();
	
page(_($help_context = "General Ledger Transaction Details"), true);

if (!isset($_GET['type_id']) || !isset($_GET['trans_no'])) 
{ /*Script was not passed the correct parameters */

	display_note(_("The script must be called with a valid transaction type and transaction number to review the general ledger postings for."));
	end_page();
}


function getbanktrans($type, $trans_no=null, $person_type_id=null, $person_id=null)
{
	$sql = "SELECT *, ".TB_PREF."bank_trans.id AS bt_counter,  bank_account_name, account_code, bank_curr_code
		FROM ".TB_PREF."bank_trans, ".TB_PREF."bank_accounts
		WHERE ".TB_PREF."bank_accounts.id=".TB_PREF."bank_trans.bank_act ";
	if ($type != null)
		$sql .= " AND type=".db_escape($type);
	if ($trans_no != null)
		$sql .= " AND ".TB_PREF."bank_trans.trans_no = ".db_escape($trans_no);
	if ($person_type_id != null)
		$sql .= " AND ".TB_PREF."bank_trans.person_type_id = ".db_escape($person_type_id);
	if ($person_id != null)
		$sql .= " AND ".TB_PREF."bank_trans.person_id = ".db_escape($person_id);
	$sql .= " ORDER BY ".TB_PREF."bank_trans.id DESC";

	 return db_query($sql, "query for bank transaction");
}

function get_gl_trans_edit($type, $trans_id)
{
	$sql = "SELECT gl.*, cm.account_name, IF(ISNULL(refs.reference), '', refs.reference) AS reference FROM "
		.TB_PREF."gl_trans as gl
		LEFT JOIN ".TB_PREF."chart_master as cm ON gl.account = cm.account_code
		LEFT JOIN ".TB_PREF."refs as refs ON (gl.type=refs.type AND gl.type_no=refs.id)"
		." WHERE gl.type= ".db_escape($type) 
		." AND gl.type_no = ".db_escape($trans_id)."";
		
		$sql .=	" ORDER BY counter";

	return db_query($sql, "The gl transactions could not be retrieved");
}

function edit_transaction($editable, $type_id, $trans_id, $rowcount, $trans_date, $bank_trans_array){



//echo '<pre>';
//print_r($_POST);
//echo '</pre>';


//--------gl_trans table updating --------------
	for($i=0;$i<$rowcount;){
		$sql = "UPDATE ".TB_PREF."gl_trans 
						SET account = ".$editable[$i]['code'].", 
							amount = ".$editable[$i]['amount'].", 
							person_id = '".$editable[$i]['payeename']."',
							tran_date = '".date2sql($trans_date)."'
						WHERE type = '$type_id' 
						AND type_no = '$trans_id' 
						AND counter = ".$editable[$i]['counter'];	
		
		//db_query($sql, $err_msg);

		if($type_id == ST_BANKDEPOSIT){
			$sql = "SELECT id AS bank_id FROM ".TB_PREF."bank_accounts WHERE account_code = ".$editable[$i]['code']."";
			$result = db_query($sql, $err_msg);
			$row = db_fetch($result);

			$sql = "UPDATE ".TB_PREF."bank_trans 
							SET amount = '".$editable[$i]['amount']."' ,
								person_id = '".$editable[$i-1]['payeename']."',
								bank_act = '".$row['bank_id']."',
								trans_date = '".date2sql($trans_date)."'
								
							WHERE type = '$type_id' 
							AND trans_no = '$trans_id'
							AND id = '".$bank_trans_array[$i]['bt_counter_id']."'";

			//db_query($sql, $err_msg);
		}
		$i++;
	}
	
	if($type_id == ST_BANKPAYMENT){
		for($j=0;$j<count($bank_trans_array);){
			$relavant_bankcode = end($editable);
			//print_r($relavant_bankcode['amount']);
			$sql = "SELECT id AS bank_id FROM ".TB_PREF."bank_accounts WHERE account_code = ".$bank_trans_array[$j]['account_code']."";
			$result = db_query($sql, $err_msg);
			$row = db_fetch($result);
		
			echo '<br>'.$sql = "UPDATE ".TB_PREF."bank_trans 
							SET amount = '".$editable[$i]['amount']."' ,
								person_id = '".$editable[$i-1]['payeename']."',
								bank_act = '".$row['bank_id']."',
								trans_date = '".date2sql($trans_date)."'
								
							WHERE type = '$type_id' 
							AND trans_no = '$trans_id'
							AND id = '".$bank_trans_array[$i]['bt_counter_id']."'";
			//db_query($sql, $err_msg);
			$j++;
			
		}
	}
		



	
	
	if($type_id == ST_CUSTPAYMENT || $type_id == ST_BANKPAYMENT || $type_id == ST_SUPPAYMENT ){
		
		if($type_id == ST_CUSTPAYMENT){
			$sql = "SELECT id AS bank_id FROM ".TB_PREF."bank_accounts WHERE account_code = ".$editable[0]['code']."";

			$result = db_query($sql, $err_msg);
			$row = db_fetch($result);
	
			$sql = "UPDATE ".TB_PREF."bank_trans 
							SET amount = '".$editable[1]['amount']."' ,
								person_id = '".$editable[$i-1]['payeename']."',
								bank_act = '".$row['bank_id']."',
								trans_date = '".date2sql($trans_date)."'
								
							WHERE type = '$type_id' 
							AND trans_no = '$trans_id'
							AND id = '".$bank_trans_array[0]['bt_counter_id']."'";
			//db_query($sql, $err_msg);
		}
		if($type_id == ST_BANKPAYMENT || $type_id == ST_SUPPAYMENT){
			$relavant_bankcode = end($editable);
			//print_r($relavant_bankcode['amount']);
			$sql = "SELECT id AS bank_id FROM ".TB_PREF."bank_accounts WHERE account_code = ".$relavant_bankcode['code']."";
			$result = db_query($sql, $err_msg);
			$row = db_fetch($result);
	
			$sql = "UPDATE ".TB_PREF."bank_trans 
							SET amount = '".$relavant_bankcode['amount']."' ,
								person_id = '".$editable[$i-1]['payeename']."',
								bank_act = '".$row['bank_id']."',
								trans_date = '".date2sql($trans_date)."'
								
							WHERE type = '$type_id' 
							AND trans_no = '$trans_id'
							AND id = '".$bank_trans_array[0]['bt_counter_id']."'";
			//db_query($sql, $err_msg);
		}


	}

//--------------edit customer payment related tables--------
	
	if($type_id == ST_CUSTPAYMENT){
		$sql = "UPDATE ".TB_PREF."cust_allocations 
					SET date_alloc = '".date2sql($trans_date)."',
						amt = '".$editable[0]['amount']."'
					WHERE trans_no_from = ".$trans_id."
					AND trans_type_from = ".$type_id."";
		///db_query($sql, $err_msg);
	
	}
//--------------edit customer payment related tables--------
	
//----------------updating the audit trials table record---------
	$sql = "UPDATE `".TB_PREF."audit_trail` 
					SET gl_date = '".date2sql($trans_date)."',
						description = 'Edited'
					WHERE type = ".$type_id."
					AND trans_no = ".$trans_id."";
		//db_query($sql, $err_msg);

//---------------------edit supplier payment related tables------------
	if($type_id == ST_SUPPAYMENT){
		$sql = "UPDATE ".TB_PREF."supp_allocations 
						SET amt = '".abs($editable[$rowcount-1]['amount'])."'
						WHERE trans_no_from = '$trans_id'
						AND trans_type_from = '$type_id'";
		//db_query($sql, $err_msg);
		
		$sql = "UPDATE  ".TB_PREF."supp_trans 
					SET ov_amount = '".$editable[$rowcount-1]['amount']."' ,
						ov_discount = 0,
						ov_gst = 0,
						alloc = '".abs($editable[$rowcount-1]['amount'])."'
					WHERE trans_no = '$trans_id'
					AND type = '$type_id'";
		//db_query($sql, $err_msg);
	}
//---------------------edit supplier payment related tables------------

}

if(isset($_POST['EditTransaction'])){


$bank_trans = getbanktrans($_GET['type_id'], $_GET['trans_no'], $person_type_id=null, $person_id=null);
$k=0;
while ($row_banktrans = db_fetch($bank_trans)) 
{
	$bank_trans_array[$k]=array('bt_counter_id'=>$row_banktrans['bt_counter'], 
								'bank_account'=>$row_banktrans['bank_act'],
								'bank_amount'=>$row_banktrans['amount'],
								'account_code'=>$row_banktrans['account_code']);	
	$k++;
}
echo '<pre>';
print_r($bank_trans_array);
echo '</pre>';

	$row_payee = $_POST['nameofpayee'];
	$code = $_POST['account_code']+1;
	$row_count = $_POST['rowcount'];
	$_POST['amount'.$_POST['account_code']];
	$trans_date = $_POST['tran_date'];
	
	 $j =0;
	for($i=$row_count;$i>0;){

		$sql = "SELECT id AS bank_id FROM ".TB_PREF."bank_accounts WHERE account_code = ".$_POST[$code-$i]."";
		$result = db_query($sql, $err_msg);
		$row = db_fetch($result);
		
		$sql_bank_trans = "SELECT * FROM ".TB_PREF."bank_trans 
														WHERE type = ".$_GET['type_id']." 
														AND trans_no = ".$_GET['trans_no']." 
														AND bank_act = ".$row['bank_id'];
		$result_bank_trans = db_query($sql_bank_trans, $err_msg);
		$row_bank_trans = db_fetch($result_bank_trans);
			
		$row_payee;
		$_POST[$code-$i];
		$_POST['amount'.($code-$i)];
		
		$editabledate[$j]=array('code'=>$_POST[$code-$i], 
								'amount'=>$_POST['amount'.($code-$i)], 
								'counter'=>$code-$i, 
								'payeename'=>$row_payee, 
								'bank'=>$row['bank_id'],
								'bank_counter'=>$row_bank_trans['id']);
		 
		$i--;
		$j++;
	}
	echo 'editable';
	echo '<pre>';
	print_r($editabledate);
	echo '</pre>';

	edit_transaction($editabledate,$_GET['type_id'],$_GET['trans_no'],$row_count, $trans_date, $bank_trans_array);

}

start_form('','','edit_trans.php?type_id='.$_GET['type_id'].'&trans_no='.$_GET['trans_no'],'edit_tansaction');

function display_gl_heading($myrow)
{
	global $systypes_array;
	$trans_name = $systypes_array[$_GET['type_id']];
    start_table(TABLESTYLE, "width=95%");
    $th = array(_("#"), _("Reference"), _("Date(mdy)"), _("Person/Item"));
    table_header($th);	
    start_row();	
    label_cell("$trans_name #" . $_GET['trans_no']);
    label_cell($myrow["reference"]);
	//label_cell(sql2date($myrow["tran_date"]));
	//date_cells(null, 'tran_date', '', null, 0, 0, 10);
	custom_input('tran_date', sql2date($myrow["tran_date"]),'10');
		
	custom_input('nameofpayee', payment_person_name($myrow["person_type_id"],$myrow["person_id"]),'40');
	
	//bank_accounts_list_cells($label, 'selected_bank', $row_acc["bank_act"], $submit_on_change=false);
	
	end_row();

	comments_display_row($_GET['type_id'], $_GET['trans_no']);

    end_table(1);
}
$result = get_gl_trans_edit($_GET['type_id'], $_GET['trans_no']);



if (db_num_rows($result) == 0)
{
    echo "<p><center>" . _("No general ledger transactions have been created for") . " " .$systypes_array[$_GET['type_id']]." " . _("number") . " " . $_GET['trans_no'] . "</center></p><br><br>";
	end_page(true);
	exit;
}

/*show a table of the transactions returned by the sql */
$dim = get_company_pref('use_dimension');

if ($dim == 2)
	$th = array(_("Account Code"), _("Account Name"), _("Dimension")." 1", _("Dimension")." 2", _("Debit"), _("Credit"), _("Amount"), _("Memo"));
else if ($dim == 1)
	$th = array(_("Account Code"), _("Account Name"), _("Dimension"), _("Debit"), _("Credit"), _("Amount"), _("Memo"));
else		
	$th = array(_("Account Code"), _("Account Name"), _("Debit"), _("Credit"), _("Amount"), _("Memo"));
$k = 0; //row colour counter
$heading_shown = false;
$row_count = 0;




$credit = $debit = 0;
while ($myrow = db_fetch($result)) 
{
	if ($myrow['amount'] == 0) continue;
	if (!$heading_shown)
	{
		display_gl_heading($myrow);
		
		start_table(TABLESTYLE, "width=95%");
		table_header($th);
		$heading_shown = true;
	}	

	alt_table_row_color($k);
	
	$account_code =  $myrow['counter'];
	echo gl_all_accounts_list($myrow['counter'], $myrow['account'], true, true);
	
   // label_cell($myrow['account']);
	//label_cell($myrow['account_name']);
	if ($dim >= 1)
		label_cell(get_dimension_string($myrow['dimension_id'], true));
	if ($dim > 1)
		label_cell(get_dimension_string($myrow['dimension2_id'], true));

	display_debit_or_credit_cells($myrow['amount']);
	
	custom_input('amount'.$myrow['counter'], $myrow['amount']);
	
	label_cell($myrow['memo_']);
	end_row();
    if ($myrow['amount'] > 0 ) 
    	$debit += $myrow['amount'];
    else 
    	$credit += $myrow['amount'];
		
		$row_count++;
}
//echo $row_count;
if ($heading_shown)
{
    start_row("class='inquirybg' style='font-weight:bold'");
    label_cell(_("Total"), "colspan=2");
    if ($dim >= 1)
        label_cell('');
    if ($dim > 1)
        label_cell('');
    amount_cell($debit);
    amount_cell(-$credit);
    label_cell('');
	
    end_row();
	
	end_table(1);

	
}

hidden('rowcount', $row_count);
hidden('account_code', $account_code);

//end of while loop
 //$sql = "SELECT * FROM `".TB_PREF."cust_allocations` WHERE trans_no_from = ".$_GET['trans_no'];

submit_center('EditTransaction', _("Edit Transacion"), true, '', '');

end_form();
is_voided_display($_GET['type_id'], $_GET['trans_no'], _("This transaction has been voided."));


end_page();

?>
