<?php 
    // continue the session
    session_start();
    
    // 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';

    // Init some variables
    $userRow=null;
    $timecardUserAssocRow=null;
    $companyID=-1;
    $payDateStart=null;
    $timecardUserID=-1;

    // Assume NOT gtg
    $gtg = false;

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

    // Determine if a user ID was sent in the URL
    if (isset($_GET['tuid']) ){
        // Hold onto the user ID to be used
        $timecardUserID = $_GET['tuid'];
    }
    else{
        // Determine if it was posted
        if (isset($_POST['TaskID']) ){
            // Maybe it was posted
            $timecardUserID = $_POST['UserID'];
        }
    }
    
    // Determine if a company ID was sent in the URL
    if (isset($_GET['cid']) ){
        // Hold onto the company ID to be used
        $companyID = $_GET['cid'];
    }
    else{
        // Determine if it was posted
        if (isset($_POST['CompanyID']) ){
            // Maybe it was posted
            $companyID = $_POST['CompanyID'];
        }
    }
    
    // Determine if the pay date start was sent in the URL
    if (isset($_GET['pds']) ){
        // Hold onto the pay date start to be used
        $payDateStart = $_GET['pds'];
    }
    
    // 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();
        
        // Determine if this user has access to this page
        if ($userRow["UserLevel"]=='TIMECARD ONLY' || 
            $userRow["SUEmployee"]!=1 ||
            $userRow["AccountStatus"]!='ACTIVE'){
            // redirect to the invalid access page
            echo ('<script>window.location = "invalid_access.php";</script>');

            exit;
        }
        
        // 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"]))){
            // Set the good to go until they log out
            $gtg = true;

            // Determine if BOTH the user ID AND form submitted
            if (isset($_POST['formSubmitted']) && 
                htmlspecialchars($_POST['formSubmitted'])=='TRUE' &&
                $timecardUserID>0 && $companyID > 0){
                // Determine if this user can even modify
                if ($userRow["CanModify"]==0){
                    // Inform them it was not updated
                    echo '<script>alert("You do not have access to modify/add this kind of data. Redirecting to the timecards page.");</script>';

                    // redirect to the clocked status page page
                    echo ('<script>window.location = "clockedStatus.php";</script>');
                }
                else {
                    // Set the local variables from what was posted
                    $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']));
                    $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');

                    // 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 . ';';
                    
                    // Get any rows that are returned
                    $conflictingTimecardRecords = $db->queryDB($sql, $userRow, "addTimecard 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 adding will conflict with others.  This is not allowed. New labor clock row was NOT added to 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 enter 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){
                            // Let's create the insert query off of what we have
                            $sql='INSERT INTO laborclock (UserID, CompanyID ';
                            if ($startLocation!=null) {$sql = $sql . ', StartLocation';}
                            if ($endLocation!=null) {$sql = $sql . ', EndLocation';}
                            if ($startTime!=null) {$sql = $sql . ', StartTime';}
                            if ($startTime!=null) {$sql = $sql . ', CurrentLaborCategoryStartTime';}
                            if ($endTime!=null) {$sql = $sql . ', EndTime';}
                            if ($ratePercentage!=null) {$sql = $sql . ', RatePercentage';}
                            if ($payDateStart!=null) {$sql = $sql . ', PayDateStart';}
                            if ($laborCategory!=null) {$sql = $sql . ', CurrentLaborCategoryID';}
                            $sql=$sql .') VALUES (' . $timecardUserID . ', ' . $companyID;
                            if ($startLocation!=null) {$sql = $sql . ', "' .$startLocation . '"';}
                            if ($endLocation!=null) {$sql = $sql . ', "' .$endLocation . '"';}
                            if ($startTime!=null) {$sql = $sql . ', "' .$startTime . '"';}
                            if ($startTime!=null) {$sql = $sql . ', "' .$startTime . '"';}
                            if ($endTime!=null) {$sql = $sql . ', "' .$endTime . '"';}
                            if ($ratePercentage!=null) {$sql = $sql . ', ' .$ratePercentage . '';}
                            if ($payDateStart!=null) {$sql = $sql . ', "' .$payDateStart . '"';}
                            if ($laborCategory!=null) {$sql = $sql . ', ' .$laborCategory . '';}
                            $sql=$sql .');';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
                            // Attempt to run the query and evaluate the response
                            if ($db->queryDB($sql, $userRow, "addTimecard Form occurance 2")){
                                // Get the most recent ID (tool)
                                $newToolID = mysqli_insert_id($db->getDBConnection());

                                // redirect to the clocked status page page
                                echo ('<script>window.location = "clockedStatus.php";</script>');
                            }
                            else {
                                echo '<script>alert("New labor clock row was NOT added to the database. Please check the data and try again.");</script>';
                                // TODO: How do I want to display a failure to the user?
                                // echo '<font color="red">Task was NOT added to the database. <br> Please check the data and try again.</font>';
                            }
                        }
                    }

                    // Change the form back to NOT being submitted
                    $_SESSION['formSubmitted']='FALSE';
                }
            }
            else {
                // Set the form submitted session variable to FALSE
                $_POST['formSubmitted']='FALSE';
            }
        }
    }
?>
        
﻿<!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 - Add Timecard</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />

    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    <script src="scripts/jpicker-1.1.6/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="scripts/jpicker-1.1.6/jpicker-1.1.6.min.js" type="text/javascript"></script>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>
    
    <link rel="icon" href="images/ees_ico.ico"/> 
    
    <link href="scripts/jpicker-1.1.6/css/jPicker-1.1.6.css" rel="stylesheet" type="text/css"/>
    <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">

<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 - Add 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){
            // Get the timecard for this user
            echo getTimecard($db, $userRow, $timecardUserAssocRow, null, $payDateStart);
        }
        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>