<?php 
    // continue the session
    session_start();
    
    // Determine if the form was submitted recently
    if ((!isset($_POST['formSubmitted']) || 
         !htmlspecialchars($_POST['formSubmitted'])=='TRUE') && !isset($_GET['timecardUserID'])){
        // Require the login since we are not submitting the form
        require_once('php_only_scripts/protector.php');
    }
    
    //include file
    include_once 'php_only_scripts/user_agent.php';

    // Init some variables
    $userRow=null;
    $timecardUserAssocRow=null;
    $timecardUserID=-1;
    $clockID=-1;
    $payDateStart=null;
    $fromEditButton='FALSE';
    $justClockedIn=0;

    // Assume NOT gtg
    $gtg = false;
    
    // Add includes to PHP files that I will need to access
    require_once 'php_only_scripts/database.php';
    require_once 'php_only_scripts/presentation.php';
    include 'php_only_scripts/global_after_session.php';
    include 'php_only_scripts/global_functions.php';
    include 'php_only_scripts/timecards_presentation.php';

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());
    
    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        exit;
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        //create an instance of UserAgent class
        $ua = new UserAgent();

        // If site is accessed from mobile, then redirect to the page stating 
        // mobile devices are not useable here
        //.
        if($ua->is_mobile() && 
           $userRow["SUEmployee"]==1 &&
           $userRow["UserLevel"]!='SU' &&
           $userRow["UserLevel"]!='EXECUTIVE' ||
           $userRow["AccountStatus"]!='ACTIVE'){
                // Redirect to the site informing them
                echo ('<script>window.location = "invalid_device.php";</script>');

                // Exit out of any more code execution
                exit;
        }
    
        // Determine if a user ID sent in the URL
        if (isset($_GET['timecardUserID']) ){
            // Hold onto the Timecard user ID to be used
            $timecardUserID = $_GET['timecardUserID'];
        }
        else {
            // Determine if a user ID sent in a post
            if (isset($_POST['UserID']) ){
                // Hold onto the Timecard user ID to be used
                $timecardUserID = $_POST['UserID'];
            }
            else {
                // Hold onto the Timecard user ID to be used
                $timecardUserID = $userRow['UserID'];
            }
        }

        // Determine if a clock ID sent in a post
        if (isset($_POST['clockID']) ){
            // Hold onto the Timecard clock ID to be used
            $clockID = htmlspecialchars($_POST['clockID'], ENT_QUOTES, 'UTF-8');
        }

        // Determine if a pay date sent in a post
        if (isset($_POST['payDateStart']) ){
            // Hold onto the pay date to be used
            $payDateStart=str_replace(" ","T",htmlspecialchars($_POST['payDateStart']));
        }

        // Determine if a From Edit sent in a post
        if (isset($_POST['fromEditButton']) ){
            // Hold onto the From Edit value to be used
            $fromEditButton = htmlspecialchars($_POST['fromEditButton'], ENT_QUOTES, 'UTF-8');
        }
        
        // Create a query to to get timecard user information on the passed in timecard user
        $sql = 'SELECT * FROM users u ' .
               'WHERE u.UserID=' . $timecardUserID . ';';

        // Attempt to get the timecard user row
        $timecardUserRow = $db->queryDB($sql, $userRow, "updateTimecard Form occurance 1");

        // Attempt to get the timecard user row
        $timecardUserAssocRow = $timecardUserRow->fetch_assoc();

        // Determine if this user is allowed here or not
        if ($userRow["CompanyID"]==1 &&
            ($userRow["UserLevel"]=='SU' ||
             ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==$timecardUserAssocRow["CompanyID"]) ||
             ($userRow["UserID"]==$timecardUserAssocRow["UserID"]))){
            // Set the good to go until they log out
            $gtg = true;
        
            // Determine if the form was submitted recently
            if (isset($_POST['formSubmitted']) && 
                htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
                // Determine what the user preference is for tasks.  Set to machining as default
                $ts=1;
                switch ($userRow["PrimaryTaskType"]) {
                    case 'DESIGNING':
                        // Set to desiging tasks
                        $ts=2;

                        // Leve this case statement
                        break;
                    case 'PROGRAMMING':
                        // Set to programming tasks
                        $ts=3;

                        // Leve this case statement
                        break;
                    case 'IN-HOUSE':
                        // Set to in-house tasks
                        $ts=4;

                        // Leve this case statement
                        break;
                    default:
                        break;
                }

                // Set the place to be redirected to to be the tasks page
                $redirectTo='tasks.php?ts=' . $ts;
                
                // Determine if they are clockin only user
                if ($userRow["UserLevel"]=='TIMECARD ONLY'){
                    // Set the place to be redirected to to be the clocked statuses page
                    $redirectTo='clockedStatus.php';
                }


                // Determine if this user can even modify
                if (!$userRow["CanModify"]){
                    // Let them know they cannot modify
                    echo '<script> alert("Your profile does not allow you to modify.\nContact a higher level to request this privilege.");</script>'; 

                    // redirect to the tasks page
                    echo ('<script>window.location = "' . $redirectTo . '";</script>');
                }
                else {
                    // Set the local variables from what was posted for the timecard table
                    if ($clockID==-1) {$clockID = htmlspecialchars($_POST['clockID'], ENT_QUOTES, 'UTF-8');}
                    $companyID = htmlspecialchars($_POST['CompanyID'], ENT_QUOTES, 'UTF-8');
                    $userID = $timecardUserID;
                    $taskID = htmlspecialchars($_POST['TaskID'], ENT_QUOTES, 'UTF-8');
                    $startLocation = htmlspecialchars($_POST['StartLocation'], ENT_QUOTES, 'UTF-8');
                    $endLocation = htmlspecialchars($_POST['EndLocation'], ENT_QUOTES, 'UTF-8');
                    $startTime=str_replace("T"," ",htmlspecialchars($_POST['StartTime']));
                    $endTime=str_replace("T"," ",htmlspecialchars($_POST['EndTime']));
                    $beforeEndTime=str_replace("T"," ",htmlspecialchars($_POST['BeforeEndTime']));
                    $ratePercentage = htmlspecialchars($_POST['RatePercentage'], ENT_QUOTES, 'UTF-8');
                    $payDateStart=str_replace("T"," ",htmlspecialchars($_POST['PayDateStart'], ENT_QUOTES, 'UTF-8'));
                    $laborCategory=htmlspecialchars($_POST['laborCategory'], ENT_QUOTES, 'UTF-8');

                    // Set the local variables from what was posted for the users table
                    $payPeriod = htmlspecialchars($_POST['PayPeriod'], ENT_QUOTES, 'UTF-8');

                    // Determine if this is just an edit from a SU or Exec
                    if ($fromEditButton=="TRUE"){
                        // First create a query to determine if this conflicts with another range
                        $sql='SELECT * FROM laborclock ' .
                             'WHERE  ((StartTime BETWEEN "' . $startTime. '" AND "' . $endTime . '") ' .
                             '        OR  (EndTime BETWEEN "'. $startTime . '" AND "' . $endTime . '")) ' .
                             'AND UserID=' . $timecardUserID . ' ' .
                             'AND ClockID<>' . $clockID . ';';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
                        // Get any rows that are returned
                        $conflictingTimecardRecords = $db->queryDB($sql, $userRow, "updateTimecard Form occurance 1");

                        // Determine if there are any rows, because this would be bad.
                        if (mysqli_num_rows($conflictingTimecardRecords)>0){
                            // Let the user know that they are trying to add through existing pay ranges
                            echo '<script>alert("The pay range that you are updating will conflict with others.  This is not allowed. Labor clock row was NOT updated in the database. Please check the data and try again.");</script>';
                        }
                        else {
                            // Create a query to determine if the labor category uses PTO
                            $sql='SELECT * FROM laborcategories WHERE LaborCategoryID=' . $laborCategory . ';';

                            // Get any rows that are returned
                            $laborCategoryInfoRow = $db->queryDB($sql, $userRow, "addTimecard Form occurance 2");

                            // Determine if there is a row for this category
                            $usesPTO=0;
                            if (mysqli_num_rows($laborCategoryInfoRow)>0){
                                // Attempt to get the labor category row as array
                                $laborCategoryInfoAssocRow = $laborCategoryInfoRow->fetch_assoc();

                                // Fill the variables in properly now
                                $usesPTO = $laborCategoryInfoAssocRow["UsesPTO"];
                            }

                            // Now determine if this type uses PTO
                            $okToInsertRow=true;
                            if ($usesPTO==1){
                                // Create a query to get the user's PTO balance
                                $sql='SELECT * FROM employeebenefits WHERE UserID=' . $timecardUserID . ';';

                                // Get any rows that are returned
                                $userBenefitsRow = $db->queryDB($sql, $userRow, "addTimecard Form occurance 3");

                                // Determine if there is a row for the benefits
                                $ptoBalance=0;
                                if (mysqli_num_rows($userBenefitsRow)>0){
                                    // Attempt to get the labor category row as array
                                    $userBenefitsAssocRow = $userBenefitsRow->fetch_assoc();

                                    // Fill the variables in properly now
                                    $ptoBalance = $userBenefitsAssocRow["PTOBalance"];
                                }

                                // Put the two strings as dates. 
                                $startTimeDateTime=strtotime($_POST['StartTime']);
                                $endTimeDateTime=strtotime($_POST['EndTime']);

                                // Get the difference in hours of the two dates.  We need this for comparison of PTO left.
                                $ptoHoursDifference=($endTimeDateTime - $startTimeDateTime)/60/60;

                                // Now determine if the user has enough PTO to allow for this insert
                                if ($ptoBalance<$ptoHoursDifference){
                                    // Inform the user that they cannot enter this time for the user because they do not have enough PTO
                                    echo '<script>alert("The pay frame that you are trying to update is in the PTO category. This user does not have enough PTO hours. You are trying to enter ' . $ptoHoursDifference . ' hours and this user only has ' . $ptoBalance . ' Hours. Aborting entry.");</script>';

                                    // Set the flag to stop the insert
                                    $okToInsertRow=false;
                                }
                            }

                            // Determine if we are OK to enter
                            if ($okToInsertRow){
                                // Determine if they are changing the end time
                                $clockedStateSQL="";
                                if ($beforeEndTime==null &&
                                    $endTime!=null){
                                    // create an sql to clock them out as clocked out
                                    $clockedStateSQL = ', CurrentLaborCategoryID=(SELECT LaborCategoryID FROM laborcategories WHERE Name="Clocked Out") ' .
                                                       ', CurrentLaborCategoryStartTime=CURRENT_TIMESTAMP ';
                                }

                                // Let's create the update query off of what we have
                                $sql='UPDATE laborclock SET ';
                                $sql = $sql . 'CompanyID=' . $companyID;
                                if ($taskID!=null) {$sql = $sql . ', TaskID=' . $taskID;}
                                if ($startTime!=null) {$sql = $sql . ', StartTime="' . $startTime . '"';}
                                if ($endTime!=null) {$sql = $sql . ', EndTime="' . $endTime . '"';}
                                if ($startLocation!=null) {$sql = $sql . ', StartLocation="' . $startLocation . '"';}
                                if ($endLocation!=null) {$sql = $sql . ', EndLocation="' . $endLocation . '"';}
                                if ($ratePercentage!=null) {$sql = $sql . ', RatePercentage=' . $ratePercentage;}
                                if ($payPeriod!=null) {$sql = $sql . ', RatePercentage=' . $ratePercentage;}
                                if ($payDateStart!=null) {$sql = $sql . ', PayDateStart="' . $payDateStart . '"';}
                                if ($laborCategory!=null) {$sql = $sql . ', CurrentLaborCategoryID="' . $laborCategory . '"';}
                                $sql = $sql . $clockedStateSQL;
                                $sql=$sql .' WHERE ClockID=' . $clockID . ';';

                                // Attempt to run the query and evaluate the response
                                if (!$db->queryDB($sql, $userRow, "updateTimecard Form occurance 2")){
                                    echo '<script>alert("Timecard was NOT updated in the database. Please check the data and try again.");</script>';
                                }
                                else {
                                    // Let's create the update query off of what we have
                                    $sql='UPDATE users SET ';
                                    $sql = $sql . 'PayPeriod="' . $payPeriod . '" ';
                                    $sql=$sql .'WHERE UserID=' . $userID . ';';

                                    // Attempt to run the query and evaluate the response
                                    if (!$db->queryDB($sql, $userRow, "updateTimecard Form occurance 3")){
                                        echo '<script>alert("Timecard was NOT updated in the database. Please check the data and try again.");</script>';
                                    }
                                    else {
                                        // Determine if this is just an edit from a SU or Exec
                                        if ($fromEditButton=="TRUE"){
                                            // redirect to the full timecard page
                                            echo ('<script>window.location = "paydateHours.php?timecardUserID=' . $timecardUserID . '&paydateStart=' . $payDateStart . '";</script>');
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else{
                        // Ensure that we have a company ID and a user ID before we do any of this
                        if ($companyID!=null &&
                            $userID>0){
                            // Create the current time in the timezone that we are at
                            $currentTime = (new DateTime())->modify($_SESSION['ServerTimezoneDiff'] . ' hour')->format('Y-m-d H:i:s');
        
                            // Determine if they are clocking in
                            if ($endTime!=null &&
                                $endTime!=''){
                                // Set the place to be redirected to to be the tasks page
                                $redirectTo='redirectors/logout.php';

                                // Get the client's current location
                                $endLocation = get_ip_address();

                                // Let's create the update query off of what we have.
                                //    TODO: Right now the normal clock out is '2' this may change later.
                                $sql='UPDATE laborclock SET EndTime="' . $currentTime . '"';
                                if ($laborCategory!=null) {$sql = $sql . ', CurrentLaborCategoryStartTime=CURRENT_TIMESTAMP';}
                                if ($laborCategory!=null) {$sql = $sql . ', CurrentLaborCategoryID="' . $laborCategory . '"';}
                                if ($endLocation!=null) {$sql = $sql . ', EndLocation="' . $endLocation . '"';}
                                $sql=$sql .' WHERE ClockID=' . $clockID . ';';

                                // Attempt to run the query and evaluate the response
                                if (!$db->queryDB($sql, $userRow, "updateTimecard Form occurance 4")){
                                    echo '<script>alert("Timecard was NOT updated in the database. Please check the data and try again.");</script>';
                                }
                            }
                            else{
                                // Get the client's current location
                                $startLocation = get_ip_address();
                                $endLocation = '';

                                // Let's create the insert query off of what we have
                                $sql='INSERT INTO laborclock (';
                                $sql = $sql . 'CompanyID';
                                $sql = $sql . ', UserID';
                                if ($taskID!=null) {$sql = $sql . ', TaskID';}
                                if ($ratePercentage!=null) {$sql = $sql . ', RatePercentage';}
                                if ($payDateStart!=null) {$sql = $sql . ', PayDateStart';}
                                if ($startTime!=null) {$sql = $sql . ', StartTime';}
                                if ($startLocation!=null) {$sql = $sql . ', StartLocation';}
                                if ($laborCategory!=null) {$sql = $sql . ', CurrentLaborCategoryID';}
                                $sql=$sql .') VALUES (';
                                $sql = $sql . $companyID;
                                $sql = $sql . ', ' . $userID;
                                if ($taskID!=null) {$sql = $sql . ', ' . $taskID;}
                                if ($ratePercentage!=null) {$sql = $sql . ', ' . $ratePercentage;}
                                if ($payDateStart!=null) {$sql = $sql . ', "' . $payDateStart . '"';}
                                if ($startTime!=null) {$sql = $sql . ', "' . $currentTime . '"';}
                                if ($startLocation!=null) {$sql = $sql . ', "' . $startLocation . '"';}
                                if ($laborCategory!=null) {$sql = $sql . ', "' . $laborCategory . '"';}
                                $sql=$sql .');';
                                
                                // Lock the table while checking/Writing
                                $db->queryDB("LOCK TABLES laborclock WRITE;", $userRow, "updateTimecard Form occurance 5");
                                
                                // Run Query to determine if they are already clocked in
                                $clockedInResult = $db->queryDB("SELECT 1 FROM laborclock WHERE UserID=" . $userID . " AND EndTime IS NULL;", $userRow, "updateTimecard Form occurance 6");
                                
                                // Determine if they are already clocked in
                                if(mysqli_num_rows($clockedInResult)!=0) {
                                    // Let's create the update query off of what we have
                                    $closeSQL='UPDATE laborclock SET EndTime="' . $currentTime . '"';
                                    if ($startLocation!=null) {$closeSQL = $closeSQL . ', EndLocation="' . $startLocation . '"';}
                                    $closeSQL=$closeSQL .'WHERE UserID=' . $userID . ' AND EndTime IS NULL;';

                                    // Close this timecard period before allowing another to start
                                    $db->queryDB($closeSQL, $userRow, "updateTimecard Form occurance 7");
                                }

                                // Set a just clocked in field
                                $justClockedIn=1;

                                // Attempt to run the query and evaluate the response
                                if (!$db->queryDB($sql, $userRow, "updateTimecard Form occurance 8")){
                                    echo '<script>alert("Timecard was NOT updated in the database. Please check the data and try again.");</script>';
                                }
                                
                                // Unlock Lock the table
                                $db->queryDB("UNLOCK TABLES;", $userRow, "updateTimecard Form occurance 9");
                            }
                            
                        }
                        else {
                            echo '<script>alert("There is not enough information to update/insert timecard information. Please check the data and try again.");</script>';
                        }
                        
                        // redirect to the tasks page
                        echo ('<script>window.location = "' . $redirectTo . '";</script>');
                    }
                    
                    // Change the form back to NOT being submitted
                    $_SESSION['formSubmitted']='FALSE';
                }
            }
            else {
                // Set the form submitted session variable to FALSE
                $_POST['formSubmitted']='FALSE';
            }
        }
        else {
            // redirect to the invalid access page
            echo ('<script>window.location = "invalid_access.php";</script>');

            exit;
        }
    }
?>
        
﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Task Management System - Timecard</title>

    <meta name="keywords" content="GIS,data,timecard,IT" />
    <meta name="description" content="EES Divisions." />
    <meta http-equiv="refresh" content="300;url=updateTimecard.php" />

    <script src="./javascript/general.js" type="text/javascript"></script>
    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>

    <link rel="rel icon" href="images/ees_ico.ico"  type="image/x-icon"/> 
    <link href="./SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    <link href="./SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
    <link rel = "stylesheet" type="text/css" href="./css/contentpage.css" >
</head>

<body class="thrColElsHdr">
<script>
    var isClockedIn = false;
    var userip;
    var timer = null;
    
    // Create a variable to hold the server hour time difference
    var serverTimezoneDiff = null;

    function preSubmitLogic(){
        try {
            // Get the controls that we will be populating
            var startTimeCtrl = document.getElementById('StartTime');
            var endTimeCtrl = document.getElementById('EndTime');
            
            // Get a current date value. 
            var currentDate = new Date((new Date()).getTime()+(serverTimezoneDiff*3600000));
            var currentDateString = date2str(currentDate, 'yyyy-MM-ddThh:mm:ss');

            //Determine if they have ever logged in
            if (startTimeCtrl.value===''){
                // Set just the start value to be the current date and reset the end so a new row will be inserted
                startTimeCtrl.value = date2str(currentDate, 'yyyy-MM-ddThh:mm:ss');

                // populate the end time to be nothing
                endTimeCtrl.value = '';
            }
            else{
                // Determine if the end date has a value
                if (endTimeCtrl.value!==''){
                    // Get the two dates as javascript dates
                    var startDate = new Date(startTimeCtrl.value.replace("T"," "));
                    var endDate = new Date(startTimeCtrl.value.replace("T"," "));
                    
                    // Ensure that the start date is before the end date
                    if (startDate>endDate){
                        // Start date is newer, so do not allow the submit
                        return false;
                    }
                }
                
                // Determine if we are clocked in
                if (isClockedIn) {
                    // populate the end time to be the current date and time
                    endTimeCtrl.value = currentDateString;
                }
                else{
                    // populate the start time to be the current date and time 
                    startTimeCtrl.value = currentDateString;

                    // populate the end time to be nothing
                    endTimeCtrl.value = '';
                }
            }
            
            // Success if we made it all of the way through
            return true;
        }
        catch (err){
            // Failure if we are here
            return false;
        }
    }

</script>
    
<div id="container">
  
<!-- start of banner wrap --->

<div id="topContent">
  
<div>
   <div class="MenuBarHorizontal" id="navBar">  <ul id="TopNav" class="MenuBarHorizontal">

    <script type="text/javascript">
    <!--
    var MenuBar2 = new Spry.Widget.MenuBar("TopNav", {imgDown:"./SpryAssets/SpryMenuBarDownHover.gif", imgRight:"./SpryAssets/SpryMenuBarRightHover.gif"});
    //-->
    </script>

    </div>
  </div>
</div>
<!-- end of banner wrap --->

  <!-- end #header -->
  <br class="clearfloat" />
  <div id="sidebar1">
      <?php 
        // Determine if we are GTG
        if ($gtg){
          // Render the appropriate presentation for the timecards sidebar
          getSidebar($userRow, 'timecard');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Timecard</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href=
          "<?php echo ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'?"https" : "http") . "://" . $_SERVER['HTTP_HOST'] .  $_SERVER['REQUEST_URI']); ?>"> Timecard </a></div>
    <br>
        
    <?php
        // Determine if they are GTG
        if ($gtg){
            // Determine if this if not a current timecard 
            if ($fromEditButton=="TRUE"){
                // Get the timecard for this user
                echo getTimecard($db, $userRow, $timecardUserAssocRow, $clockID, $payDateStart);
            }
            else {
                // Get the current timecard info
                echo getCurrentTimecard($db, $userRow, $timecardUserAssocRow, $justClockedIn);
            }
        }
        else {
            // Set the login failed to true
            $_SESSION['failedLogin']='TRUE';

            // Add a session variable that is this page URL
            $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

            // redirect to the login page
            echo ('<script>window.location = ".";</script>');
        }
    ?>       
    
  <!-- end #mainContent -->
  
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  
  <!-- start #footer --></div>
   <div id="footer">
    <p>© 2018 Evolve Engineering and Software. EES, Evolve Engineering and Software, EES Logo are registered marks of Evolve Engineering and Software.</p>
  <!-- end #footer -->
   </div>
<!-- end #container -->
</div>

</body>

</html>