<?php 
    // Determine if the form was submitted recently
    if (!isset($_POST['formSubmitted']) || 
        !htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
        // Require the login since we are not submitting the form
        require_once('php_only_scripts/protector.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/financials_presentation.php';

    // Init some variables
    $userRow=null;
    $bonusUserAssocRow=null;
    $bonusUserID=-1;
    $clockID=-1;
    $payDateStart=null;

    // Assume NOT gtg
    $gtg = false;
    
    // 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();

        // Determine if a user ID sent in the URL
        if (isset($_GET['bonusUserID']) ){
            // Hold onto the Timecard user ID to be used
            $bonusUserID = $_GET['bonusUserID'];
        }
        else {
            // Determine if a user ID sent in a post
            if (isset($_POST['UserID']) ){
                // Hold onto the Timecard user ID to be used
                $bonusUserID = $_POST['UserID'];
            }
            else {
                // Hold onto the Timecard user ID to be used
                $bonusUserID = $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']));
        }

        // Create a query to to get bonus user information on the passed in bonus user
        $sql = 'SELECT * FROM users u ' .
               'WHERE u.UserID=' . $bonusUserID . ';';

        // Attempt to get the bonus user row
        $bonusUserRow = $db->queryDB($sql, $userRow, "financials Form occurance 1");

        // Attempt to get the bonus user row
        $bonusUserAssocRow = $bonusUserRow->fetch_assoc();
 
        // Determine if this user is allowed here or not
        if ($userRow["AccountStatus"]=='ACTIVE' &&
            $userRow["SUEmployee"]==1 && 
            $userRow["UserLevel"]!='TIMECARD ONLY' &&
            ($userRow["UserLevel"]=='SU' ||
             ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==$bonusUserAssocRow["CompanyID"]) ||
             ($userRow["UserID"]==$bonusUserAssocRow["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 if this user can even modify
                if (!$userRow["CanModify"]){
                    // Let them know they cannot modify
                    echo "<script type=\"text/javascript\">window.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 = "tasks.php";</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 = $bonusUserID;
                    $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'));

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

                    // Set today as the quarter to check
                    $quarterStart = new DateTime();

                    // Create the previous quarter
                    $previousQuarterStart = clone $quarterStart;
                    $previousQuarterStart->modify('-3 months');

                    // Set string column names
                    $percentToGoalColumnName = "PercentToGoalQ" . getQuarterNumber($quarterStart->format("n"));
                    $goalPercentAdjustmentColumnName = "PercentToGoalAdjustmentQ" . getQuarterNumber($quarterStart->format("n"));
                    $percentOfPayColumnName = "GoalPercentOfPayQ" . getQuarterNumber($quarterStart->format("n"));
                    $goalFudgeFactorColumnName = "GoalFudgeFactorQ" . getQuarterNumber($quarterStart->format("n"));
                    $previousPercentToGoalColumnName = "PercentToGoalQ" . getQuarterNumber($previousQuarterStart->format("n"));
                    $previousGoalPercentAdjustmentColumnName = "PercentToGoalAdjustmentQ" . getQuarterNumber($previousQuarterStart->format("n"));
                    $previousPercentOfPayColumnName = "GoalPercentOfPayQ" . getQuarterNumber($previousQuarterStart->format("n"));
                    $previousGoalFudgeFactorColumnName = "GoalFudgeFactorQ" . getQuarterNumber($previousQuarterStart->format("n"));

                    // Set the local variables from what was posted
                    $percentToGoal = htmlspecialchars($_POST['percentToGoal']);
                    $goalPercentAdjustment = htmlspecialchars($_POST['goalPercentAdjustment']);
                    $percentOfPay = htmlspecialchars($_POST['percentOfPay']);
                    $goalFudgeFactor = htmlspecialchars($_POST['goalFudgeFactor']);
                    $previousPercentToGoal = htmlspecialchars($_POST['previousPercentToGoal']);
                    $previousPercentGoalAdjustment = htmlspecialchars($_POST['previousGoalPercentAdjustment']);
                    $previousPercentOfPay = htmlspecialchars($_POST['previousPercentOfPay']);
                    $previousGoalFudgeFactor = htmlspecialchars($_POST['previousGoalFudgeFactor']);

                    // Let's create the update query off of what we have
                    $sql='UPDATE companies SET ';
                    $sql= $sql . 'CompanyID=' . $companyID;
                    if ($percentToGoal!=null) {$sql = $sql . ', ' . $percentToGoalColumnName . '=' . $percentToGoal;}
                    if ($goalPercentAdjustment!=null) {$sql = $sql . ', ' . $goalPercentAdjustmentColumnName . '=' . $goalPercentAdjustment;}
                    if ($percentOfPay!=null) {$sql = $sql . ', ' . $percentOfPayColumnName . '=' . $percentOfPay;}
                    if ($goalFudgeFactor!=null) {$sql = $sql . ', ' . $goalFudgeFactorColumnName . '=' . $goalFudgeFactor;}
                    if ($previousPercentToGoal!=null) {$sql = $sql . ', ' . $previousPercentToGoalColumnName . '=' . $previousPercentToGoal;}
                    if ($previousPercentGoalAdjustment!=null) {$sql = $sql . ', ' . $previousGoalPercentAdjustmentColumnName . '=' . $previousPercentGoalAdjustment;}
                    if ($previousPercentOfPay!=null) {$sql = $sql . ', ' . $previousPercentOfPayColumnName . '=' . $previousPercentOfPay;}
                    if ($previousGoalFudgeFactor!=null) {$sql = $sql . ', ' . $previousGoalFudgeFactorColumnName . '=' . $previousGoalFudgeFactor;}
                    $sql=$sql .' WHERE CompanyID=' . $companyID . ';';
//echo '<script>alert("' . addslashes($sql) . '");</script>';

                    // Attempt to run the query and evaluate the response
                    if (!$db->queryDB($sql, $userRow, "financials Form occurance 1")){
                        echo '<script>alert("Company was NOT updated in the database. Please check the data and try again.");</script>';
                        // TODO: How do I want to display a failure to the user?
                    }
                    
                    // 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 - Financials</title>

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

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

    <link rel="icon" href="images/ees_ico.ico"/> 
    <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 hoursWorked = null;
    var hoursWorkedTimer = null;
    var hourlyPay=0;
    var percentToGoal=0;
    var percentIntoQuarter=0;
    var percentOfPay=10;
    var fudgeFactor=1;
    var isClockedIn = false;
    var timer = null;
    
    function startTimer(timer, controlName, hoursWorked){
        // Set up the new timer
        timer = setInterval(function(){displayTimer(controlName, hoursWorked)}, 1000);
    }

    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();
            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 nothing
                    endTimeCtrl.value = currentDateString;
                }
                else{
                    // populate the start time to be the current 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 tasks sidebar
          getSidebar($userRow, 'financials');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Financials</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href="financials.php"> Financials </a></div>

    <br>
        
    <?php
        // Determine if they are GTG
        if ($gtg){
            // Time to query for their bonuses
            echo getBonus($db, $userRow, $bonusUserAssocRow);
        }
        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>