<?php
    require_once '../database.php';
    require_once '../global_functions.php';

    // Method to modify the labor clock
    function modifyUserCurrentLaborClock($db, $userRow, $laborClockID, $laborCategoryID){
        // Assume that we are successful unless proven otherwise
        $errorString='';
        
        try {
            // Determine if the IDs necessary are one greater than 0
            if ($laborClockID!=null && $laborClockID>0 &&
                $laborCategoryID!=null && $laborCategoryID>0){
                // We need to do a query to see if this status is one changeable by this user
                $sql='SELECT UsesPTO ' . 
                     'FROM laborcategories ' . 
                     'WHERE LaborCategoryID=' . $laborCategoryID .';';

                // Attempt to run the select query
                $row = $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 1");

                // determine if there is a row for this category
                if ($row!=null){
                    // Attempt to get the row
                    $assocRow = $row->fetch_assoc();

                    // Get the value that that would determine if this is a row they can update
                    $usesPTO = $assocRow["UsesPTO"];

                    // Determine if they can update it
                    if ($usesPTO==1){
                        // Return an error letting them know why they cannot update it
                        return 'ABORT MODIFY (change_user_clock_status)::Putting the user into this state requires the use of PTO. Doing it here is not the appropriate place to do it. Please ensure that you are entering PTO as it should be or inform the appropriate level person, so they can do it properly. Aborting...';
                    }
                }

                // We need to do a query to see if this status is one changeable by this user
                $sql='SELECT lcg.UsesPTO ' .
                     'FROM laborclock lc ' .
                     'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID = lcg.LaborCategoryID ' .
                     'WHERE lc.ClockID=' . $laborClockID .';';

                // Attempt to run the select query
                $row = $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 2");

                // determine if there is a row for this category
                if ($row!=null){
                    // Attempt to get the row
                    $assocRow = $row->fetch_assoc();

                    // Get the value that that would determine if this is a row they can update
                    $usesPTO = $assocRow["UsesPTO"];

                    // Determine if they can update it
                    if ($usesPTO==1){
                        // Return an error letting them know why they cannot update it
                        return 'ABORT MODIFY (change_user_clock_status)::Taking this user out of PTO status is not allowed at this screen. If necessary, see a higher lever user so they can do it properly. Aborting...';
                    }
                }

                // Create a query to determine what status the user is at currently
                $sql='SELECT lc.*, lcg.Name AS ClockedInName, u.FirstName, u.LastName ' .
                     'FROM laborclock lc ' .
                     'LEFT JOIN laborcategories lcg ON lc.CurrentLaborCategoryID = lcg.LaborCategoryID ' .
                     'LEFT JOIN users u ON lc.UserID = u.UserID ' .
                     'WHERE lc.ClockID=' . $laborClockID .';';
                
                // Attempt to run the select query
                $row = $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 3");

                // determine if there is a row for this category
                if ($row!=null){
                    // Attempt to get the row
                    $assocRow = $row->fetch_assoc();

                    // Get the name of the clocked in status
                    $clockedInName = $assocRow["ClockedInName"];
                    
                    // Determine if they are coming from the 10 minute break
                    if ($clockedInName=="10 Min Break"){
                        // Assume end time at first and convert to PHP datetime
                        $dateToUse = new DateTime($assocRow["CurrentLaborCategoryStartTime"]); 

                        // Get the difference between now as interval and decimal 
                        // TODO: Minus 1 for the hour difference between server and workplace.
                        $dateDiff  = $dateToUse->diff(new DateTime()); 
                        $decimalHours = round($dateDiff->s / 3600 + $dateDiff->i / 60 + 
                                       $dateDiff->h + $dateDiff->days * 24, 2);
                        $minutes=round((($decimalHours)*60), 2);

                        // Determine if they have been on 10 minute break for longer than 10 minutes
                        if ($minutes>10){
                            // Create a query to add a note about the employee of them going past the 10 minutes
                            $sql='INSERT INTO notes (AssociatedCategoryID, Category, Title, Note, EnteredByID) ' .
                                 'VALUES(' .$assocRow["UserID"] . ', "EMPLOYEE", "Went Over 10 Minutes For Break", ' . 
                                 '"This is an automated message recording that ' . $assocRow["FirstName"] .
                                 ' ' . $assocRow["LastName"] . ' took ' . $minutes . ' minutes on their 10 minute ' . 
                                 'break instead of the allotted 10 minutes.", ' . $userRow["UserID"] . ')';
                            
                            // Attempt to run the update query
                            $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 4");
                        }
                        
                        // Create a query to add time to their 10 minute break sum
                        $sql='UPDATE laborclock ' . 
                             'SET BreakTimeTaken=BreakTimeTaken+' . $minutes . 
                             'WHERE ClockID= ' . $laborClockID . ';';

                        // Attempt to run the update query
                        $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 5");
                        
                    }
                }
                
                // attempt to update the labor clock with the new category
                $sql='UPDATE laborclock ' . 
                     'SET CurrentLaborCategoryID=' . $laborCategoryID . ', ' . 
                     '    CurrentLaborCategoryStartTime=CURRENT_TIMESTAMP ' . 
                     'WHERE ClockID= ' . $laborClockID . ';';

                // Attempt to run the update query
                $db->queryDB($sql, $userRow, "change_user_clock_status form occurance 6");
            }
            else{
                // Create the error string to return back to the caller
                return 'ABORT MODIFY (change_user_clock_status)::The IDs passed in for either the labor clock or the category is not correct. Aborting...';
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT MODIFY (change_user_clock_status)::There an uncaught error while setting new tool slots to prepare for g-code mods.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // Return what could be an error string
        return $errorString;
    }
    
    $db = new Database();
    $db->setupTmsDB();
    
    // Set defaults for used variables
    $sessionID=-1;
    $userRow = null;

    // check the passed in session ID
    if (isset($_GET['sessionID']) ){
        // get the passed in session ID
        $sessionID = $_GET['sessionID'];
    }

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser($sessionID);
    if (mysqli_num_rows($currentUser)!=1){
        echo 'ABORT MODIFY (change_user_clock_status)::Your session has expired.  ' . 
             'Refresh the page before modifying the task for present.';
    }
    else {
        // Set defaults for the passed in variables
        $laborClockID=-1;
        $machineID=-1;

        // check the passed in labor clock ID
        if (isset($_GET['laborClockID']) ){
            // get the passed in labor clock ID
            $laborClockID = $_GET['laborClockID'];
        }

        // check the passed in Labor Category ID
        if (isset($_GET['laborCategoryID']) ){
            // get the passed in Labor Category ID
            $laborCategoryID = $_GET['laborCategoryID'];
        }

        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        // Attempt to adjust the tools.  Assign the error string the result.
        $errorString=modifyUserCurrentLaborClock($db, $userRow, $laborClockID, $laborCategoryID);

        // return any error result
        echo $errorString;
    }
?>