<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Extended HRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/

$page_security = 'HR_PAYSLIP';
$path_to_root="../..";
include($path_to_root . "/includes/session.inc");
add_access_extensions();
include($path_to_root . "/includes/ui.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/date_functions.inc");
include($path_to_root . "/modules/ExtendedHRM/includes/Payroll.inc");
include_once($path_to_root . "/admin/db/fiscalyears_db.inc");

if (!@$_GET['popup']){
	page(_("Advance Salary"));
} else
	page(_("Advance Salary"), true);
// page(_("Advance Salary"), @$_REQUEST['popup'], false, "", $js);

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>"));
 
check_db_has_salary_account(_("There are no Salary Account defined in this system. Kindly Open")." <a href='".$path_to_root."/modules/ExtendedHRM/manage/hrm_settings.php'>"._("Settings")."</a> "._("to update it."));

if(isset($_GET['Added'])){
	display_notification(sprintf(_('The Employee Advance Salary is added #%s'),$_GET['Added']));
}

if(isset($_GET['adv_id'])){
	$advance_row = GetRow('kv_empl_salary_advance', ['id' => $_GET['adv_id']] );
	$_POST['employee_id'] = $advance_row['empl_id'];
	$month = $_POST['month'] = $advance_row['month'];
	$year = $_POST['year'] = $advance_row['year'];
}
if (isset($_GET['employee_id'])){
	$_POST['employee_id'] = $_GET['employee_id'];
}
if (isset($_GET['month'])){
	$_POST['month'] = $_GET['month'];
}
if (isset($_GET['year'])){
	$_POST['year'] = $_GET['year'];
}

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

$employee_id = get_post('employee_id','');
$month = get_post('month','');
$year = get_post('year','');

if(list_updated('dates') || get_post('RefreshInquiry') || list_updated('employee_id')) {
		$month = date("m", strtotime($_POST['dates']));   
		$Ajax->activate('totals_tbl');
}
if(isset($_GET['adv_id']))
echo '<h4><center> Advance Payslip #'.$_GET['adv_id'].'</center></h4>';
div_start('totals_tbl');
	start_form();
		if (!isset($_GET['adv_id']) && db_has_employees()) {
			start_table(TABLESTYLE_NOBORDER);
			start_row();
			// kv_fiscalyears_list_cells(_("Fiscal Year").":", 'year', null, true);
			// kv_current_fiscal_months_list_cell(_("Months"), "month", null, true);
			//label_cells(_("Month"), )
			employee_list_cells(_("Select an Employee")." :", 'employee_id', null,	_("Select an Employee"), true, check_value('show_inactive'),false, false,true);
			date_cells(_("Date of Payment") . ":", 'dates', null, null, 0,0,0, null, true);			
			end_row();
			end_table();
			br();
			if (get_post('_show_inactive_update')) {
				$Ajax->activate('employee_id');
				// $Ajax->activate('month');
				// $Ajax->activate('year');
				$Ajax->activate('dates');
				set_focus('employee_id');
			}
		} 
		else {	
			hidden('employee_id');
			hidden('month');
			//hidden('year');
		}

		$month = (int)date('m', strtotime($_POST['dates']));
			$date = $_POST['dates'];
			$sql = "SELECT id FROM ".TB_PREF."fiscal_year WHERE begin <=". db_escape(date2sql($_POST['dates']))." AND end >=". db_escape(date2sql($_POST['dates']));
			$result = db_query($sql, "could not retrieve last fiscal years");
			$row = db_fetch($result);
			$sql = "SELECT MAX(`month`) as month FROM ".TB_PREF."kv_empl_salary WHERE year = ".db_escape($row['id'])." AND empl_id = ".db_escape($_POST['employee_id']);
 			$result = db_query($sql, "Could not retrieve salary");
			$payslip_month = db_fetch($result);

		if(isset($payslip_month) && ($payslip_month['month'] > $month) && !isset($_GET['adv_id'])){
			display_warning(_("You can't input advance salary for older months when the system processed new months."));

			$Ajax->activate('adv_tbl');
		}

		if(get_post('dates') || list_updated('dates')){
			$Ajax->activate('adv_tbl');
			$Ajax->activate('dates');
			$Ajax->activate('totals_tbl');
			// if(isset($_POST['dates'])){
			$day_of_month = date("m", strtotime($_POST['dates'])) ;
			// $current_date_of_month = array_search($day_of_month, $months);
			//$payslip_month = GetSingleValue('kv_empl_salary','month',array('month'=>(int)$day_of_month,'empl_id' =>$_POST['employee_id']));
			//}
		}
if(isset($payslip_month) && ($payslip_month['month'] > $month) && !isset($_GET['adv_id'])){ } else {
	$hrmsetup = HRM_Get_Options();
	$month = (int)$month= date("m", strtotime($_POST['dates']));
	$ext_year = date("Y", strtotime($_POST['dates']));
	if($hrmsetup['monthly_choice'] == 1){
			 $total_days =  31;
		for($kv=1; $kv<=$total_days; $kv++){						
			$th[] = $kv;
		}	
	}elseif($hrmsetup['monthly_choice'] == 2){
		$vj= 1;
		if($hrmsetup['BeginDay'] >= 1 && $hrmsetup['BeginDay'] < 31){
			$kv = $hrmsetup['BeginDay'];
			$kv_begin_days = $hrmsetup['BeginDay'];
			// $month=$year=0;
			$pre_mnth =  (($month > 1)? ($month-1) : 12);
			$total_days =  date("t", strtotime($ext_year."-".$month."-01"));
			for($kv; $kv<=$total_days; $kv++){		
				$th[] = $kv;
			}	
		}
					
		if($hrmsetup['EndDay'] < 31){ 
			$kv_end_days = $hrmsetup['EndDay'];
			$nxt_mnth =  (($month > 1)? ($month+1) : 12);

			for($kv=1;$kv<=$hrmsetup['EndDay'];$kv++){			
				$th[] = $kv;
			}
		}
	}elseif($hrmsetup['monthly_choice'] == 3){
		$vj= 1;
		if($hrmsetup['BeginDay'] >= 1 && $hrmsetup['BeginDay'] < 31){
			$kv = $hrmsetup['BeginDay'];
			$kv_begin_days = $hrmsetup['BeginDay'];
			// $month=$year=0;
			$pre_mnth =  (($month > 1)? ($month-1) : 12);
			$total_days =  date("t", strtotime($ext_year."-".$pre_mnth."-01"));
			for($kv; $kv<=$total_days; $kv++){		
				$th[] = $kv;
			}	
		}			
		if($hrmsetup['EndDay'] < 31){ 
			$kv_end_days = $hrmsetup['EndDay'];
			//$nxt_mnth =  (($month < 12)? ($month+1) : '1');
			for($kv=1;$kv<=$hrmsetup['EndDay'];$kv++){			
				$th[] = $kv;
			}
		}else
			$kv_end_days = $hrmsetup['EndDay'];
	}

	if($hrmsetup['monthly_choice'] == 1){
		// $date_range_months = sql2date(date("Y-m-d", strtotime($ext_year."-".$month."-01"))).' - '.sql2date(date("Y-m-t", strtotime($ext_year."-".$month."-01"))); 
		// $date_range_begin = sql2date(date("Y-m-d", strtotime($ext_year."-".$month."-01"))); 
		// $date_range_end = sql2date(date("Y-m-t", strtotime($ext_year."-".$month."-01"))); 
		$date_range_begin = begin_month($_POST['dates']);
		$date_range_end = end_month($_POST['dates']);
	} else
	if($hrmsetup['monthly_choice'] == 2){
		$date_range_begin = sql2date(date("Y-m-d", strtotime($ext_year."-".$month."-".$hrmsetup['BeginDay']))); 
		$date_range_end = sql2date(date("Y-m-d", strtotime($ext_year."-".$nxt_mnth."-".$kv_end_days)));
	} elseif($hrmsetup['monthly_choice'] == 3){
		$pre_mnth =  (($month > 1)? ($month-1) : 12);
		if($pre_mnth == 12 )
			$prev_ext_year = $ext_year-1;
		else
			$prev_ext_year = $ext_year;

		$total_days =  date("t", strtotime($prev_ext_year."-".$pre_mnth."-01"));

		$date_range_begin = sql2date(date("Y-m-d", strtotime($prev_ext_year."-".$pre_mnth."-".$kv_begin_days))); 
		$date_range_end =sql2date(date("Y-m-d", strtotime($prev_ext_year."-".$month."-".$kv_end_days))); 
	}
	//-----------------
	if($employee_id != ''){
		if(!isset($advance_row)){
			// $advance_salary = GetAll('kv_empl_salary_advance',array('empl_id'=> $employee_id, 'date'=>[date2sql($begin_month),'','<='],'date'=>[date2sql($end_month),'','>=']));
			$advance_salary = GetAll('kv_empl_salary_advance',array('empl_id'=> $employee_id));
			foreach($advance_salary as $ad_v_sal){	
				if(date2sql($date_range_begin) < $ad_v_sal['date'] && $ad_v_sal['date'] < date2sql($date_range_end))
					if($ad_v_sal['date'] > 1){
						$_POST['adv_id'] = $ad_v_sal['id'];
					}
			}
			if(isset($_POST['adv_id']))
				$advance_sal_row = GetRow('kv_empl_salary_advance',array('empl_id'=> $employee_id, 'id'=>$_POST['adv_id']));
		}else
			$advance_sal_row = $advance_row;

		// dev_display_error(GetRow('kv_empl_salary_advance', array('empl_id'=> $employee_id, 'date' =>date2sql($_POST['dates'])),null,null,null,true));
		if(isset($advance_sal_row) && $advance_sal_row != '')
			$advance_pay = $advance_sal_row['amount'];
		//if($advance_pay ){
		$job_row =  GetRow('kv_empl_job', array('empl_id' => $employee_id)); 
		$max_amount = (isset($job_row['gross']) ? $job_row['gross'] : 0);

		if(isset($job_row['currency']) && $job_row['currency'] != ''){
			$curr_code =  $job_row['currency'];
			$ex_dat = (isset($_POST['date']) ? sql2date($_POST['date']) : Today());
			$ex_rate = number_format(get_exchange_rate_from_home_currency($curr_code, $ex_dat), 4);
		} else{
			$curr_code = get_company_currency();
			$ex_rate = 1; 
		} 

		div_start('adv_tbl');
		//if(!isset($payslip_month) || isset($advance_sal_row['inactive']) && $advance_sal_row['inactive'] == 1){ //$payslip_month if start 
		if($employee_id != ''){
			start_table(TABLESTYLE);
					// $month_name = kv_month_name_by_id(get_post('month'));
			label_row(_("Employee No").":", $_POST['employee_id']);
			label_row(_("Employee Name").":", kv_get_empl_name($_POST['employee_id'],true));
			label_row(_("Max. Available").":", $max_amount);
			hidden('max_amount', $max_amount);
			hidden('ex_rate', $ex_rate);
			// label_row(_("Month of Payment").":", $month_name); 
					// if(isset($advance_sal_row['date'])){
					// 	label_row(_("Date of Payment"), sql2date($advance_sal_row['date']));
					// }else{
					// 	date_row(_("Date of Payment") . ":", 'dates');
					// }
			if(isset($advance_pay)){
				label_row(_("Bank"), GetSingleValue('bank_accounts', 'bank_name', ['id' => $advance_sal_row['bank_id']]));
			} else 
				kv_bank_accounts_list_row(_("Bank"), 'bank_id', null, false, false);
			if(isset($advance_pay)){
					label_row(_("Advance Amount"), $advance_pay);
					$paid_adv =GetSingleValue('kv_empl_salary', 'adv_sal', array('empl_id'=> $employee_id, 'month' => (int)$day_of_month));
				if($paid_adv){
					label_row(_("Status"), _("Paid and Payroll Processed"));
				} else {
					label_row(_("Status"), _("Just Paid"));
				}
				$submit = false;
				if(isset($advance_sal_row['payment'])){
					$bank_trans_details = GetRow('bank_trans',array('type' => ST_BANKPAYMENT,'trans_no' => $advance_sal_row['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"'));
				}
			}else{
				if(!isset($_GET['adv_id'])){
					$month = date("m", strtotime($_POST['dates']));
					$year = date("Y", strtotime($_POST['dates']));
				}
				if(db_has_employee_payslip($employee_id, $month, $year) == false ){
					text_row(_("Advance Amount"), 'adv_sal', null, 15, 20);
					textarea_row(_("Purpose"), 'purpose', null, 30, 5);
					$submit =  true;
				}else{
					label_row(_("Advance Amount"), _("Sorry, Payroll already Processed to this month"));
					$submit =  false;
				}
			}
			if(isset($advance_sal_row['description']))
				label_row(_("Purpose"), _($advance_sal_row['description']));						

			end_table();
			br();br();

				/*if($month == date('m'))
					$submit =  true;
				else
					$submit = false;
*/
			if($submit && !isset($advance_pay)){					
				submit_center('pay_adv_salary', _("Process Payout"), true, _("Payout to Employees"), 'default');					
			} else{
				br(2);	
				$result = get_gl_trans(ST_BANKPAYMENT, isset($advance_sal_row['payment']) ? $advance_sal_row['payment']:'');
					//submit_center('DeletePayslip', _("Delete"), true, _('Delete Payslip'), 'default');
				if (db_num_rows($result) == 0){
					echo "<p><center>"._("No general ledger transactions have been created for")."</center></p><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"), _("Memo"));
				else if ($dim == 1)
					$th = array(_("Account Code"),_("Account Name"),_("Dimension"),_("Debit"),_("Credit"),_("Memo"));
				else		
					$th = array(_("Account Code"), _("Account Name"), _("Debit"), _("Credit"), _("Memo"));
				$k = 0; //row colour counter
				$heading_shown = false;
				$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);
					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']);
					label_cell($myrow['memo_']);
					end_row();
					if ($myrow['amount'] > 0 ) 
						$debit += $myrow['amount'];
					else 
						$credit += $myrow['amount'];
				}
				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);
				}
					
			}
		}
	} else { 
		echo '<center><h4>'._("No Employee selected to Process Advance Salary").' </h4> </center>';
	}

	}//$payslip_month if end
	div_end();
	end_form();
		
div_end();

function can_process()
{
	if ($_POST['adv_sal'] == ""){
		display_error(_("Please Enter the Advance Salary."));
		set_focus('adv_sal');
		return false;
	}

	if ($_POST['bank_id'] == ""){
		display_error(_("Select a bank."));
		set_focus('bank_id');
		return false;
	}  

	return true;
}

	if(isset($_POST['pay_adv_salary']) && can_process() ) {	
		begin_transaction();	
		if( get_post('max_amount') >= get_post('adv_sal')){
			$id = Insert('kv_empl_salary_advance', array('empl_id' => $_POST['employee_id'], /*'month' => $_POST['month'], 'year' => $_POST['year'],*/ 'amount' => input_num('adv_sal'), 'description' => $_POST['purpose'], 'date' =>  array($_POST['dates'],'date'), 'bank_id' => $_POST['bank_id'] ) );

			$empl_name = kv_get_empl_name($_POST['employee_id']);
			$cart = new items_cart(ST_BANKPAYMENT);
			$cart->tran_date = $_POST['dates'];
			$cart->add_gl_item(get_hrm_option('adv_salary_account'), 0, 0, (input_num('adv_sal')*$ex_rate),'');
			$bank_id = write_bank_transaction(ST_BANKPAYMENT, 0, $_POST['bank_id'], $cart,$_POST['dates'], PT_EMPLOYEE, $_POST['employee_id'], 0, '', 'Employee Advance Salary #'.$_POST['employee_id'].'-'. $empl_name, true, null);

			if(isset($bank_id) && $bank_id[1] > 0)
				Update('kv_empl_salary_advance', array('id' => $id,'empl_id' => $_POST['employee_id']), array('payment' => $bank_id[1]));

			add_audit_trail(ST_EMPLOYEE_ADVANCE, $id, $_POST['dates']);

			// if(isset($_POST['bank_id']) && $_POST['bank_id'] > 0 ){
			// 	$bank_details = GetRow('bank_accounts', ['id' => $_POST['bank_id']]);
			// 	if(is_array($bank_details)){
			// 		add_bank_trans(ST_EMPLOYEE_ADVANCE, $id, $_POST['bank_id'], $_POST['employee_id'], Today(),	-(input_num('adv_sal')*$ex_rate), PT_EMPLOYEE, $_POST['employee_id']);
			// 		$BankGL = $bank_details['account_code'];
			// 		$hrmsetup = get_hrm_option();
			// 		$empl_name = kv_get_empl_name($_POST['employee_id']); 
			// 		if($BankGL && $hrmsetup['adv_salary_account']) {
			// 			add_gl_trans(ST_EMPLOYEE_ADVANCE, $id, Today(), $BankGL, 0,0, 'Employee Salary #'.$_POST['employee_id'].'-'. $empl_name, -(input_num('adv_sal')*$ex_rate));
			// 			add_gl_trans(ST_EMPLOYEE_ADVANCE, $id, Today(), $hrmsetup['adv_salary_account'], 0,0, 'Employee Salary #'.$_POST['employee_id'].'-'. $empl_name, (input_num('adv_sal')*$ex_rate), '', PT_EMPLOYEE, $_POST['employee_id']);
			// 		}
			// 	}
			// }
			commit_transaction();

			meta_forward($_SERVER['PHP_SELF'], "Added=$id&adv_id=".$id."&employee_id=".$_POST['employee_id'].'&dates='.$_POST['dates']);
		}else
		display_error(_("Sorry the Amount is more than the maximum Allowed amount"));
	}

end_page(@$_GET['popup'], false, false); ?>
<style>
	/*table { width: auto; }*/
</style>
