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

$page_security = 'SA_OPEN';
$path_to_root="../..";

include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/admin/db/attachments_db.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");

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();
}
page(_("Petrol Allowance Claims"), false, false, "", $js);

simple_page_mode(true);

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

if(!isset($_POST['empl_id']) && isset($_GET['empl_id']))
	$_POST['empl_id'] = $_GET['empl_id'];

//----------------------------------------------------------------------------
if ($Mode == 'ADD_ITEM' || $Mode == 'UPDATE_ITEM'){

	$update = false;
	if ($_POST['selected_id'] != -1) {
		Update('kv_empl_petrol', array('id' => $_POST['selected_id']), array( 'travel_date' => array($_POST['travel_date'], 'date'), 'status' => $_POST['status'], 'distance' => $_POST['distance'], 'amount' => input_num('amount'), 'from_place' => $_POST['from_place'], 'to_place' => $_POST['to_place'], 'rate_per_hr' => $_POST['rate_per_hr'], 'description'=> $_POST['description'], 'empl_id' => $_POST['empl_id']));

		$note = _("New Petrol Bill has been Updated Successfully");
		$Allowance_id = $_POST['selected_id'];
		$update = true; 
	} else{
		$Allowance_id = Insert('kv_empl_petrol', array( 'travel_date' => array($_POST['travel_date'], 'date'), 'status' => $_POST['status'], 'distance' => $_POST['distance'], 'amount' => input_num('amount'), 'from_place' => $_POST['from_place'], 'to_place' => $_POST['to_place'], 'rate_per_hr' => $_POST['rate_per_hr'], 'description'=> $_POST['description'],  'empl_id' => $_POST['empl_id']));
		$note =  _("Petrol Bill has been Created Successfully.");
	}//kv_add_or_update_cv($empl_id, $_POST['empl_firstname'], $_POST['cv_title'], $kv_file_name ); 

	if($Allowance_id > 0 && $_POST['status'] == 1 && $_POST['pre_status'] != 1){
		$petrol_debit = GetSingleValue('kv_empl_option', 'option_value', array('option_name' => 'petrol_debit'));
		if($petrol_debit != ''){
			//if($update)
				//Update('gl_trans', array('type' => 95, 'type_no' => $Allowance_id, 'amount' => array('0', '', '>')), array('amount' => input_num('amount'))); 
			//else
				add_gl_trans(95, $Allowance_id, $_POST['date_of_pay'], $petrol_debit, 0,0, 'Petrol Allowance #'.$_POST['empl_id'].'-'. kv_get_empl_name($_POST['empl_id']), input_num('amount'));
		}

		$petrol_credit = GetSingleValue('kv_empl_option', 'option_value', array('option_name' => 'petrol_credit'));
		if($petrol_credit != '')
			//if($update)
				//Update('gl_trans', array('type' => 95, 'type_no' => $Allowance_id, 'amount' => array('0', '', '<')), array('amount' => -input_num('amount'))); 
			//else
				add_gl_trans(95, $Allowance_id, $_POST['date_of_pay'], $petrol_credit, 0,0, 'Petrol Allowance #'.$_POST['empl_id'].'-'. kv_get_empl_name($_POST['empl_id']), -input_num('amount'));
	}
	display_notification($note);
	meta_forward($_SERVER['PHP_SELF'], "empl_id=".$_POST['empl_id']);
}

if ($Mode == 'Delete'){
	
	Delete('kv_empl_petrol', array('id' => $selected_id));	
	display_notification(_("Petrol Bill has been deleted.")); 
	$Mode = 'RESET';
}

if ($Mode == 'RESET'){
	unset($_POST['distance']);
	unset($_POST['amount']);
	unset($_POST['rate_per_hr']);
	unset($_POST['description']);
	//unset($_POST['empl_id']);
	$selected_id = -1;	
	$Ajax->activate('totals_tbl');
}

//----------------------------------------------------------------------------------------
$empl_id = get_post('empl_id');

function edit_link($row){
  	return button('Edit'.$row["id"], _("Edit"), _("Edit"), ICON_EDIT);
}

function view_link($row){
  	return button('view'.$row["id"], _("View"), _("View"), ICON_VIEW);
}

function download_link($row){
  	return button('download'.$row["id"], _("Download"), _("Download"), ICON_DOWN);
}

function delete_link($row){
  	return button('Delete'.$row["id"], _("Delete"), _("Delete"), ICON_DELETE);
}

//----------------------------------------------------------------------------------------
 $_POST['description'] = $_POST['from_place']=$_POST['to_place']='';
	
div_start('totals_tbl');
start_form();
	if (db_has_employees()) {

		$empl_row = GetRow('kv_empl_info',array('user_id' => $_SESSION['wa_current_user']->user));		

		if(is_array($empl_row) && $empl_row['report_to'] == ''){
			$_POST['empl_id'] =  $empl_row['empl_id'];
			hidden('empl_id' , $empl_row['empl_id']);
		} else{
			start_table(TABLESTYLE_NOBORDER);
				employee_list_row(_("Select an Employee: "), 'empl_id', null, _('Select Employee'), true, check_value('show_inactive'));			
			end_table();
		}
	} else{
		display_warning(_("No employee in the system"));
	}

	$sql = 'SELECT id, travel_date, from_place, to_place, distance, rate_per_hr, amount, IF(status =0 , "Pending", IF(status = 1, "Accepted" , "Rejected")) FROM '.TB_PREF.'kv_empl_petrol ';
if(get_post('empl_id') != ''){
	 $sql .=" WHERE empl_id=".db_escape(get_post('empl_id'));
}
	$cols = array(
		_("#") => array('name'=>'id', 'ord'=>''),
	    _("Journey Date") => array('name'=>'travel_date', 'type'=>'date'),  
	    _("Source (From)") => array('name'=>'from_place'),
	    _("Destination (To)") => array('name'=>'to_place'),
	    _("Distance(km)") => array('name'=>'distance'),	    
	    _("Rate Per Hour") => array('name'=>'rate_per_hr'),	    
	    _("Bill Amount") => array('name'=>'amount'),
	    _("Status") => array('name'=>'amount'),
	    	array('insert'=>true, 'fun'=>'edit_link'),
	    	array('insert'=>true, 'fun'=>'view_link'),
	    	array('insert'=>true, 'fun'=>'download_link'),
	    	array('insert'=>true, 'fun'=>'delete_link')
	);	
	$table =& new_db_pager('kv_empl_petrol', $sql, $cols);
	$table->width = "80%";
	display_db_pager($table);

	br(2);	
	if( ( get_post('RefreshInquiry') || get_post('distance') ) && input_num('distance') > 0 ) {		
		$_POST['amount'] = input_num('rate_per_hr') * input_num('distance');
		$Ajax->activate('PetrolAllowance');
	}

	div_start('PetrolAllowance');
	start_table(TABLESTYLE2);
	
	if ($selected_id != -1){
		if($Mode == 'Edit')	{		
			$row = GetRow('kv_empl_petrol', array('id' => $selected_id));	

			$_POST['description']  	= $row["description"];
			$_POST['from_place']	= $row["from_place"];
			$_POST['to_place']  	= $row["to_place"];
			$_POST['distance']  	= $row["distance"];
			$_POST['rate_per_hr']  	= $row["rate_per_hr"];
			$_POST['amount'] 		= $row["amount"];
			$_POST['status'] 		= $row["status"];
			$_POST['travel_date']  	= sql2date($row["travel_date"]);				
		} else 
			$_POST['rate_per_hr'] = get_post('rate_per_hr'); 
	}else 
		$_POST['rate_per_hr'] = get_post('rate_per_hr'); 

	hidden('selected_id', $selected_id);
	hidden('date_of_pay', Today());
	
	kv_rate_per_hour_row(_("Travel mode").':', 'rate_per_hr', null, true);
	kv_basic_row(_("Distance(Km)").':', 'distance', 20, 100, null, true);
	if( get_post('rate_per_hr') || get_post('distance') || get_post('RefreshInquiry')) {
		$_POST['amount'] = input_num('rate_per_hr') * input_num('distance');
	}
	hidden('amount', input_num('amount'));
	label_row(_("Bill Amount").':', input_num('amount'), null);
	date_row(_("Date of Journey") . ":", 'travel_date');
	textarea_row(_("Description:"), 'description', $_POST['description'], 30, 5);
	
	text_row_ex(_("Source (From)").':', 'from_place', 30);
	text_row_ex(_("Destination (To)").':', 'to_place', 30);
	//text_row_ex(_("Distance").':', 'distance', 20, 20, '', null, null, ' KM ');	

	$report_to = GetSingleValue('kv_empl_info', 'report_to', array('empl_id' => get_post('empl_id')));
	label_row(_("Report To:"), GetSingleValue('kv_empl_info', 'CONCAT(`empl_firstname`, " ", `empl_lastname`)', array('	empl_id' => $report_to)));
	
	if(!isset($empl_row['report']) && get_post('status') != 1){
		accept_reject_pending_list_row(_("Status"), 'status');
		hidden('pre_status', $_POST['status']);
	} else{
		label_row(_('Status'), (isset($_POST['status']) ? ( $_POST['status'] == 1 ? 'Accepted' : ($_POST['status'] == 0 ? 'Pending' : ($_POST['status'] == 2 ? 'Rejected' : ('-')))  )  :   'Pending' ) );
		hidden('status', isset($_POST['status']) ? $_POST['status'] : 0);
	}
	
	end_table(1);
	div_end();
	submit_add_or_update_center($selected_id == -1, '', 'process');
	br();
	if (!isset($empl_row['report']) && get_post('status') == 1 && $selected_id != -1){
		$result = get_gl_trans(95, $selected_id);

		if (db_num_rows($result) == 0){
			echo "<p><center>"._("No general ledger transactions have been created for")."</center></p><br>";
				//end_page(true);
				//exit;
		}else {

			/*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);
			}
		}
	}

end_form();
div_end();
end_page();

?>