<?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" );

if (isset($_GET['vw']))
	$view_id = $_GET['vw'];
else
	$view_id = find_submit('view');
if ($view_id != -1){		//echo $view_id;
	$row =  GetRow('kv_empl_travel', array('id' => $view_id));
	if ($row['filename'] != ""){
		if(in_ajax()) {
			$Ajax->popup($_SERVER['PHP_SELF'].'?vw='.$view_id);
		} else {
			$type = ($row['filetype']) ? $row['filetype'] : 'application/octet-stream';	
    		header("Content-type: ".$type);
    		//header('Content-Length: '.$row['filesize']);
	    	
	 		header("Content-Disposition: inline");
	    	echo file_get_contents(company_path(). "/attachments/travel_bills/".$row['unique_name']);
    		exit();
		}
	}	
}
if (isset($_GET['dl']))
	$download_id = $_GET['dl'];
else
	$download_id = find_submit('download');

if ($download_id != -1){
	$row = GetRow('kv_empl_travel', array('id' => $download_id));
	if ($row['filename'] != ""){
		if(in_ajax()) {
			$Ajax->redirect($_SERVER['PHP_SELF'].'?dl='.$download_id);
		} else {
			$type = ($row['filetype']) ? $row['filetype'] : 'application/octet-stream';	
    		header("Content-type: ".$type);
	    	//header('Content-Length: '.$row['filesize']);
    		header('Content-Disposition: attachment; filename='.$row['filename']);
    		echo file_get_contents(company_path()."/attachments/travel_bills/".$row['unique_name']);
	    	exit();
		}
	}	
}

$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();
}
$help_context = _("Travel Claims");
page($help_context, 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 ($Mode == 'ADD_ITEM' || $Mode == 'UPDATE_ITEM'){
	if(!isset($max_image_size))
		$max_image_size = 500;
	$upload_file = "";
	if (isset($_FILES['kv_attach_name']) && $_FILES['kv_attach_name']['name'] != '') {
				
		$result = $_FILES['kv_attach_name']['error'];
		$upload_file = 'Yes'; 
		$attr_dir = company_path().'/attachments' ; 
		if (!file_exists($attr_dir)){				
			mkdir($attr_dir);
		}
		$dir = $attr_dir.'/travel_bills';
		if (!file_exists($dir)){
			mkdir($dir);
		}	
		$doc_ext = substr(trim($_FILES['kv_attach_name']['name']), strlen($_FILES['kv_attach_name']['name'])-3); 
		if($doc_ext == 'ocx' ) {
			$doc_ext = substr(trim($_FILES['kv_attach_name']['name']),strlen($_FILES['kv_attach_name']['name'])-4); 
		}

		$filename = basename($_FILES['kv_attach_name']['name']);
		$filesize = $_FILES['kv_attach_name']['size'];
		$filetype = $_FILES['kv_attach_name']['type'];
		
		if ($Mode == 'UPDATE_ITEM')	{
		    $row = GetRow('kv_empl_travel', array('id' => $selected_id));
		    if ($row['filename'] == "")
        		exit();
			$unique_name = $row['unique_name'];
			if ($filename && file_exists($dir."/".$unique_name))
				unlink($dir."/".$unique_name);
		}
		else
			$unique_name = uniqid();

		if ( $filesize > ($max_image_size * 1024)) { //File Size Check
			display_warning(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $max_image_size);
			$upload_file ='No';
		}elseif (file_exists($dir."/".$unique_name)){
			$result = unlink($dir."/".$unique_name);
			if (!$result) 	{
				display_error(_('The existing Bill could not be removed'));
				$upload_file ='No';
			}
		}
			
		if ($upload_file == 'Yes'){
			$result = move_uploaded_file($_FILES['kv_attach_name']['tmp_name'], $dir."/".$unique_name);			
		}
		//$Ajax->activate('_page_body');
	} else {
		if ($_POST['selected_id'] != -1) {
			$FileAttachment = GetRow('kv_empl_travel', array('id' => $_POST['selected_id']));

			$filename = $FileAttachment['filename'];
			$filetype = $FileAttachment['filetype'];
			$unique_name = $FileAttachment['unique_name']; 
		} else 
			$filename = $filetype =$unique_name = ''; 
	}
	$update = false;
	if ($_POST['selected_id'] != -1) {
		Update('kv_empl_travel', array('id' => $_POST['selected_id']), array('title' => $_POST['title'], 'status' => $_POST['status'], 'purpose' => $_POST['purpose'], 'travel_date' => array($_POST['travel_date'], 'date'), 'distance' => $_POST['distance'], 'amount' => input_num('amount'), 'from_place' => $_POST['from_place'], 'to_place' => $_POST['to_place'], 'mode' => $_POST['mode'], 'description'=> $_POST['description'], 'filename' => $filename, 'unique_name' => $unique_name, 'filetype' => $filetype, 'empl_id' => $_POST['empl_id']));

		$note = _("New Travel Bill has been Updated Successfully");
		$Allowance_id = $_POST['selected_id'];
		$update = true;
	} else{
		$Allowance_id = Insert('kv_empl_travel', array('title' => $_POST['title'], 'status' => $_POST['status'], 'purpose' => $_POST['purpose'], 'travel_date' => array($_POST['travel_date'], 'date'), 'distance' => $_POST['distance'], 'amount' => input_num('amount'), 'from_place' => $_POST['from_place'], 'to_place' => $_POST['to_place'], 'mode' => $_POST['mode'], 'description'=> $_POST['description'], 'filename' => $filename, 'unique_name' => $unique_name, 'filetype' => $filetype, 'empl_id' => $_POST['empl_id']));
		$note =  _("Travel 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){
		$travel_debit = GetSingleValue('kv_empl_option', 'option_value', array('option_name' => 'travel_debit'));
		if($travel_debit != ''){
			//display_notification($Allowance_id.'--'.$_POST['status']);
			//if($update)
				//Update('gl_trans', array('type' => 96, 'type_no' => $Allowance_id, 'amount' => array('0', '', '>')), array('amount' => input_num('amount'))); 
			//else			
				add_gl_trans(96, $Allowance_id, $_POST['date_of_pay'], $travel_debit, 0,0, 'Travel Allowance #'.$_POST['empl_id'].'-'. kv_get_empl_name($_POST['empl_id']), input_num('amount'));
		}

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

	display_notification($note);
	$Mode = 'RESET';
}

if ($Mode == 'Delete'){
	$row = GetRow('kv_empl_travel', array('id' => $selected_id));
	$dir =  company_path()."/attachments/travel_bills";
	if (file_exists($dir."/".$row['unique_name']))
		unlink($dir."/".$row['unique_name']);
	Delete('kv_empl_travel', array('id' => $selected_id));	
	display_notification(_("Travel Bill has been deleted.")); 
	$Mode = 'RESET';
}

if ($Mode == 'RESET'){
	unset($_POST['trans_no']);
	unset($_POST['description']);
	$selected_id = -1;
}

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

function display_rows(){}

//----------------------------------------------------------------------------------------
start_form(true);
	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, purpose, travel_date, filename, title, from_place, to_place, distance,  amount, mode, IF(status =0 , "Pending", IF(status = 1, "Accepted" , "Rejected")) FROM '.TB_PREF.'kv_empl_travel';
	if(get_post('empl_id') != ''){
		 $sql .=" WHERE empl_id=".db_escape(get_post('empl_id'));
	}

	$cols = array(
		_("#") => array('name'=>'id', 'ord'=>''),
		_("Travel Purpose") => array('name'=>'purpose'), 
	    _("Travel Date") => array('name'=>'travel_date', 'type'=>'date'),	
	    _("Filename") => array('name'=>'filename'),
	    _("Claim Title") => array('name'=>'title'),    
	    _("From Place") => array('name'=>'from_place'),
	    _("To Place") => array('name'=>'to_place'),
	    _("Distance") => array('name'=>'distance'),	    
	    _("Bill Amount") => array('name'=>'amount'),
	    _("Travel Mode") => array('name'=>'mode'),
	    _("Status") => array('name'=>'mode'),
	    	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_travel', $sql, $cols);
	$table->width = "80%";
	display_db_pager($table);
	
	br(2);	
	start_outer_table(TABLESTYLE2);
	$_POST['title']  = $_POST['purpose']= $_POST['mode'] = $_POST['description'] = $_POST['from_place']	=$_POST['to_place'] = $_POST['distance']=  '';
			$_POST['amount'] = 0;
	if ($selected_id != -1){
		if($Mode == 'Edit')	{		
			$row = GetRow('kv_empl_travel', array('id' => $selected_id));	

			$_POST['title']  		= $row["title"];
			$_POST['purpose']  		= $row["purpose"];
			$_POST['mode']  		= $row["mode"];
			$_POST['description']  	= $row["description"];
			$_POST['from_place']	= $row["from_place"];
			$_POST['to_place']  	= $row["to_place"];
			$_POST['distance']  	= $row["distance"];
			$_POST['amount'] 		= $row["amount"];
			$_POST['status'] 		= $row["status"];
			$_POST['travel_date']  	= sql2date($row["travel_date"]);				
		} 
	}
	hidden('selected_id', $selected_id);
	hidden('date_of_pay', Today());

	table_section(1);
	text_row_ex(_("Claim Title").':', 'title', 40);
	date_row(_("Travel Date") . ":", 'travel_date');
	text_row_ex(_("Travel Purpose").':', 'purpose', 40);
	travel_mode_list_row(_("Travel Mode").':', 'mode', $_POST['mode']);
	textarea_row(_("Description:"), 'description', $_POST['description'], 35, 5);
	kv_doc_row(_("Bill copy") . ":", 'kv_attach_name', 'kv_attach_name');
	
	table_section(2);
	text_row_ex(_("From Place").':', 'from_place', 40);
	text_row_ex(_("To Place").':', 'to_place', 40);
	text_row_ex(_("Distance").':', 'distance', 20);
	amount_row(_("Bill Amount").':', 'amount');

	$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_to']) && 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_outer_table(1);
	submit_add_or_update_center($selected_id == -1, '', 'process');
	br();
	if (!isset($empl_row['report_to']) && get_post('status') == 1 && $selected_id != -1){
		$result = get_gl_trans(96, $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();

end_page();

?>