<?php    
    include_once dirname(__FILE__) . '/../setup_presentation.php';
    include_once dirname(__FILE__) . '/../global_after_session.php';
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';

    function recalculateToolsForTask($db, $userRow, $inTaskID, $inMachinineID){
        $result = "";
        
        // Set up what the user posted at first, to be changed with logic.
        $taskID = $inTaskID;
        $machinineID = $inMachinineID;
        
        try {
            // Ensure that we have a task and machine to work on
            if ($taskID>0 && 
                $machinineID>0){
                // Create a query to determine if this is a machine that we currently handle.
                $sql='SELECT m.Type ' . 
                     'FROM tasktomachinelinker ttml ' . 
                     'LEFT JOIN machines m ON ttml.MachineID=m.MachineID ' .
                     'WHERE TaskID=' . $taskID . ';';

                // Run the query
                $machineType = $db->queryDB($sql, $userRow, "recalculate_machining_task_tools Form occurance 1");

                // Get the assoc row
                $machineTypeAssocRow = $machineType->fetch_assoc();
                
                // Determine if there are any rows. 
                // TODO: Currently we are only handling Mills for the tools. Update this as we handle more.
                if ($machineType["Type"] != 'MILL'){
                    // Send a message back to lewt them know we are not handling this type of machine
                    $returnString = 'INFO MESSAGE (recalculate_machining_task_tools)::There was a problem handling this type of machine.. Aborting...';
                    
                    // Determine if we have a row.
                    if ($machineType["Type"] != null){
                        // Send a message back to lewt them know we are not handling this SPECIFIC type of machine
                        $returnString = 'INFO MESSAGE (recalculate_machining_task_tools)::We do not currently handle tool modifications for machine type ' . $machineType["Type"] . '. Aborting...';
                    }
                    
                    // Return from this method with the 'info message'
                    return $returnString;
                }

                // Create a query to determine if there are any tools unassigned
                $sql = 'SELECT COUNT(*) AS AmountOfToolsUnassigned ' . 
                       'FROM tooltotasklinker ' . 
                       'WHERE TaskID = ' . $taskID . ' ' .
                       'AND ToolPosition <= 0;';
                
                // Run the query
                $toolsUnassignedSQL = $db->queryDB($sql, null, "recalculate_machining_task_tools Form occurance 1");
                
                // Check the results of the queries.  If either returns a row, then that could be cause for abort
                if (mysqli_num_rows($toolsUnassignedSQL)>0){
                    // Get the assoc row
                    $taskOnMachineAssocRow = $toolsUnassignedSQL->fetch_assoc();

                    // Determine if there are any unassigned tools
                    if ($taskOnMachineAssocRow["AmountOfToolsUnassigned"]>0){
                        // return a message for not allowing this to happen
                        return 'ABORT MOVE (recalculate_machining_task_tools)::Cannot move this ' . 
                               'task into machining because there are ' . 
                               $taskOnMachineAssocRow["AmountOfToolsUnassigned"] . ' ' .
                               'tools assigned to this task that do NOT have a position ' .
                               'defined.';
                    }
                }
                
                // Create a query to remove all suggested tools before I put any new suggested tools into the system
                $sql = 'UPDATE assignedtools ' . 
                       'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' .
                           'SuggestedExposedLength=0, SuggestedNote="", SuggestedUseNewTool=0 ' . 
                       'WHERE MachineID = ' . $machinineID . ';'; 
                
                // Run the update query
                $db->queryDB($sql, $userRow, "recalculate_machining_task_tools Form occurance 2");
                
                // Setup the result to give information about the move, if necessary
                $result = setTaskToolsAsSuggested($db, $userRow, $taskID, $machinineID);

                // Create a query to clear out the hold flags
                $sql = 'UPDATE tasktomachinelinker SET IsPendingApproval=0, ' . 
                       'IsPendingTools=0, IsWaitingToBeReviewed=0 ' .
                       'WHERE MachineID = ' . $machinineID . ' ' . 
                       'AND TaskID = ' . $taskID . ';'; 

                // Run the update query
                $db->queryDB($sql, $userRow, "recalculate_machining_task_tools Form occurance 3");
                
                // Create a query to clear out the material hold flags on all job blanks for this task
                $sql = 'UPDATE jobblanks SET IsPendingStock=0 ' .
                       'WHERE TaskID = ' . $taskID . ';'; 

                // Run the update query
                $db->queryDB($sql, $userRow, "recalculate_machining_task_tools Form occurance 4");
            }
            else {
                // Send and error message back
                return 'ABORT MOVE (recalculate_machining_task_tools)::There is no task ' . 
                          'or machine to change to the machining. Aborted.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT MOVE (recalculate_machining_task_tools)::There was an error ' . 
                      'trying to move the task ID ' . $taskID . ' to machining. ' . 
                      '\n\n The error is: \n' . $ex->getMessage();
        }

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

    // Set defaults for the passed in variables
    $sessionID=-1;

    // 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 MOVE (recalculate_machining_task_tools)::Your session has expired.  ' . 
             'Refresh the page before moving this task into machining.';
    }
    else {
        // Set defaults for the passed in variables
        $taskID=-1;
        $machinineID=-1;

        // Check for the task ID
        if (isset($_GET['taskID']) ){
            // Hold on to the task ID
            $taskID = $_GET['taskID'];
        }

        // Check for the machine ID
        if (isset($_GET['machineID']) ){
            // Hold on to the machine ID
            $machinineID = $_GET['machineID'];
        }

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

        // Move this task into machining. This will include moving tools into the state to get ready.
        echo recalculateToolsForTask($db, $userRow, $taskID, $machinineID);
    }
?>   

