<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Extended HRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/
$page_security = 'HR_LOAN_INQ';
$path_to_root="../../..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();
include($path_to_root . "/modules/ExtendedHRM/includes/Payroll.inc" );
$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");
if (!@$_GET['popup']){
	page(_("Loan Approve Inquiry"));
} else
	page(_("Loan Approve Inquiry"),true);
kv_simple_page_mode(true);

$dec = user_price_dec();
check_db_has_employees(sprintf(_("There is no employee in this system. Kindly Open '%s' to update it"), "<a href='".$path_to_root."/modules/ExtendedHRM/manage/employees.php'>"._("Add And Manage Employees")."</a>"));

//---------------------------------------------------------------------------------------------------
$input_error = 0;

if (isset($_GET['loan_id'])){
		$_POST['loan_id'] = $_GET['loan_id'];
	}

//---------------------------------------------------------------------------------------------------
$action = $_SERVER['PHP_SELF'];
if ($page_nested)
	$action .= "?empl_id=".get_post('empl_id');
start_form(false, false, $action);

if (!$page_nested){
	// start_table(TABLESTYLE_NOBORDER);
	// 		start_row();
	// 		 	department_list_cells(_("Select a Department")." :", 'dept_id', null,	_('No Department'), true, check_value('show_inactive'));
	// 			employee_list_cells(_("Select an Employee"). " :", 'empl_id', null,	_("Select an Employee"), true, check_value('show_inactive'), false, false,true);
	// 			$new_item = get_post('dept_id')=='';
	// 	 	end_row();
	//  	end_table();
	echo "<hr></center>";
}
else
	br(2);
//----------------------------------------------------------------------------------------------------
if ($Mode == 'RESET'){
	$selected_id = -1;
	$sav = get_post('show_inactive');
	$dept = get_post('dept_id');
	unset($_POST);
	$_POST['dept_id'] = $dept;
	$_POST['show_inactive'] = $sav;
	$Ajax->activate('_page_body');
}

if (list_updated('empl_id')) {
	$Ajax->activate('price_table');
	$Ajax->activate('Edit_Loan');
}
if (list_updated('empl_id') || isset($_POST['periods']) || isset($_POST['loan_type_id'])) {
	// after change of stock, currency or salestype selector
	// display default calculated price for new settings. 
	// If we have this price already in db it is overwritten later.
	unset($_POST['monthly_pay']);
	//$Mode = $_POST['Mode'];
	$Ajax->activate('Edit_Loan');
}
//---------------------------------------------------------------------------------------------------
if(isset($_GET['loan_id']))
echo '<h4><center>Loan #'.$_GET['loan_id'].'</center></h4>';
div_start('price_table');
$order_by = $where  = [];
$join = array( 
	0 => array('join' => 'LEFT', 'table_name'=>'kv_empl_loan_repayment AS repayment','conditions' =>'`loan`.`id` = `repayment`.`loan_id`'),
	1 => array('join' => 'INNER', 'table_name' => 'kv_empl_loan_types AS type', 'conditions' => '`type`.`id` = `loan`.`loan_type_id`'),
	2 => array('join' => 'INNER', 'table_name' => 'kv_empl_info AS info', 'conditions' => '`info`.`empl_id` = `loan`.`empl_id`')
);
	if(get_post('empl_id') !='' ){
		$where = array('`info`.`empl_id`' => get_post('empl_id'));

			} else { 
				if(get_post('dept_id') > 0){

					$where['`job`.`department`'] = get_post('dept_id');
					$order_by['info.empl_id'] = 'asc';

				}elseif(isset($_POST['loan_id'])){
					$where['`loan`.`id`'] = get_post('loan_id');
					$order_by['info.empl_id'] = 'asc';
				}else {
					$order_by['info.empl_id'] = 'asc';
				}
			}
			$columns = array('`info`.`empl_id`, CONCAT(`info`.`empl_firstname`, " ", `info`.`empl_lastname`) AS name, `type`.`loan_name`, `loan`.`loan_amount`, `loan`.`monthly_pay`, `loan`.`periods`, `repayment`. `periods_paid`, `loan`. `date`, `loan`.`status`, `loan`.`id`, `type`.`interest_rate`,`loan`.`end_date`,`repayment`.`re_pay_amount`,`repayment`.`re_pay_date`,`repayment`.`pay_slip_id`,`repayment`.`payment_id`,`loan`.`payment`');

			$loans = GetDataJoin('kv_empl_loan AS loan', $join , $columns, $where, $order_by);

//---------------------------------

foreach($loans as $loan_single) 

if($loan_single['end_date'] == '0000-00-00'){
	$date_of_end = date('Y-m-d', strtotime("+".$loan_single[5]." months", strtotime($loan_single[7])));
	} 
else
$date_of_end = $loan_single['end_date'];

echo "<br>";

start_table(TABLESTYLE2, "width='95%'");
echo "<tr valign=top><td>"; // outer table

/*Now the customer charged to details in a sub table*/
start_table(TABLESTYLE, "width='100%'");
$th = array(_("Employee"));
table_header($th);
if(isset($loan_single)){
label_row(null, $loan_single[0] , "nowrap");
label_row(null, $loan_single[1] , "nowrap");
}
end_table();
/*end of the small table showing charge to account details */

echo "</td><td>"; // outer table

start_table(TABLESTYLE, "width='100%'");
$th = array(_("Amount"),'');
table_header($th);
if(isset($loan_single)){
	label_row('Loan Amount', price_format($loan_single[3]) , "nowrap","align=right");
	label_row('Installment',price_format($loan_single['monthly_pay']), "nowrap","align=right");
	label_row('Balance Payable',price_format($loan_single[4]* ($loan_single[5]-$loan_single[6])), "nowrap","align=right");
	start_row();
	label_cells(_("Loan type"), $loan_single['loan_name'], "class='tableheader2'");
	label_row(_("Interest Rate"), $loan_single['interest_rate'].'%', "nowrap");
	end_row();
}
end_table();

echo "</td><td>"; // outer table

start_table(TABLESTYLE, "width='100%'");
$th = array(_("Date"),'');
table_header($th);
if(isset($loan_single)){
	label_row(_('Start'), sql2date($loan_single[7]) , "nowrap");
	label_row(_('End'),sql2date($date_of_end), "nowrap");
	label_row(_('Installment periods'),$loan_single['periods'], "nowrap");
	label_row(_('Total Periods Paid'), $loan_single[6], "nowrap");
	if(isset($loan_single['payment'])){
		$bank_trans_details = GetRow('bank_trans',array('type' => ST_BANKPAYMENT,'trans_no' => $loan_single['payment']));
		label_row(_('Payment'),get_trans_view_str($bank_trans_details["type"],$bank_trans_details["trans_no"],$bank_trans_details['ref'],false,'','',false,'data-classes="half_width popup_height5"'));
	}
}
end_table();

start_table(TABLESTYLE, "width='100%'");
// $th = array(_("Date"),'');
start_row();
// label_cells(_("Start"), sql2date($loan_single[7]), "class='tableheader2'");
// label_cells(_("End"), sql2date($date_of_end), "class='tableheader2'");
end_row();
start_row();
// label_cells(_("Status"), $loan_single[8], "class='tableheader2'");
// label_cells(_("Shipping Company"), $myrow["shipper_name"], "class='tableheader2'");
end_row();
// comments_display_row(ST_CUSTCREDIT, $trans_id);
end_table();

echo "</td></tr>";
end_table(1); // outer table


//----------------------------------------
	start_table(TABLESTYLE);

	$th = array ('',_('Date'), _('#Payslip/Amount deposit'),_('Amount Paid This Time'), _("Periods Paid"),_("Total Paid"));
			inactive_control_column($th);
			table_header($th);
			$s_no = 1;

	foreach($loans as $loan_single) {
				
		if((int)$loan_single['re_pay_amount'] <= 0 || $loan_single['re_pay_amount'] == null){
					echo '<tr><td colspan="6"> No Data </td></tr>';
					continue;
				}
				if($loan_single['end_date'] == '0000-00-00' ){

				$date_of_end = date('Y-m-d', strtotime("+".$loan_single[5]." months", strtotime($loan_single[7])));
				} 
				else
				$date_of_end = $loan_single['end_date'];

				echo '<tr style="text-align:left"><td>'.$s_no.'</td><td>'.(sql2date($loan_single['re_pay_date'])).'</td><td>'.(isset($loan_single['pay_slip_id']) && ($loan_single['pay_slip_id'] >0) ? hrm_viewer_link(ST_EMPLOYEE_SALARY,$loan_single['pay_slip_id'],$loan_single['pay_slip_id']) : (isset($loan_single['payment_id'])&&($loan_single['payment_id'] >0) ? get_gl_view_str(ST_BANKDEPOSIT,$loan_single['payment_id'],$loan_single['payment_id']) : '')).'</td><td style="text-align:right;">'.price_format($loan_single['re_pay_amount'] ).'</td><td>'.$loan_single[6].'</td><td style="text-align:right;">'.price_format($loan_single[4]*$loan_single[6]).'</td>';
				// edit_button_cell("Edit".$loan_single['id'], _("Edit"));
				// label_cell(get_gl_view_str(98,$loan_single['id'], _("")));	
				// repay_button_cell("Pay".$loan_single['id'], _("Repayment"));
 			// 	delete_button_cell("Delete".$loan_single['id'], _("Delete"));
 				echo '<tr>';
 				$s_no++;
	}
	end_table();
div_end();
//------------------------------------------------------------------------------------------------
echo "<br>";
end_form();
end_page();

function PMT($i, $n, $p) {
	$i = $i/1200; 
	$p = -$p; 
	return $i * $p * pow((1 + $i), $n) / (1 - pow((1 + $i), $n));
}
//----------------------------------------------------------------------------------------------------
function get_loan_interest_rate($id){
	return GetSingleValue('kv_empl_loan_types', 'interest_rate', array('id' => $id));
}
//----------------------------------------------------------------------------------------------------
function can_process(){
	if ($_POST['empl_id'] == ""){
		display_error(_("There is no Employee selected."));
		set_focus('selected_id');
		return false;
	} 
	if ($_POST['loan_amount'] == ""  || !check_num('loan_amount', 0)){
		display_error(_("Loan Amount is Empty or Not number"));
		set_focus('loan_amount');
		return false;
	} 
	if ($_POST['periods'] == ""|| !check_num('periods', 0)){
		display_error(_("Term Period is Empty or not Number."));
		set_focus('periods');
		return false;
	} 
	if ($_POST['loan_type_id'] == ""){
		display_error(_("Select Loan Type."));
		set_focus('loan_id');
		return false;
	} 
	if ($_POST['monthly_pay'] == "" || !check_num('monthly_pay', 0)){
		display_error(_("Calculate the Monthly Pay and Save it."));
		set_focus('loan_id');
		return false;
	} 
	/*$form_date = date2sql($_POST['date']);
	$today_date = date("Y-m-d");
	if($form_date < $today_date && get_hrm_option('test_mode') == 0){
		display_error(_("Enter a Valid Date."));
		set_focus('date');
		return false;
	}
	if(GetSingleValue('kv_empl_loan', 'id', array('empl_id' => $_POST['empl_id'], 'status' => 'Active')) != $_POST['selected_id']){
		display_error(_("The Selected Employee has another loan, which has not closed yet."));
		set_focus('date');
		return false;
	}*/
	return true;
}
?>
