<?php
    function retrieveTimecardHistoryAsList($db, $userRow, $timecardUserAssocRow){
        // Initialize the return
        $result = 
            '<li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell payDateCell">
                        <p><b>Pay Date Start</b></p>
                    </div>
                    <div class="cell payDateEndCell">
                        <p><b>Pay Date End</b></p>
                    </div>
                    <div class="cell totalPayDateHoursCell">
                        <p><b>Total Hours</b></p>
                    </div> 
                    <div class="cell updateCell">
                        <p><b>Details</b></p>
                    </div>
                </div>
            </li>';
        
        // determine what kind of user this is
        if ($userRow["CompanyID"]==1 &&
            ($userRow["UserLevel"]=='SU' ||
             ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==$timecardUserAssocRow["CompanyID"]))){
            // Change the column headers
            $result = 
                '<li class="ui-state-default ui-state-disabled Table">
                    <div class="Heading">
                        <div class="cell payDateCell">
                            <p><b>Pay Date Start</b></p>
                        </div>
                        <div class="cell payDateEndCell">
                            <p><b>Pay Date End</b></p>
                        </div>
                        <div class="cell totalPayDateHoursCell">
                            <p><b>Total Break Time</b></p>
                        </div> 
                        <div class="cell totalPayDateHoursCell">
                            <p><b>Total Hours</b></p>
                        </div> 
                        <div class="cell updateCell">
                            <p><b>Details</b></p>
                        </div>
                    </div>
                </li>';
        }

        try {
            // 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"]))){
                // Get the timecard hour and paydates to be displayed
                $sql = 'SELECT lc.PayDateStart, ROUND(SUM((IF(lc.EndTime IS NULL, UNIX_TIMESTAMP(CONVERT_TZ(NOW(), "+00:00", "-01:00")), UNIX_TIMESTAMP(lc.EndTime)) - UNIX_TIMESTAMP(lc.StartTime)))/3600,2) as CurrentPaydayHours, sum(IF(lc.EndTime is null, 1, 0)) as CurrentTimecard, ' . 
                       'ROUND(SUM(BreakTimeTaken),2) as TotalBreakTimeTaken, ' . 
                       'u.FirstName, u.LastName, SUM(lcg.UsesPTO) AS UsedAnyPTO ' .
                       'FROM laborclock lc ' .
                       'LEFT JOIN users u ON lc.UserID=u.UserID ' .
                       'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID=lcg.LaborCategoryID ' .
                       'WHERE lc.UserID=' . $timecardUserAssocRow["UserID"]. ' ' .
                       'GROUP BY lc.PayDateStart ' .
                       'ORDER BY lc.PayDateStart DESC;';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
                // Query the database for the hours for each pay period 
                $rows = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 1");

                // Loop through the returned results
                $order=0;
                $name='';
                while ($row=mysqli_fetch_array($rows)){
                    // Get the name to put at the top
                    $name=$row["FirstName"] . ' ' . $row["LastName"];
                    
                    // Increase the order by one
                    $order++;

                    // Set the color ofd the row to automatically be NOT current
                    $usedPTOColor=$color='FireBrick';

                    // Determine if it is current to change trhe cvolor of the row
                    if($row["CurrentTimecard"]){
                        // Change it to green for the current one
                        $usedPTOColor=$color='OliveDrab';
                    }
                    
                    // Get the current pay date
                    $startPayDate=new DateTime($row["PayDateStart"]);

                    // Get the year
                    $payDateYear=intval($startPayDate->format('Y'));

                    // Determine if there was any PTO used this pay period after the time we implemented PTO in 2023.
                    if ($row["UsedAnyPTO"] && $payDateYear>2022){
                        // Set the color to yellow
                        $usedPTOColor='Yellow';
                    }
                    
                    // Determine what is the pay range
                    $howFarAhead="";
                    switch ($timecardUserAssocRow["PayPeriod"]) {
                        case "Annually":
                            // Set it for 1 year ahead
                            $howFarAhead="+1 years";

                            break;
                        case "Semi-Annually":
                            // Set it for 6 months ahead
                            $howFarAhead="+6 months";

                            break;
                        case "Quarterly":
                            // Set it for 3 months ahead
                            $howFarAhead="+3 months";

                            break;
                        case "Monthly":
                            // Set it for 1 month ahead
                            $howFarAhead="+1 months";

                            break;
                        case "Bi-Weekly":
                            // Set it for 2 weeks ahead
                            $howFarAhead="+2 weeks";

                            break;
                        case "Weekly":
                            // Set it for 1 week ahead
                            $howFarAhead="+1 weeks";

                            break;
                        case "Daily":
                            // Set it for 1 day ahead
                            $howFarAhead="+1 days";

                            break;
                        default:
                            // Set it for 2 weeks ahead
                            $howFarAhead="+2 weeks";

                            break;
                    }

                    // Determine if this user has access to enter new pay periods
                    $addPayPeriodHTML='';
                    $totalBreakTime='';
                    if ($userRow["CompanyID"]==1 &&
                        ($userRow["UserLevel"]=='SU' ||
                         ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==$timecardUserAssocRow["CompanyID"]))){
                        // Add the HTML
                        $addPayPeriodHTML='<button type="button" name="addPayPeriodButton" id="addPayPeriodButton" title="Add a new pay range for this pay period." onclick="window.location = \'addTimecard.php?tuid=' . $timecardUserAssocRow["UserID"] . '&cuid=' . $timecardUserAssocRow["CompanyID"] . '&pds=' . $row["PayDateStart"] . '\';">+</button>';
                        
                        // Add the total break time html
                        $totalBreakTime='<div class="cell totalPayDateHoursCell" style="background-color: '. $usedPTOColor . ';">
                                            <span>
                                                <p>' . $row["TotalBreakTimeTaken"] . ' Minutes</p>
                                            </span>
                                        </div> 
                                        ';
                    }

                    // Create the end date/time to be 2 weeks from the start
                    $endDateTime = (new DateTime($row["PayDateStart"]))->modify($howFarAhead)->modify('-1 seconds');

                    // Add this option to the select
                    $result = $result .
                        '<li id="Timecard_' . $order . '" class="ui-state-default Table">
                            <div class="Row" style="background-color: '. $color . ';">
                                <div class="cell payDateCell"> 
                                    <span>
                                        <p>' . $row["PayDateStart"] . '</p>
                                    </span>
                                </div>
                                <div class="cell payDateEndCell">
                                    <span>
                                        <p>' . $endDateTime->format('Y-m-d H:i:s') . '</p>
                                    </span>
                                </div>
                                ' . $totalBreakTime . '
                                <div class="cell totalPayDateHoursCell" style="background-color: '. $usedPTOColor . ';">
                                    <span>
                                        <p>' . $row["CurrentPaydayHours"] . ' Hours</p>
                                    </span>
                                </div> 
                                <div class="cell updateCell">
                                    <span>
                                        <table>
                                            <tr>
                                                <td>
                                                   <button type="button" name="payDateHistoryButton" id="payDateHistoryButton" title="View history of this pay period." onclick="window.location = \'paydateHours.php?timecardUserID=' . $timecardUserAssocRow["UserID"] . '&paydateStart=' . $row["PayDateStart"] .'\';">View</button>
                                                   ' . $addPayPeriodHTML . '
                                                </td>
                                            </tr>                                
                                        </table>
                                    </span>
                                </div>
                            </div>
                        </li>';
                }
                
                $result='<div style="text-align: center; font-size:30px;">' . $name . '</div><br>' . $result;
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function retrievePayDateHistoryAsList($db, $userRow, $timecardUserAssocRow, $payDateStart){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableTimecardRowCellHTML = '';

        // Determine if they are at a level to manage tasks
        switch ($userRow["UserLevel"]){
            case 'EXECUTIVE':
            case 'SU':
                $updateableTitleRowCellHTML = '
                            <div class="cell updateCell">
                                <p><b>Edit</b></p>
                            </div>
                        ';

                break;
        }

        // Initialize the return with columns
        $result = 
            '<li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell dayNumberCell">
                        <p><b>Day Number</b></p>
                    </div>
                    <div class="cell dayDateCell">
                        <p><b>Date</b></p>
                    </div>
                    <div class="cell dayWeekdayCell">
                        <p><b>Weekday</b></p>
                    </div>
                    <div class="cell dayTotalHoursCell">
                        <p><b>Total Hours</b></p>
                    </div> 
                </div>
            </li>
            <li class="ui-state-default ui-state-disabled Table">
                <div class="Group Heading" id="TimecardDetails_Header" style="display:none;">
                    <div class="Row">
                        <div class="cell durationFiller">
                        </div>
                        <div class="cell durationTextCell">
                            <span>
                                <p>Day #/Duration</p>
                            </span>
                        </div>
                        <div class="cell durationStartTimeCell">
                            <span>
                                <p>Start Time</p>
                            </span>
                        </div>
                        <div class="cell durationEndTimeCell">
                            <span>
                                <p>End Time</p>
                            </span>
                        </div>
                        <div class="cell durationHoursCell">
                            <span>
                                <p>Duration Hours</p>
                            </span>
                        </div>' . 
                        $updateableTitleRowCellHTML . '
                    </div>
                </div>
            </li>';

        try {
            // 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"]))){
                // Get the timecard hour and paydates to be displayed
                $sql = 'SELECT lc.ClockID, lc.TaskID, lc.StartTime, lc.EndTime, lc.RatePercentage, lc.StartLocation, lc.EndLocation, ' . 
                       'u.FirstName, u.LastName, lcg.UsesPTO ' .
                       'FROM laborclock lc ' .
                       'LEFT JOIN users u ON lc.UserID=u.UserID ' .
                       'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID=lcg.LaborCategoryID ' .
                       'WHERE lc.UserID=' . $timecardUserAssocRow["UserID"]. ' ' .
                       'AND lc.PayDateStart=\'' . $payDateStart . '\' ' . 
                       'ORDER BY lc.StartTime ASC;';

                // Query the database for the hours for each pay period 
                $rows = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 2");

                // Init some variables for the loop
                $order=0;
                $timecardDayCount=1;
                $durationCount=1;
                $lastStartDate='';
                $currentDaySeconds=0;
                $currentDayInfoHTML='';
                $currentDayDurationInfo='';
                $dayUsesPTO=false;

                // Loop through the returned results
                $name='';
                while ($row=mysqli_fetch_array($rows)){
                    // Init variables
                    $updateableTimecardRowCellHTML = '';

                    // Get the name to put at the top
                    $name=$row["FirstName"] . ' ' . $row["LastName"];
                    
                    // Increase the order by one
                    $order++;

                    // Set the intividual clockin row color to be olive drab
                    $clockinRowColorCSS='background-color:OliveDrab;';
                    
                    // Create the new date based on what comes from the database
                    $loopStartDate=new DateTime($row["StartTime"], new DateTimeZone('America/Denver'));

                    // Determine if the end date is not null
                    if ($row["EndTime"]!=null && $row["EndTime"]!=''){
                        // Set the end date to the date in the database row
                        $loopEndDate=new DateTime($row["EndTime"], new DateTimeZone('America/Denver'));
                    }
                    else {
                        // Set the end date to the current mountain standard date/time
                        $loopEndDate=new DateTime("now", new DateTimeZone('America/Denver'));
                    }

                    // Determine if we need to start a new day section
                    if ($lastStartDate=='' ||
                        $lastStartDate->format("Y-m-d")!=$loopStartDate->format("Y-m-d")){
                        // determine if this is the first row
                        if ($lastStartDate==''){
                            // Set the last start date to the now current date
                            $lastStartDate = $loopStartDate;
                        }
                        else {
                            // Determine if the last day had PTO used
                            if ($dayUsesPTO){
                                // Replace the style string in this day
                                $currentDayInfoHTML = str_replace('style=""','style="background-color:yellow;"', $currentDayInfoHTML);
                                
                                $dayUsesPTO=false;
                            }
                                                        
                            // Add the current day to the result
                            $result=$result . $currentDayInfoHTML .
                                    '
                                    <div class="cell dayTotalHoursCell">
                                        <span>
                                            <p>' . round(($currentDaySeconds/3600), 2) . ' Hours</p>
                                        </span>
                                    </div> 
                                </div>
                            </li>' . $currentDayDurationInfo . '</div></li>';

                            // Increment the day that we are currently on
                            $timecardDayCount++;
                        }

                        // Create the new rollup 
                        $currentDayInfoHTML= 
                            '<li class="ui-state-default Table" style="background-color:FireBrick;" onclick="javascript:div_toggleUneditableTableRowVisibility(\'TimecardDetails_' . $timecardDayCount . '\');">
                                <div class="Row">
                                    <div class="cell dayNumberCell" style="">
                                        <span>
                                            <p>' . $timecardDayCount . '</p>
                                        </span>
                                    </div>
                                    <div class="cell dayDateCell">
                                        <span>
                                            <p>' . $loopStartDate->format("Y-m-d") . '</p>
                                        </span>
                                    </div>
                                    <div class="cell dayWeekdayCell">
                                        <span>
                                            <p>' . $loopStartDate->format('l') . '</p>
                                        </span>
                                    </div>';

                        // Start a new current Day duration block
                        $currentDayDurationInfo = '
                            <li class="ui-state-default Table">
                                <div class="Group" id="TimecardDetails_' . $timecardDayCount . '" style="display:none;">';

                        // Set the last start date to the now current date
                        $lastStartDate = $loopStartDate;

                        // Reset the total amount of hours for the day
                        $currentDaySeconds=0;

                        // Reset the duration back down to the first
                        $durationCount=1;
                    }

                    // Set the current amount of seconds in this duration
                    $currentDurationSeconds=$loopEndDate->getTimestamp()-$loopStartDate->getTimestamp();
                    
                    // Determine if any pay periods on this day used PTO time
                    if($row["UsesPTO"]==1){
                        // Set the intividual clockin row color to be olive drab
                        $clockinRowColorCSS='background-color:yellow;';
                        
                        // Set the day uses PTO flag to yes
                        $dayUsesPTO=true;
                    }

                    // Determine what the user level is to setup the task row cell
                    switch ($userRow["UserLevel"]){
                        case 'SU':
                        case 'EXECUTIVE':
                            // Give the the delete option
                            $updateableTimecardRowCellHTML = '
                                <div class="cell updateCell" style="' . $clockinRowColorCSS . '">
                                    <span>
                                        <table>
                                            <tr>
                                                <td>
                                                    <form action="updateTimecard.php?timecardUserID=' . $timecardUserAssocRow["UserID"] . '" method="post" enctype="multipart/form-data">  
                                                        <input type="hidden" name="clockID" id="clockID" value="' . $row["ClockID"] . '"/>
                                                        <input type="hidden" name="timecardUserID" id="timecardUserID" value="' . $timecardUserAssocRow["UserID"] . '"/>
                                                        <input type="hidden" name="payDateStart" id="payDateStart" value="' . $payDateStart . '"/>
                                                        <input type="hidden" name="fromEditButton" id="fromEditButton" value="TRUE"/>
                                                        <input type="submit" value="..." title="Edit this duration."/>
                                                    </form>
                                                </td>
                                            </tr>
                                        </table>
                                    </span>
                                </div>
                                ';
                    }

                    // Add this duration to the current day
                    $currentDayDurationInfo=$currentDayDurationInfo.
                        '   <div id="TimecardDay_' . $timecardDayCount . '_Duration_' . $durationCount . '" class="Row">
                                <div class="cell durationFiller">
                                </div>
                                <div class="cell durationTextCell" style="' . $clockinRowColorCSS . '">
                                    <span>
                                        <p>Day:' . $timecardDayCount . '  Duration: ' . $durationCount . '</p>
                                    </span>
                                </div>
                                <div class="cell durationStartTimeCell" style="' . $clockinRowColorCSS . '">
                                    <span>
                                        <p>' . $loopStartDate->format("H:i:s") . '</p>
                                    </span>
                                </div>
                                <div class="cell durationEndTimeCell" style="' . $clockinRowColorCSS . '">
                                    <span>
                                        <p>' . $loopEndDate->format("H:i:s") . '</p>
                                    </span>
                                </div>
                                <div class="cell durationHoursCell" style="' . $clockinRowColorCSS . '">
                                    <span>
                                        <p>' . round(($currentDurationSeconds/3600), 2) . '</p>
                                    </span>
                                </div>
                                ' . $updateableTimecardRowCellHTML . '
                            </div>';

                    // Increase the current amount of seconds in this current day
                    $currentDaySeconds=$currentDaySeconds+$currentDurationSeconds;

                    // Increase the duration
                    $durationCount++;
                }

                // Determine if there was only one day
                if ($order>0){
                    // Determine if the last day had PTO used
                    if ($dayUsesPTO){
                        // Replace the style string in this day
                        $currentDayInfoHTML = str_replace('style=""','style="background-color:yellow;"', $currentDayInfoHTML);
                    }

                    // Finish the day if there were days added
                    $result=$result . $currentDayInfoHTML .
                            '
                            <div class="cell dayTotalHoursCell">
                                <span>
                                    <p>' . round(($currentDaySeconds/3600), 2) . ' Hours</p>
                                </span>
                            </div> 
                        </div>
                    </li>' . $currentDayDurationInfo . '</div></li>';
                }
                
                $result='<div style="text-align: center; font-size:30px;">' . $name . '</div><br>' . $result;
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function notifyOfTimecardRollover ($db, $userID, $firstName, $lastName, $lastPayPeriodInMilliSeconds, $lastPayDateStart, $benefitsMessage){
        // Init Variables
        $lastPayPeriodHours=intval($lastPayPeriodInMilliSeconds/(1000*60*60));
        $lastPayPeriodMinutes=intval(($lastPayPeriodInMilliSeconds/(1000*60))%60);
        $lastPayPeriodSeconds=intval(($lastPayPeriodInMilliSeconds/1000)%60);

        // Let's create and get the users to inform
        $sql='SELECT * 
              FROM users 
              WHERE (UserID = ' . $userID . ') 
              OR    (UserLevel IN ("SU", "EXECUTIVE") AND SUEmployee=1 AND CompanyID=1 AND AccountStatus="Active");';
        $usersToNotify = $db->queryDB($sql, null, "timecards_presentation Form occurance 3");

        // determine if the is a last entry in the database
        if ($usersToNotify!=null){
            // Loop through the returned results
            while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                // Init the message
                $messageToSend='';
                
                // Determine if this is the employee that this information most matters
                $propogatedBenefitsMessage='';
                if ($userID==$userToNotify["UserID"] ||
                    $userToNotify["UserLevel"]=="SU"){ // TODO: Remove this after fully tested
                    // Set the message so the user can see it
                    $propogatedBenefitsMessage=$benefitsMessage;
                }

                // Determine if they care about ANY status changing
                if ($userToNotify["ReceivePayPeriodRolloverUpdate"]){
                    // Create the message to add for this
                    $messageToSend="A new Pay Period has begun for " . 
                              $firstName . " " . 
                              $lastName . 
                              ".  Please review the last pay " . 
                              "period worked starting '" . $lastPayDateStart . "', " . 
                              "which has a total  of " . $lastPayPeriodHours . 
                              " hours, " . $lastPayPeriodMinutes . " minutes and " . 
                              $lastPayPeriodSeconds . " seconds. " . $propogatedBenefitsMessage . 
                              "Be sure to report any discrepancies to an executive or system SU.\r\n\r\n" .
                              "Regards, \r\n\r\nEvolve Engineering and Software Support Team\r\n" .
                              "(720)552-7997";
                }

                // First determine if they care about any changes
                if ($messageToSend!="" && 
                    preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])){
                    // Decode the quotes to be shown as quotes.  Not weirdness
                    $messageToSend = htmlspecialchars_decode ($messageToSend, ENT_COMPAT | ENT_HTML401);

                    // Create the subject
                    $subject = htmlspecialchars_decode ("Timecard Rollover has happened for " . 
                                                        $firstName . " " . 
                                                        $lastName);
                    $headers = "From: EES Mail Admin"." <admin@eestms.com>\r\n"; 
                    $headers .= "MIME-Version: 1.0\r\n";
//                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                    $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";

                    try {
                        // Attempt to mail it
                        mail($userToNotify["EMail"],$subject,$messageToSend,$headers);
                    } 
                    catch (Exception $e) {
                            echo("The notification was not sent to " . $userToNotify["EMail"] .
                             " because of an error.");
                    }
                }
            }
        }
        
        // Create the message to add for this
        $popupMessage="A new Pay Period has begun. Please review the last pay " . 
                      "period worked starting \'" . $lastPayDateStart . "\', " . 
                      "which has a total  of " . $lastPayPeriodHours . 
                      " hours, " . $lastPayPeriodMinutes . " minutes and " . 
                      $lastPayPeriodSeconds . " seconds. Be sure to report " .
                      "any discrepancies to an executive or system SU.";

        // Show the popup message
        echo '<script type="text/javascript">alert(\'' . $popupMessage . '\'); </script>';
    }

    function calculateCurrentPaydayStart($paySchedule, $payDateToCheckTimestamp){
        // Setup the return value to be today
        $returnPayDateStart = new DateTime();

        // Determine if the passed in value is even anything
        if ($payDateToCheckTimestamp!= null &&
            $payDateToCheckTimestamp!=''){
            // Create the date/time to check and set the next paycheck the same for now
            $returnPayDateStart = new DateTime($payDateToCheckTimestamp);

            // Create a current date time stamp to compare with
            $currentDate = new DateTime();
            
            // Set the time to the time of the pay day passed in to compare in order to make sure we are only comparing days
            $currentDate->setTime($returnPayDateStart->format('H'), $returnPayDateStart->format('i'), $returnPayDateStart->format('s'));

            // Determine if the pay date to check is NOT further than today's date
            if ($returnPayDateStart<=$currentDate){
                // Determine how many days it has been since the last clock in
                $diff = $currentDate->getTimestamp() - $returnPayDateStart->getTimestamp();

                // 1 day = 24 hours
                // 24 * 60 * 60 = 86400 seconds
                $days= abs(round($diff / 86400));

                // Determine what their pay schedule is to determine time between paydays.
                switch ($paySchedule){
                    case 'Daily':
                        // Change it to yesterday 
                        $returnPayDateStart=$currentDate->modify('-1 day');

                        // No need to check the others
                        break;
                    case 'Weekly':
                        // Find out how many weeks it has been since last clockin
                        $weeks= floor($days/7);
                        
                        // Create the next Pay day by adding the appropriate time
                        $returnPayDateStart->modify('+' . $weeks . ' week');

                        // No need to check the others
                        break;
                    case 'Bi-Weekly':
                        // Find out how many bi-weeks it has been since last clockin
                        $biweeks= (floor($days/14));
                        $weeks= $biweeks*2;

                        // Create the next Pay day by adding the appropriate time
                        $returnPayDateStart->modify('+' . $weeks . ' week');

                        // No need to check the others
                        break;
                    case 'Monthly':
                        // Reset the next payday to today
                        $returnPayDateStart = new DateTime();

                        // Monthly pay is calculated the first day of the month at midnight currently
                        $returnPayDateStart->modify('first day of this month')->setTime(0, 0, 1);
                        
                        break;
                    case 'Quarterly':
                        // Determine what quarter we are in.  For quarterly paid people they will be 
                        // paid on the first day of the next quarter at midnight from current.
                        if ($currentDate->format('m')>=1 && $currentDate->format('m')<=3) {
                            // Set it for January 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-' . $currentDate->format('Y') . ' 00:00:01');
                        } 
                        else if ($currentDate->format('m')>=4 && $currentDate->format('m')<=6) {
                            // Set it for April 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-04-' . $currentDate->format('Y') . ' 00:00:01');
                        }
                        else if ($currentDate->format('m')>=7 && $currentDate->format('m')<=9) {
                            // Set it for July 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-7-' . $currentDate->format('Y') . ' 00:00:01');
                        }
                        else if ($currentDate->format('m')>=10 && $currentDate->format('m')<=12) {
                            // Set it for October 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-10-' . $currentDate->format('Y') . ' 00:00:01');
                        }
                        
                        // No need to check the others
                        break;
                    case 'Semi-Annually':
                        // Determine what half year we are in.  For semi-annually paid people they will be
                        // paid on the first day of the next 6 month period from current date at midnight.
                        if ($currentDate->format('m')>=1 && $currentDate->format('m')<=6) {
                            // Set it for January 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-' . $currentDate->format('Y') . ' 00:00:01');
                        } 
                        else if ($currentDate->format('m')>=7 && $currentDate->format('m')<=12) {
                            // Set it for July 1st of this year
                            $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-07-' . $currentDate->format('Y') . ' 00:00:01');
                        }

                        // No need to check the others
                        break;
                    case 'Annually':
                        // There is only one option to be setup up to be paid the first ofnext year,
                        // since we only pay annually at the beginning of the year at midnight .
                        
                        // Set it for January 1st of this year
                        $returnPayDateStart = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-' . $currentDate->format('Y') . ' 00:00:01');


                        // No need to check the others
                        break;
                }
            }
        }

        // Return whatever we have
        return $returnPayDateStart;
    }

    function getCurrentTimecard($db, $userRow, $timecardUserAssocRow, $justClockedIn){
        // Set the return to nothing
        $returnValue = '';

        //TODO: Use this for testing until fully tested out.
$sqlTest='';

        // Determine if there is a timecard user row and a user row or not
        if ($timecardUserAssocRow!=null &&
            $userRow!=null) {
            $editableHTML = 'readonly="readonly"';
            $controlsHiddenStyle = 'display: none;';

            // Fill in any variables that we can from the query
            $companyID = $timecardUserAssocRow["CompanyID"];
            $firstPayDate = $timecardUserAssocRow["FirstPayDate"];
            $payPeriod = $timecardUserAssocRow["PayPeriod"];

            // Init all of the other variables
            $clockID = null;
            $taskID = -1;
            $startTime = '';
            $endTime = '';  
            $ratePercentage = 1;
            $payDateStart = $firstPayDate;
            $startLocation = '';
            $endLocation = '';
            $laborCategoryHTML = '';

            // Initialize variable that will be used in the HTML and Javascript
            $amountOfCurrentPaySeconds = 0;
            $clockToUse = 'now';
            $isClockedIn = 'false';
            $submitText = 'Clock In';

            // Create a query to to get most recent timecard information if it is still running
            $sql = 'SELECT * FROM laborclock lc1  ' . 
                   'WHERE lc1.UserID=' . $timecardUserAssocRow["UserID"] . ' ' .
                   'AND lc1.PayDateStart = (SELECT MAX(PayDateStart) FROM laborclock lc2 WHERE lc1.UserID = lc2.UserID) ' .
                   'AND lc1.StartTime = (SELECT MAX(StartTime) FROM laborclock lc2 WHERE lc1.UserID = lc2.UserID);';

            // Attempt to get the most recent timecard info
            $timecardRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 4");

            // determine if the is a last entry in the database
            if ($timecardRow!=null){
                // Attempt to get the timecard row
                $timecardAssocRow = $timecardRow->fetch_assoc();

                // Calculate what pay period we should be in. Could be the same.
                $payDateStart = calculateCurrentPaydayStart($payPeriod, $timecardAssocRow["PayDateStart"]);

                // Set the things we can
                $clockID = $timecardAssocRow["ClockID"];
                $taskID = $timecardAssocRow["TaskID"];
                $startTime=str_replace(" ","T",$timecardAssocRow["StartTime"]);
                $endTime=str_replace(" ","T",$timecardAssocRow["EndTime"]);
                $ratePercentage = $timecardAssocRow["RatePercentage"];
                $startLocation = $timecardAssocRow["StartLocation"];
                $endLocation = $timecardAssocRow["EndLocation"];

                // Determine if there is an end time or not
                if ($endTime == null ||
                    $endTime == ''){
                    // Determine if we have a start time
                    if ($startTime != null &&
                        $startTime != ''){
                        // Set the submit button text to be one of clocking out
                        $submitText = 'Clock Out';

                        // set the text for the isClockedIn to denote that they are
                        $isClockedIn = 'true';

                        // Change the clock to use to be the last start time
                        $clockToUse = $timecardAssocRow["StartTime"];
                        
                        // Allow them to change their labor category to where they want to clock out to
                        $laborCategoryHTML='
                                        <tr>
                                            <td align="middle" valign="middle">
                                                <br>
                                                <strong>Clock Out To: </strong> &nbsp; &nbsp;
                                                ' 
                                                . getLaborCategoryAsSelectOptions($db, $userRow, 2, 'Clocked Out') . 
                                                '
                                            </td>
                                        </tr>
                                        ';
                    }
                }
                else {
                    // Allow them to change their labor category to whatever they are working on
                    $laborCategoryHTML='
                                    <tr>
                                        <td align="middle" valign="middle">
                                            <br>
                                            <strong>Current Labor Area: </strong> &nbsp; &nbsp;
                                            ' 
                                            . getLaborCategoryAsSelectOptions($db, $userRow, null, 'Clocked In') . 
                                            '
                                        </td>
                                    </tr>
                                    ';
                    
                }

                // Create a query to get the amount of seconds in this current pay day
                $sql = 'SELECT SUM((UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime))) as CurrentPaydaySeconds ' .
                       'FROM laborclock ' . 
                       'WHERE PayDateStart = \'' . $timecardAssocRow["PayDateStart"] . '\' ' .
                       'AND UserID=' . $timecardUserAssocRow["UserID"] . ' ' .
                       'GROUP BY PayDateStart;';

                // Attempt to get the most recent timecard info
                $timecardAmountRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 5");

                // determine if there is any current time put in
                if ($timecardAmountRow!=null){
                    // Attempt to get the timecard amount row as an ASS
                    $timecardAmountAssocRow = $timecardAmountRow->fetch_assoc();

                    // Get the amount of milli they have currently logged
                    $amountOfCurrentPaySeconds = ($timecardAmountAssocRow["CurrentPaydaySeconds"]);
                }

                // Determine if they just clocked in
                if ($justClockedIn==1){
                    // Create a query to to get the last pay period if this is a clock in
                    $sql = 'SELECT MAX(PayDateStart) as MaxPayDateStart FROM laborclock ' .
                           'WHERE UserID=' . $timecardUserAssocRow["UserID"] . ' ' .
                           'AND EndTime IS NOT NULL;';

                    // Attempt to get it
                    $checkLastTimecard = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 6");

                    // determine if there is any last time put in
                    if ($checkLastTimecard!=null){
                        // Attempt to get the timecard amount row as an ASS
                        $checkLastTimecardRow = $checkLastTimecard->fetch_assoc();

                        // Determine if the pay period has changed
                        if ($payDateStart->format('Y-m-d H:i:s') != $checkLastTimecardRow["MaxPayDateStart"]){
                            // Create a query to get the amount of seconds in this current pay day
                            $sql = 'SELECT SUM((UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime))) as CurrentPaydaySeconds ' .
                                   'FROM laborclock ' . 
                                   'WHERE PayDateStart = \'' . $checkLastTimecardRow["MaxPayDateStart"] . '\' ' .
                                   'AND UserID=' . $timecardUserAssocRow["UserID"] . ' ' .
                                   'GROUP BY PayDateStart;';

                            // Attempt to get the most recent timecard info
                            $lastTimecardAmountRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 7");

                            // determine if there is any current time put in
                            if ($lastTimecardAmountRow!=null){
                                // Attempt to get the timecard amount row as an ASS
                                $lastTimecardAmountAssocRow = $lastTimecardAmountRow->fetch_assoc();
                                
                                // Determine the decimal hours that they accumulated this week
                                $lastPayPeriodHoursDecimal=($lastTimecardAmountAssocRow["CurrentPaydaySeconds"])/(60*60);

                                // Setup a query to get information about the user in the benefits table
                                $sql='SELECT * ' .
                                     'FROM employeebenefits ' .
                                     'WHERE UserID = ' . $timecardUserAssocRow["UserID"] . ';';

                                // Query the database for the employee benefits
                                $employeeBenefitsRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 8");

                                // determine if there is a employee benefits row
                                $benefitsMessage='';
                                $usedPTOMessage="";
                                if ($employeeBenefitsRow!=null && mysqli_num_rows($employeeBenefitsRow)==1){
                                    // Attempt to get the years worked row
                                    $employeeBenefitsAssocRow = $employeeBenefitsRow->fetch_assoc();
                                    
                                    // Get all of the current benefits values
                                    $hoursWorkedThisYear=$employeeBenefitsAssocRow["HoursWorkedThisYear"];
                                    $ptoBalance=$employeeBenefitsAssocRow["PTOBalance"];
                                    $ptoHoursAccruedThisYear=$employeeBenefitsAssocRow["PTOHoursAccruedThisYear"];
                                    $trialPeriod=$employeeBenefitsAssocRow["TrialPeriod"];
                                    $lastPayDateUpdated=$employeeBenefitsAssocRow["LastPayDateUpdated"];
                                    $yearsWorkedAtPayPeriodStart=0;
                                    
                                    // Now determine if this is NOT a trial period person
                                    if ($trialPeriod==0){
                                        // Setup a query to determine years worked
                                        $sql='SELECT DATEDIFF("' . $checkLastTimecardRow["MaxPayDateStart"] . '", u.AddDate)/365.25 AS YearsWorked ' .
                                             'FROM users u ' .
                                             'WHERE u.UserID = ' . $timecardUserAssocRow["UserID"] . ' ' .
                                             'AND u.UserLevel <> "TIMECARD ONLY";';
//$sqlTest="\r\n\r\n1) " .$sql;
                                        // Query the database for the user years worked
                                        $yearsWorkedRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 9");

                                        // determine if there is a row for years worked
                                        $yearsWorked=0;
                                        if ($yearsWorkedRow!=null){
                                            // Attempt to get the years worked row
                                            $yearsWorkedAssocRow = $yearsWorkedRow->fetch_assoc();

                                            // Set the things we can
                                            $yearsWorked = round($yearsWorkedAssocRow["YearsWorked"],2);
                                        }

                                        // Create a query to get any PTO Used
                                        $sql = 'SELECT lc.UserID, ' . 
                                                       'SUM((UNIX_TIMESTAMP(lc.EndTime) - UNIX_TIMESTAMP(lc.StartTime))/60/60) AS PTOUsed ' .
                                                'FROM laborclock lc ' .
                                                'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID = lcg.LaborCategoryID ' .
                                                'LEFT JOIN employeebenefits eb ON lc.UserID = eb.UserID ' .
                                                'WHERE lc.UserID = ' . $timecardUserAssocRow["UserID"] . ' ' .
                                                'AND lc.PayDateStart > eb.LastPayDateUpdated ' .
                                                'AND lc.StartTime < \'' . $payDateStart->format('Y-m-d H:i:s') . '\' ' .
                                                'AND lcg.UsesPTO=1 ' .
                                                'GROUP BY lc.UserID ' .
                                                'ORDER BY lc.StartTime;';

//$sqlTest=$sqlTest . "\r\n\r\n2) " .$sql;
                                        // Attempt to accrual rate row
                                        $ptoUsedRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 10");

                                        // determine if there is a row for accrual rate
                                        $ptoUsed=0;
                                        if ($ptoUsedRow!=null && mysqli_num_rows($ptoUsedRow)==1){
                                            // Attempt to get the accrual rate
                                            $ptoUsedAssocRow = $ptoUsedRow->fetch_assoc();

                                            // Get the value of the PTO that was used
                                            $ptoUsed=$ptoUsedAssocRow["PTOUsed"];

                                            // Determine if the amount used is over zero
                                            if ($ptoUsed>0){
                                                // Determine if there is enough PTO to cover the used PTO
                                                if ($ptoBalance<$ptoUsed){
                                                    // Set a message to be used to let everyone know they used PTO when they did not have enough
                                                    $usedPTOMessage=" --PTO was used over the amount that was available. Take actions accordingly.";
                                                }

                                                // Set the new PTO balance in the code
                                                $ptoBalance=$ptoBalance-$ptoUsed;
                                                
                                                // Create a query to update the used PTO on the benefits table
                                                $sql='UPDATE employeebenefits ' .
                                                     'SET PTOBalance = ' . $ptoBalance . ' ' .
                                                     'WHERE UserID = ' . $timecardUserAssocRow["UserID"] . ';';

                                                // Update the PTO to be the correct amount
                                                $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 11");
                                            }
                                        }

                                        // Create a query to get employee accrual rate
                                        $sql = 'SELECT * ' .
                                               'FROM EmployeePTOAccrualRate ' . 
                                               'WHERE TenureYearThisStarts < ' . $yearsWorked . ' ' .
                                               'ORDER BY TenureYearThisStarts DESC ' .
                                               'LIMIT 1;';
                                        
                                        // Determine if they are considered 0 years
                                        if ($yearsWorked==0){
                                            // Create a query to get employee accrual rate when they are at 0 years tenure
                                            $sql = 'SELECT * ' .
                                                   'FROM EmployeePTOAccrualRate ' . 
                                                   'WHERE TenureYearThisStarts <= ' . $yearsWorked . ' ' .
                                                   'ORDER BY TenureYearThisStarts DESC ' .
                                                   'LIMIT 1;';
                                        }
                                        

//$sqlTest=$sqlTest . "\r\n\r\n3) " .$sql;
                                        // Attempt to accrual rate row
                                        $accrualRateRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 11");

                                        // determine if there is a row for accrual rate
                                        $accrualRate=1;
                                        $maxAnnually=80;
                                        $maxOverall=120;
                                        if ($accrualRateRow!=null){
                                            // Attempt to get the accrual rate
                                            $accrualRateAssocRow = $accrualRateRow->fetch_assoc();

                                            // Fill the variables in properly now
                                            $accrualRate = $accrualRateAssocRow["AccrualRate"];
                                            $maxAnnually=$accrualRateAssocRow["MaxAnnually"];
                                            $maxOverall=$accrualRateAssocRow["MaxOverallPTO"];
                                        }

                                        // Create a query to get the last pay period PTO information
                                        $sql = 'SELECT gv.*, gv.AccrualRate/30*gv.TimeWorked AS AccruedTime ' .
                                               'FROM (SELECT lc.UserID, u.UserName, ' .
                                                    'SUM((UNIX_TIMESTAMP(lc.EndTime) - UNIX_TIMESTAMP(lc.StartTime))/60/60) AS TimeWorked, ' .
                                                    '(SELECT IF(DATEDIFF(eb.LastPayDateUpdated, u.AddDate)/365.25<=0,0,DATEDIFF(eb.LastPayDateUpdated, u.AddDate)/365.25) FROM users u WHERE u.UserID = lc.UserID AND u.UserLevel <> "TIMECARD ONLY") AS YearsWorked, ' .
                                                    '(SELECT AccrualRate FROM EmployeePTOAccrualRate WHERE TenureYearThisStarts <= YearsWorked ORDER BY TenureYearThisStarts DESC LIMIT 1) AS AccrualRate ' .
                                                    'FROM laborclock lc ' .
                                                    'LEFT JOIN users u ON lc.UserID = u.UserID ' .
                                                    'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID = lcg.LaborCategoryID ' .
                                                    'LEFT JOIN employeebenefits eb ON lc.UserID = eb.UserID ' .
                                                    'WHERE lc.PayDateStart > eb.LastPayDateUpdated ' .
                                                    'AND lc.StartTime < "' . $payDateStart->format('Y-m-d H:i:s') . '" ' .
                                                    'AND lcg.UsesPTO=0 ' .
                                                    'GROUP BY lc.UserID ' .
                                                    'ORDER BY lc.StartTime) AS gv ' .
                                                'WHERE gv.UserID = ' . $timecardUserAssocRow["UserID"] . ';';

//$sqlTest=$sqlTest."\r\n\r\n4) " .$sql;
                                        // Attempt to accrual rate row
                                        $accruedInfoRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 12");

                                        // determine if there is a row for accrual rate
                                        $accruableHoursWorkThisPayPeriod=0;
                                        $ptoAccrualRate=0;
                                        $ptoAccruedAmount=0;
                                        if ($accruedInfoRow!=null && mysqli_num_rows($accruedInfoRow)==1){
                                            // Attempt to get the accrual rate
                                            $accruedInfoAssocRow = $accruedInfoRow->fetch_assoc();

                                            // Fill the variables in properly now
                                            $yearsWorkedAtPayPeriodStart = $accruedInfoAssocRow["YearsWorked"];
                                            $accruableHoursWorkThisPayPeriod=$accruedInfoAssocRow["TimeWorked"];
                                            $ptoAccrualRate=$accruedInfoAssocRow["AccrualRate"];
                                            $ptoAccruedAmount=$accruedInfoAssocRow["AccruedTime"];
                                        }

                                        // Get the balances should both be able to take
                                        $newPTOHoursAccruedThisYear = $ptoHoursAccruedThisYear;
                                        $newPTOHoursBalance = $ptoBalance;
                                        $infoAboutNotAccruingAtMax = '';
                                        
                                        // Determine if the values are such that they CAN accrue hours
                                        if ($ptoHoursAccruedThisYear<$maxAnnually &&
                                            $ptoBalance<$maxOverall){
                                            // Get the balances should both be able to take
                                            $newPTOHoursAccruedThisYear = $ptoAccruedAmount+$ptoHoursAccruedThisYear;
                                            $newPTOHoursBalance = $ptoAccruedAmount+$ptoBalance;

                                            // Determine if both the overall and yearly accrual amounts got exceeded
                                            if ($newPTOHoursAccruedThisYear>$maxAnnually && 
                                                $newPTOHoursBalance>$maxOverall){
                                                // Get the hours that it would have been to exceed
                                                $amountToExceedYearlyMax=$maxAnnually-$ptoHoursAccruedThisYear;
                                                $amountToExceedOverallMax=$maxOverall-$ptoBalance;

                                                // Set the accrued amount to the overall max difference
                                                $ptoAccruedAmount=$amountToExceedOverallMax;

                                                // let them know they are not accruing because both are capping out and both are equally close
                                                $infoAboutNotAccruingAtMax='Both PTO balances would have been exceeded. Both were capping out to the same value. Taking that as the accrual amount.';
                                                
                                                // Determine which is lowest and set that as the amount to increment
                                                if ($amountToExceedYearlyMax<$amountToExceedOverallMax){
                                                    // Set the accrued amount to the yearly max difference
                                                    $ptoAccruedAmount=$amountToExceedYearlyMax;
                                                    
                                                    // let them know they are not accruing because both are capping out because of yearly max exceeded
                                                    $infoAboutNotAccruingAtMax='Both PTO balances would have been exceeded. Taking the lower accrual amount from closest cap of yearly max.';
                                                }
                                                else if ($amountToExceedOverallMax<$amountToExceedYearlyMax){
                                                    // let them know they are not accruing because both are capping out because of PTO balance max exceeded
                                                    $infoAboutNotAccruingAtMax='Both PTO balances would have been exceeded. Taking the lower accrual amount from closest cap of overall max.';
                                                }
                                            }
                                            else {
                                                // determine if annual got exceeded
                                                if ($newPTOHoursAccruedThisYear>$maxAnnually){
                                                    // Get the hours that it would have been to exceed
                                                    $amountToExceedYearlyMax=$maxAnnually-$ptoHoursAccruedThisYear;

                                                    // Set the accrued amount to the yearly max difference
                                                    $ptoAccruedAmount=$amountToExceedYearlyMax;
                                                    
                                                    // let them know they are not accruing because yearly max is capping out
                                                    $infoAboutNotAccruingAtMax='Yearly max PTO will be exceeded this pay period. Taking the difference as accrued amount.';
                                                }
                                                // determine if overall got exceeded
                                                else if ($newPTOHoursBalance>$maxOverall){
                                                    // Get the hours that it would have been to exceed
                                                    $amountToExceedOverallMax=$maxOverall-$ptoBalance;

                                                    // Set the accrued amount to the overall max difference
                                                    $ptoAccruedAmount=$amountToExceedOverallMax;
                                                    
                                                    // let them know they are not accruing because overall max is capping out
                                                    $infoAboutNotAccruingAtMax='Overall max PTO will be exceeded this pay period. Taking the difference as accrued amount.';
                                                }
                                            }

                                            // Reset the balances with the new accrued amount
                                            $newPTOHoursAccruedThisYear = $ptoAccruedAmount+$ptoHoursAccruedThisYear;
                                            $newPTOHoursBalance = $ptoAccruedAmount+$ptoBalance;
                                        }
                                        else {
                                            // Set the accrued amount to zero
                                            $ptoAccruedAmount=0;
                                            
                                            // Determine which was the culprit
                                            if ($ptoHoursAccruedThisYear>=$maxAnnually &&
                                                $ptoBalance>=$maxOverall){
                                                // let them know they are not accruing because they are capped out on both
                                                $infoAboutNotAccruingAtMax='Both PTO balances are capped out prior to this pay period. No PTO accrual will be allowed.';
                                            }
                                            else if ($ptoHoursAccruedThisYear>=$maxAnnually){
                                                // let them know they are not accruing because they are capped out on the annual amount
                                                $infoAboutNotAccruingAtMax='The annual amount of PTO accrued prior to this pay period is capped out. No PTO accrual will be allowed.';
                                            }
                                            else if ($ptoBalance>=$maxOverall){
                                                // let them know they are not accruing because they are capped out on overall PTO balance
                                                $infoAboutNotAccruingAtMax='The PTO balance was capped out prior to this pay period. No PTO accrual will be allowed.';
                                            }
                                        }

                                        // Check to see if anything looks wrong before trying to update
                                        if ($newPTOHoursAccruedThisYear==null || $newPTOHoursAccruedThisYear<0 ||
                                            $newPTOHoursBalance==null ||
                                            $lastPayPeriodHoursDecimal==null || $lastPayPeriodHoursDecimal<0){
                                            // Create a message about the PTO accrual
                                            $benefitsMessage=$sqlTest."\r\n\r\nBenefits Summary\r\n\r\n" .
                                                    "A new pay period has happened, but there seems to be a problem with the PTO values to update (" .
                                                    "PTOHoursAccruedThisYear=" .$newPTOHoursAccruedThisYear. ", ".
                                                    "PTOHoursBalance='" .$newPTOHoursBalance. "', ".
                                                    "LastPayPeriodHours='" .$lastPayPeriodHoursDecimal. "'). \r\n\r\n".
                                                    "Please see the TMS software team for more information and/or corrections.\r\n\r\n";
                                        }
                                        else {
                                            // Create a query to update the all fields in the benefits table that needs to be
                                            $sql='UPDATE employeebenefits ' .
                                                 'SET PTOHoursAccruedThisYear=' . $newPTOHoursAccruedThisYear . ', ' . 
                                                     'PTOBalance=' . $newPTOHoursBalance . ', ' . 
//                                                 'AverageHoursPerPayDay=' .  . ', ' . 
                                                     'HoursWorkedThisYear=' . $lastPayPeriodHoursDecimal . '+HoursWorkedThisYear, ' . 
                                                     'LastPayDateUpdated="' . $checkLastTimecardRow["MaxPayDateStart"] . '" ' . 
                                                 'WHERE UserID = ' . $timecardUserAssocRow["UserID"] . ';';

                                            // Update the benefits table
                                            $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 13");
                                        }
                                        
                                        // Create a message about the PTO accrual
                                        $benefitsMessage=$sqlTest."\r\n\r\nBenefits Summary\r\n\r\n" .
                                                "A new pay period has happened. Here is the accumulated PTO summary:\r\n".
                                                "PTO Hours Accrued Last Pay Period: " . round($ptoAccruedAmount,2) . "   " . $infoAboutNotAccruingAtMax ."\r\n" .
                                                "PTO Hours Used Last Pay Period: " . round($ptoUsed,2) . $usedPTOMessage . "\r\n" .
                                                "PTO Hours Accrued This Year: " . round($newPTOHoursAccruedThisYear,2) . "\r\n" .
                                                "PTO Hours Balance: " . round($newPTOHoursBalance,2) . "\r\n" .
                                                "Hours Worked This Year: " . round(($lastPayPeriodHoursDecimal+$hoursWorkedThisYear),2) . "\r\n\r\n" .
                                                "These values were based on tenure at the start of this pay period. These values are:\r\n" . 
                                                "Years Worked: " . $yearsWorkedAtPayPeriodStart . " Years\r\n" .
                                                "Accrual Rate: " . $ptoAccrualRate . " /30 Hours\r\n" .
                                                "MAX PTO Annually: " . $maxAnnually . " Hours\r\n" .
                                                "Max PTO Balance: " . $maxOverall . " Hours\r\n" .
                                                "For more information on current and next PTO values, visit the EES benefits page.\r\n\r\n";
                                    }
                                }

                                //Notify whomever wants/needs to be notified
                                notifyOfTimecardRollover ($db, $timecardUserAssocRow["UserID"], $timecardUserAssocRow["FirstName"], $timecardUserAssocRow["LastName"], 
                                                               ($lastTimecardAmountAssocRow["CurrentPaydaySeconds"]*1000), 
                                                               $checkLastTimecardRow["MaxPayDateStart"], $benefitsMessage);
                            }
                        }
                    }
                }
            }

            // Determine if we have a super user or the timecard user's executive looking at it
            if ($userRow["UserLevel"]=='SU' ||
                ($userRow["UserLevel"]=='EXECUTIVE' &&
                 $userRow["CompanyID"]==$companyID)){
                // Allow for edits
                $editableHTML='';

                // Show controls
                $controlsHiddenStyle = 'display: table-row;';

            }

            // Create the amount of time worked as though they are NOT clocked in
            $currentAmountWorked = $amountOfCurrentPaySeconds;
            
            // Determine if they are clocked in
            if ($clockToUse!='now'){
                // Create the dates for now and the last clock in
                $now = new DateTime("now", new DateTimeZone('America/Denver'));
                $lastStartTime = new DateTime($clockToUse, new DateTimeZone('America/Denver'));

                // Create a variable for current time worked
                $currentAmountWorked = $now->format("U")-$lastStartTime->format("U")+$amountOfCurrentPaySeconds;
            }

            // Time calculations for days, hours, minutes and seconds
            $hours = is_nan(floor($currentAmountWorked/(60*60))) ? 0 : floor($currentAmountWorked/(60*60));
            $minutes = is_nan(floor(($currentAmountWorked/(60))%60)) ? 0 : floor(($currentAmountWorked/(60))%60);
            $seconds = is_nan(floor(($currentAmountWorked)%60)) ? 0 : floor(($currentAmountWorked)%60);
            
            $returnValue = '
                <script language="JavaScript">
                    // Create a variable to hold the server hour time difference
                    serverTimezoneDiff = ' . $_SESSION['ServerTimezoneDiff'] . '*-1;

                    // setup the is clocked in flag
                    isClockedIn = ' . $isClockedIn . ';
                </script>
                <form action="updateTimecard.php" method="post" name="updateTimecard" enctype="multipart/form-data">  
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr align="left" valign="top">
                            <td width="50%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Name:</strong> 
                                            <input type="hidden" name="clockID" id="clockID" value="' . $clockID . '">
                                            <input type="hidden" name="CompanyID" id="CompanyID" value="' . $companyID . '">
                                            <input type="hidden" name="UserID" id="UserID" value="' . $timecardUserAssocRow["UserID"] . '">
                                            <input type="hidden" name="TaskID" id="TaskID" value="' . $taskID . '">
                                            <input type="hidden" name="StartLocation" id="StartLocation" value="' . $startLocation . '">
                                            <input type="hidden" name="EndLocation" id="EndLocation" value="' . $endLocation . '">
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input type="text" name="FirstLastName" id="FirstLastName" readonly="readonly" value="'. $timecardUserAssocRow["FirstName"] . ' ' . $timecardUserAssocRow["LastName"] .'">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Last Start Time: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="StartTime" id="StartTime" ' . $editableHTML . ' step=1 type="datetime-local" class="intext" style="width: 100%;" value="' . $startTime . '" >
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Last End Time: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="EndTime" id="EndTime" ' . $editableHTML . ' step=1 type="datetime-local" class="intext" style="width: 100%;" value="' . $endTime . '" >
                                        </td>
                                    </tr>  
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Rate Multiplier: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="RatePercentage" type="text" maxlength="8" class="intext" style="width: 100%; height: 19px" value="' . $ratePercentage . '" >
                                        </td>
                                    </tr>
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Pay Period: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle"> '
                                        . $db->getTypeAsSelectOptions('users', 'PayPeriod', 'PayPeriod', $payPeriod, null, '', false, '') . 
                                        ' </td>
                                    </tr>
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Pay Date Start: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="PayDateStart" id="PayDateStart" type="datetime-local" step=1 class="intext" style="width: 100%;" value="' . str_replace(" ","T",$payDateStart->format('Y-m-d H:i:s')) . '" >
                                        </td>
                                    </tr>
                                </table>
                            </td>
                            <td width="5%">
                            </td>
                            <td width="45%" valign="middle" align="center">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td align="center" valign="middle">
                                            <strong>Pay Period Clocked In Time: </strong> 
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="center" valign="middle">
                                            <br>
                                            <p id="PayPeriodTimerArea">
                                                Clock Hours: <font color="seagreen"><b>' . $hours . 'h ' . $minutes . 'm ' . $seconds . 's</b></font> 
                                                <br><br> 
                                                Decimal Hours: <font color="seagreen"><b>' . round(($currentAmountWorked/3600), 2) . '</b></font>
                                            </p>
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $laborCategoryHTML
                                    .
                                    '
                                    <tr>
                                        <td align="center" valign="middle">
                                            <br>
                                            <input type="hidden" id="formSubmitted" name="formSubmitted" value="TRUE">
                                            <input id="formSubmit" type="submit" onclick="javascript:preSubmitLogic();" style="cursor: hand; cursor: pointer;" value="' . $submitText . '"/>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </form>
                <script language="JavaScript">
                    // Code for validating the form
                    // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                    // for details
                    var frmvalidator = new Validator("updateTimecard", "formSubmit");
                    frmvalidator.addValidation("RatePercentage",
                                               "dec",
                                               "Please a rate multiplier a decimal.");
                    frmvalidator.addValidation("RatePercentage",
                                               "greaterthan=-1",
                                               "The rate multiplier be greater than or equal to zero.");
                </script>';
        }

        // Set a just clocked in field to false
        $_SESSION['justClockedIn']='FALSE';

        // Return whatever was created
        return $returnValue;
    }

    function getLaborCategoriess($db, $userRow, $selected){
        // Initialize the return
        $result = '';
        try {
            // Determine if this is an SU user
            if ($userRow["CompanyID"]==1){
                // Showing a totally different thing for non editable users on status
                if ($userRow["UserLevel"]=='EXECUTIVE' || $userRow["UserLevel"]=='SU'){
                    // Create the query to run
                    $sql='SELECT * FROM laborcategories ORDER BY Name;';

                    // Query the rows for the labor categories
                    $rows = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 14");

                    // If there are rows, then they are good to go.
                    if ($rows == null){
                        return $result;
                    }
                    else{
                        // Loop through the returned results
                        $rowNumber = 0;

                        // Loop through the rows
                        while ($row=mysqli_fetch_array($rows)){
                            // Determine if this is one that is to be selected
                            $selectedText='';
                            if ($selected != null and $selected==$row["LaborCategoryID"]) {
                                // Create the selected html
                                $selectedText='selected';
                            }

                            // Add this option to the select
                            $result=$result . '<option title="' . $row["Description"] . '" value="' . $row["LaborCategoryID"] . '" ' . $selectedText . '>' . $row["Name"] . ' </option>';
                        }

                        // Start the return with the beginning of the select
                        $result='<select id="laborCategory" name="laborCategory" onchange="">' 
                                . $result . 
                                '</select>
                                ';
                    }
                }
                else {
                    // Create the query to run
                    $sql='SELECT * FROM laborcategories WHERE LaborCategoryID=' . $selected . ' ORDER BY Name;';

                    // Query the database 
                    $row = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 15");

                    // If there are rows, then they are good to go.
                    if ($row == null){
                        return $result;
                    }
                    else{
                        // Attempt to get the selected row
                        $assocRow = $row->fetch_assoc();

                        // Only need a text box to show them their status, since they cannot change their own company
                        $result='<input class="intext" name="laborCategory" id="laborCategory" type="text" style="width: 100%;" value="' . $assocRow["Name"] . '" disabled>';
                    }
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getTimecard($db, $userRow, $timecardUserAssocRow, $inClockID=null, $inPayDateStart=null){
        // Set the return to nothing
        $returnValue = '';

        // Determine if there is a timecard user row and a user row or not
        if ($timecardUserAssocRow!=null &&
            $userRow!=null) {
            $editableHTML = 'readonly="readonly"';
            $controlsHiddenStyle = 'display: none;';

            // Fill in any variables that we can from the query
            $companyID = $timecardUserAssocRow["CompanyID"];
            $firstPayDate = $timecardUserAssocRow["FirstPayDate"];
            $payPeriod = $timecardUserAssocRow["PayPeriod"];
            
            // Init all of the other variables. Start and end times as though this is a PTO day.
            $clockID = null;
            $taskID = -1;
            $startTime = str_replace(" ","T",date('Y-m-d 08:00:00', time()));
            $endTime = str_replace(" ","T",date('Y-m-d 16:00:00', time()));  
            $ratePercentage = 1;
            $payDateStart=str_replace(" ","T",$inPayDateStart);
            $startLocation = '';
            $endLocation = '';
            $laborCategory = null;
            
            $modifyType = 'add';

            // Determine if there is a date passed in for the pay date
            if ($inPayDateStart==null){
                // Set the value to their first pay date
                $payDateStart=str_replace(" ","T",$firstPayDate);
            }

            // Determine if there is a clockID or not
            if ($inClockID!=null && $inPayDateStart!=null){
                // Create a query to to get most recent timecard information if it is still running
                $sql = 'SELECT * FROM laborclock lc1  ' . 
                       'WHERE lc1.ClockID=' . $inClockID . ';';

                // Attempt to get the most recent timecard info
                $timecardRow = $db->queryDB($sql, $userRow, "timecards_presentation Form occurance 16");

                // determine if the is a last entry in the database
                if ($timecardRow!=null){
                    // Attempt to get the timecard row
                    $timecardAssocRow = $timecardRow->fetch_assoc();

                    // Set the things we can
                    $clockID = $inClockID;
                    $taskID = $timecardAssocRow["TaskID"];
                    $startTime=str_replace(" ","T",$timecardAssocRow["StartTime"]);
                    $endTime=str_replace(" ","T",$timecardAssocRow["EndTime"]);
                    $ratePercentage = $timecardAssocRow["RatePercentage"];
                    $startLocation = $timecardAssocRow["StartLocation"];
                    $endLocation = $timecardAssocRow["EndLocation"];
                    $laborCategory = $timecardAssocRow["CurrentLaborCategoryID"];
                }

                // Change this to an update
                $modifyType = 'update';
            }

            // Determine if we have a super user or the timecard user's executive looking at it
            if ($userRow["UserLevel"]=='SU' ||
                ($userRow["UserLevel"]=='EXECUTIVE' &&
                 $userRow["CompanyID"]==$companyID)){
                // Allow for edits
                $editableHTML='';

                // Show controls
                $controlsHiddenStyle = 'display: table-row;';

            }

            $returnValue = '
                <form action="' . $modifyType . 'Timecard.php" method="post" name="' . $modifyType . 'Timecard" enctype="multipart/form-data">  
                    <table width="40%" border="0" cellpadding="0" cellspacing="0" class="usial">
                        <tr>
                            <td height="39" align="right" valign="middle">
                                <strong>Name:</strong> 
                                <input type="hidden" name="ClockID" id="ClockID" value="' . $clockID . '">
                                <input type="hidden" name="CompanyID" id="CompanyID" value="' . $companyID . '">
                                <input type="hidden" name="UserID" id="UserID" value="' . $timecardUserAssocRow["UserID"] . '">
                                <input type="hidden" name="TaskID" id="TaskID" value="' . $taskID . '">
                            </td>
                            <td width="5%">
                            </td>
                            <td height="39" align="left" valign="middle">
                                <input type="text" name="FirstLastName" id="FirstLastName" readonly="readonly" value="'. $timecardUserAssocRow["FirstName"] . ' ' . $timecardUserAssocRow["LastName"] .'">
                            </td>
                        </tr>
                    </table>
                    <table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr align="left" valign="top">
                            <td width="49%">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Start Time: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="StartTime" id="StartTime" ' . $editableHTML . ' step=1 type="datetime-local" class="intext" style="width: 100%;" value="' . $startTime . '" >
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Start Location: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="StartLocation" id="StartLocation" ' . $editableHTML . ' type="text" maxlength="20" class="intext" style="width: 100%;" value="' . $startLocation . '" >
                                        </td>
                                    </tr>
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Pay Date Start: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="PayDateStart" id="PayDateStart" type="datetime-local" step=1 class="intext" style="width: 100%;" value="' . $payDateStart . '" >
                                        </td>
                                    </tr>
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Rate Multiplier: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="RatePercentage" type="text" maxlength="8" class="intext" style="width: 100%; height: 19px" value="' . $ratePercentage . '" >
                                        </td>
                                    </tr>
                                </table>
                            </td>
                            <td width="2%">
                            </td>
                            <td width="49" align="center">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>End Time: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="EndTime" id="EndTime" ' . $editableHTML . ' step=1 type="datetime-local" class="intext" style="width: 100%;" value="' . $endTime . '" >
                                            <input type="hidden" name="BeforeEndTime" id="BeforeEndTime" value="' . $endTime . '">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>End Location: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                            <input name="EndLocation" id="EndLocation" ' . $editableHTML . ' type="text" maxlength="20" class="intext" style="width: 100%;" value="' . $endLocation . '" >
                                        </td>
                                    </tr>
                                    <tr>
                                        <td height="39" align="right" valign="middle">
                                            <strong>Labor Category: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle">
                                        ' .
                                        getLaborCategoriess($db, $userRow, $laborCategory)
                                        .'
                                        </td>
                                    </tr>
                                    <tr style="' . $controlsHiddenStyle . '">
                                        <td height="39" align="right" valign="middle">
                                            <strong>Pay Period: </strong> 
                                        </td>
                                        <td width="5%">
                                        </td>
                                        <td height="39" align="left" valign="middle"> '
                                        . $db->getTypeAsSelectOptions('users', 'PayPeriod', 'PayPeriod', $payPeriod, null, '', false, '') . 
                                        ' </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                    <p align="right">
                        <input type="hidden" name="formSubmitted" value="TRUE">
                        <input type="hidden" name="fromEditButton" value="TRUE">
                        <input type="hidden" name="clockID" value="' . $clockID . '">
                        <input id="formSubmit" type="submit" style="cursor: hand; cursor: pointer;" value="' . $modifyType . ' timecard" />
                    </p>
                </form>
                <script language="JavaScript">
                    // Code for validating the form
                    // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                    // for details
                    var frmvalidator = new Validator("' . $modifyType . 'Timecard", "formSubmit");
                    frmvalidator.addValidation("RatePercentage",
                                               "dec",
                                               "Please a rate multiplier a decimal.");
                    frmvalidator.addValidation("RatePercentage",
                                               "greaterthan=-1",
                                               "The rate multiplier be greater than or equal to zero.");
                </script>';
        }

        // Return whatever was created
        return $returnValue;
    }

?>
