<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
ob_start();
include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');
?>

<script src="angular/angular.min.js"></script>  

<?php
//this is where you paste. Below paste it:

if ($userid == 'admin' || $userid == 'pchand' || $userid == 'jprasad'  || $userid == 'nisha' || $userid == 'clorissa'  || $userid == 'mkhan' || $userid == 'schand'  ) {

echo '<p class="page_title_text"><img alt="" src="' . $RootPath . '/css/' . $Theme .
		'/images/maintenance.png" title="' .
		_('Import Manual Tech Timesheet Data from CSV file') . '" />' . ' ' .
		_('Import Manual Tech Timesheet Data from CSV file') . '</p>';

$currentdate = date('Y-m-d h:i:s', time());

if (isset($_FILES['CostUpdateFile']) and $_FILES['CostUpdateFile']['name']) { //start file processing
	//check file info
	$FileName = $_FILES['CostUpdateFile']['name'];
	$TempName  = $_FILES['CostUpdateFile']['tmp_name'];
	$FileSize = $_FILES['CostUpdateFile']['size'];
	$InputError = 0;

	//get file handle
	$FileHandle = fopen($TempName, 'r');

	//get the header row
	$HeadRow = fgetcsv($FileHandle, 10000, ',');

	// Arrays to track successful and failed imports
	$successfulImports = array();
	$failedImports = array();
	
	//start database transaction
	DB_Txn_Begin();

	//loop through file rows
	$LineNumber = 2;
	while ( ($myrow = fgetcsv($FileHandle, 10000, ',')) !== FALSE ) {

		// Check if employee exists and is Active
		$sqlCheckEmployee = "SELECT employeeid, base_wage_rate, status 
							 FROM employeemaster 
							 WHERE employeeid = '" . DB_escape_string($myrow[1]) . "'";
		
		$resultCheckEmployee = DB_query($sqlCheckEmployee);
		
		if (DB_num_rows($resultCheckEmployee) == 0) {
			// Employee not found
			$failedImports[] = array(
				'line_number' => $LineNumber,
				'employee_id' => $myrow[1],
				'reason' => 'Employee not found in system',
				'full_row' => $myrow
			);
			$LineNumber++;
			continue;
		}
		
		$employeeData = DB_fetch_array($resultCheckEmployee);
		
		if ($employeeData['status'] != 'Active') {
			// Employee is not Active
			$failedImports[] = array(
				'line_number' => $LineNumber,
				'employee_id' => $myrow[1],
				'reason' => 'Employee status is: ' . $employeeData['status'],
				'full_row' => $myrow
			);
			$LineNumber++;
			continue;
		}
		
		// Employee is Active, proceed with import
		$baserate = $employeeData['base_wage_rate'];	
		
		$totalnormalamount = $myrow[5] * $baserate;
		$totaltimeandhalfamount = $myrow[6] * (1.5 * $baserate);
		$totaldoubleamount = $myrow[7] * (2 * $baserate);
		$totalpublicholidayamount = $myrow[11] * $baserate;
		$leavecost = $myrow[14] * $baserate;
		
		$cost = $totalnormalamount + $totaltimeandhalfamount + $totaldoubleamount + $totalpublicholidayamount + $leavecost + $myrow[8] + $myrow[10] + $myrow[9];
		$cost1 = $totalnormalamount + $totaltimeandhalfamount + $totaldoubleamount + $totalpublicholidayamount + $leavecost;
		
		$fnpfcost = $cost1 * 0.10;
		$levycost = $cost1 * 0.01;
		$fnpfcostlevy = $fnpfcost + $levycost;
		$totalcost = $cost + $fnpfcostlevy;
		
		// Get GL code
		$sql41 = "SELECT glcode
				  FROM labourcodes   
				  WHERE code = '" . DB_escape_string($myrow[2]) . "'";
		
		$ErrMsg = _('This customer could not be added because');
		$result41 = DB_query($sql41, $ErrMsg);
		
		$myrow41 = DB_fetch_array($result41);
		$glcode = $myrow41['glcode'];
		
		// Insert into manual_tech_timesheet
		$SQLstockmoves = "INSERT INTO manual_tech_timesheet (id,
											employeeid,
											labourcode,
											glcode,
											th,
											nt,
											timehalf,
											dt,
											meal,
											stay_away,
											call_out_allowances,
											premium,
											leave_type,
											leave_days,
											leave_hours,
											olddepartment,
											department,
											cost,
											fnpf,
											tpaf,
											fnpf_and_levy_cost,
											cost_including_fnpf,
											remarks,
											batch_no)
					VALUES ('" . DB_escape_string($myrow[0]) . "',
							'" . DB_escape_string($myrow[1]) . "',
							'" . DB_escape_string($myrow[2]) . "',
							'" . DB_escape_string($glcode) . "',
							'" . DB_escape_string($myrow[4]) . "',
							'" . DB_escape_string($myrow[5]) . "',
							'" . DB_escape_string($myrow[6]) . "',
							'" . DB_escape_string($myrow[7]) . "',
							'" . DB_escape_string($myrow[8]) . "',
							'" . DB_escape_string($myrow[9]) . "',
							'" . DB_escape_string($myrow[10]) . "',
							'" . DB_escape_string($myrow[11]) . "',
							'" . DB_escape_string($myrow[12]) . "',
							'" . DB_escape_string($myrow[13]) . "',
							'" . DB_escape_string($myrow[14]) . "',
							'" . DB_escape_string($myrow[15]) . "',
							'" . DB_escape_string($myrow[16]) . "',
							'" . $cost . "',
							'" . $fnpfcost . "',
							'" . $levycost . "',
							'" . $fnpfcostlevy . "',
							'" . $totalcost . "',
							'" . DB_escape_string($myrow[17]) . "',
							'" . DB_escape_string($myrow[18]) . "')";
		
		$ErrMsg = _('Manual Tech Timesheet data Failed');
		$DbgMsg = _('The SQL that failed was');
		$Result = DB_query($SQLstockmoves, $ErrMsg, $DbgMsg, true);
		
		if ($Result) {
			$successfulImports[] = array(
				'line_number' => $LineNumber,
				'employee_id' => $myrow[1]
			);
		}

		$LineNumber++;
	}

	DB_Txn_Commit();
	fclose($FileHandle);
	
	// Display results
	$successCount = count($successfulImports);
	$failedCount = count($failedImports);
	
	echo '<div class="centre">';
	echo '<h3>Import Summary</h3>';
	echo '<p><strong>File:</strong> ' . htmlspecialchars($FileName) . '</p>';
	echo '<p><strong>Successfully Imported:</strong> <span style="color: green;">' . $successCount . ' records</span></p>';
	echo '<p><strong>Failed Imports:</strong> <span style="color: red;">' . $failedCount . ' records</span></p>';
	
	if ($successCount > 0) {
		prnMsg(_('Batch Update of Manual Tech Timesheet') . ' ' . $FileName . ' ' . _('has been completed. ') . $successCount . _(' transactions committed to the database.'), 'success');
	}
	
	// Display failed imports
	if ($failedCount > 0) {
		echo '<div style="margin-top: 20px; padding: 15px; border: 2px solid #ff0000; background-color: #ffeeee;">';
		echo '<h4 style="color: #cc0000;">Failed Imports - Inactive or Non-existent Employees</h4>';
		echo '<table border="1" cellpadding="5" cellspacing="0" style="width: 100%; margin-top: 10px;">';
		echo '<thead>';
		echo '<tr style="background-color: #ffcccc;">';
		echo '<th>Line Number</th>';
		echo '<th>Employee ID</th>';
		echo '<th>Reason</th>';
		echo '</tr>';
		echo '</thead>';
		echo '<tbody>';
		
		foreach ($failedImports as $failed) {
			echo '<tr>';
			echo '<td>' . htmlspecialchars($failed['line_number']) . '</td>';
			echo '<td>' . htmlspecialchars($failed['employee_id']) . '</td>';
			echo '<td>' . htmlspecialchars($failed['reason']) . '</td>';
			echo '</tr>';
		}
		
		echo '</tbody>';
		echo '</table>';
		
		// Create download link for failed records
		$_SESSION['failed_tech_imports'] = $failedImports;
		$_SESSION['failed_tech_imports_header'] = $HeadRow;
		
		echo '<p style="margin-top: 15px;">';
		echo '<a href="' . htmlspecialchars($_SERVER['PHP_SELF']) . '?download_failed_tech=1" style="padding: 10px 20px; background-color: #cc0000; color: white; text-decoration: none; border-radius: 5px; display: inline-block;">';
		echo 'Download Failed Records (CSV)';
		echo '</a>';
		echo '</p>';
		echo '</div>';
	}
	
	echo '</div>';

} elseif (isset($_GET['download_failed_tech']) && isset($_SESSION['failed_tech_imports'])) {
	// Generate CSV file for download
	$filename = 'failed_tech_imports_' . date('Y-m-d_His') . '.csv';
	
	header('Content-Type: text/csv');
	header('Content-Disposition: attachment; filename="' . $filename . '"');
	
	$output = fopen('php://output', 'w');
	
	// Add header row
	$headerRow = $_SESSION['failed_tech_imports_header'];
	$headerRow[] = 'Line Number';
	$headerRow[] = 'Failure Reason';
	fputcsv($output, $headerRow);
	
	// Add failed records
	foreach ($_SESSION['failed_tech_imports'] as $failed) {
		$row = $failed['full_row'];
		$row[] = $failed['line_number'];
		$row[] = $failed['reason'];
		fputcsv($output, $row);
	}
	
	fclose($output);
	
	// Clear session data
	unset($_SESSION['failed_tech_imports']);
	unset($_SESSION['failed_tech_imports_header']);
	
	exit;
} else { //show file upload form

	echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post" enctype="multipart/form-data">';
	echo '<div class="centre">';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	
	echo '<br /><input type="hidden" name="MAX_FILE_SIZE" value="1000000" />' . _('Upload file') . ': <input name="CostUpdateFile" type="file" />
			<input type="submit" name="submit" value="' . _('Send File') . '" />
		</div>
		</form>';
		
	echo '<div style="margin-top: 20px; padding: 15px; border: 1px solid #ccc; background-color: #f9f9f9;">';
	echo '<h4>Important Notes:</h4>';
	echo '<ul>';
	echo '<li>Only employees with <strong>Active</strong> status will be imported.</li>';
	echo '<li>Any records with inactive or non-existent employees will be logged and available for download.</li>';
	echo '<li>You will receive a summary report after the import completes.</li>';
	echo '</ul>';
	echo '</div>';
}

}
			  
echo '</div>';
?>

<!-- Rest of the HTML and JavaScript remains the same -->
<div id="m_scroll_top" class="m-scroll-top">
	<i class="la la-arrow-up"></i>
</div>

<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

<?php
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){
	$_SESSION['Module'] = $_GET['Application'];
}

function GetRptLinks($GroupID) {
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) {
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']);
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>

<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>

<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       </div>
    </div>
   </div>
 </div>

<script>
jQuery(document).ready(function($){
	$(".xcrud").on("change","#internal",function(){ 
     var internal = $("#internal").val();
        if(internal != 0)
       {
		 $('#sectors').attr("disabled", true);
         $('#patrollocation').attr("disabled",true);
		 $('#account').attr("disabled", true);
       }
	else{
		 $('#sectors').attr("disabled", false);
         $('#patrollocation').attr("disabled",false);
		 $('#account').attr("disabled", false)
	}
   });
	
	$(".xcrud").on("change","#monout",function(){ 
     var start_time = $("#monin").val();
	 var end_time = $("#monout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclash.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });

	$(".xcrud").on("change","#tuesout",function(){ 
     var start_time = $("#tuesin").val();
	 var end_time = $("#tuesout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashtues.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
	
	$(".xcrud").on("change","#wedout",function(){ 
     var start_time = $("#wedin").val();
	 var end_time = $("#wedout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashwed.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
	
	$(".xcrud").on("change","#thursout",function(){ 
     var start_time = $("#thursin").val();
	 var end_time = $("#thursout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashthurs.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
	
	$(".xcrud").on("change","#friout",function(){ 
     var start_time = $("#friin").val();
	 var end_time = $("#friout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashfri.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
	
	$(".xcrud").on("change","#satout",function(){ 
     var start_time = $("#satin").val();
	 var end_time = $("#satout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsat.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
	
	$(".xcrud").on("change","#sunout",function(){ 
     var start_time = $("#sunin").val();
	 var end_time = $("#sunout").val();
	 var rosterid = $("#rosterid").val();
	 var employeeid = $("#employeeid").val();
		if ( end_time <= start_time){
		   alert('Time logged out has to be greater than Time logged in ');
	   }
		
	   $.ajax({
      url:'hrms/CheckEmployee-timeclashsun.php',
      method:"POST",
      data:{start_time:start_time,end_time:end_time,rosterid:rosterid,employeeid:employeeid},
      success:function(data)
     {
	   var data = JSON.parse(data);
	    console.log(data);
        if(data != 0)
       {
       alert('CLASH!This employee is already rostered in another location/post at these selected times. Please choose another employee before proceeding. Full Details where they are rostered at :ROSTERID:'+ data);
       }
      }
     })  
   });
}); 
</script>

<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>