<?php    
    include '../database.php';

    function checkForMachiningTask($db, $inMachineID){
        $result = "";
        
        try {
            // Check to see if the passed in variable is a number
            if (is_numeric($inMachineID) && $inMachineID>0){
                // Set and initialize variables
                $machineID = $inMachineID;
                
                // Create a query to see if the maching has a machining task
                $sql = 'SELECT tml.* 
                        FROM tasktomachinelinker tml 
                        LEFT JOIN tasks t on tml.TaskID = t.TaskID
                        LEFT JOIN status s on t.StatusID = s.StatusID
                        WHERE tml.MachineID = ' . $machineID . ' 
                        AND s.Name = "Machining";';
                
                // run the query to get the task ID
                $machineHasMachingQuery = $db->queryDB($sql, null, "check_to_see_if_has_machining_task Form occurance 1");

                // Determine if the machine moving to already has a machining task .
                $machineHasMachingAssocRow=null;
                if (mysqli_num_rows($machineHasMachingQuery)>0){
                    // Get the Row returned
                    $machineHasMachingAssocRow = $machineHasMachingQuery->fetch_assoc();
                    
                    // All I need to do now is return the task ID that is in machining
                    return $machineHasMachingAssocRow["TaskID"];
                }
            }
            else {
                // Return an error code
                return 'ABORT MOVE (check_to_see_if_has_machining_task)::Invalid Machine ID.  Aborting move.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT MOVE (check_to_see_if_has_machining_task)::There was ' . 
                    'an error check for a machining task.\n\n The error is: ' . 
                    $ex->getMessage();
        }

        // Return whatever we got
        return $result;
    }
    
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());
    
    // Set the return as fail at first
    $return="Fail";
    
    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser != null){
        // Set defaults for the passed in variables
        $machineID=-1;

        // Check for the index before moving
        if (isset($_GET['machineID']) ){
            // Get the machine that we are doing the checks on
            $machineID = $_GET['machineID'];
        }

        // Go and get the machines and all of their tasks
        $return = checkForMachiningTask($db, $machineID);
    }
    
    echo $return;
?>   

