<?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 resyncTaskToolsToMachining($db, $userRow, $inTaskID, $inMachinineID){
        $result = "";
        
        // Set up what the user posted at first, to be changed with logic.
        $taskID = $inTaskID;
        $machinineID = $inMachinineID;
        $assignToUserID = $inAssignToUserID;
        
        try {
            // Ensure that we have a task and machine to work on
            if ($taskID>0 && 
                $machinineID>0){
                $currentSuccess=true;
                $duplicateToolsString="";
                hasDuplicateToolsInTaskSetups($db, $userRow, $currentSuccess, $duplicateToolsString, $inTaskID);
                // Determine if we have duplicates.  If so, fail to move the task forward.
                if ($duplicateToolsString!==""){
                    // Send and error message back
                    return "ABORT RESYNC (resync_task_tools_to_machine)::There are duplicate tools in G-Code of some setups copied. Information on those setups are as follows:\n" . $duplicateToolsString . "\n\n";
                }
                
                // 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, "resync_task_tools_to_machine Form occurance 8");
                
                // 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, "resync_task_tools_to_machine Form occurance 2");
                
                // 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, "modify_task_for_presentation Form occurance 1");

                // Get the assoc row
                $machineTypeAssocRow = $machineType->fetch_assoc();
                
                // 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 && 
                        ($machineTypeAssocRow["Type"] != null && $machineTypeAssocRow["Type"] == 'MILL')){
                        // return a message for not allowing this to happen
                        return 'ABORT RESYNC (resync_task_tools_to_machine)::Cannot resync this ' . 
                               'task because there are ' . $taskOnMachineAssocRow["AmountOfToolsUnassigned"] . ' ' .
                               'tools assigned to this task that do NOT have a position defined.';
                    }
                }
                
                // Only set tools for approved machines
                if ($machineTypeAssocRow["Type"] != null && $machineTypeAssocRow["Type"] == "MILL"){
                    // Setup the result to give information about the move, if necessary
                    $result = setTaskToolsAsSuggested($db, $userRow, $taskID, $machinineID);
                }
                // TODO: Currently we are only handling Mills for the tools. Update this as we handle more.
                else if ($machineTypeAssocRow["Type"]!=null && $machineTypeAssocRow["Type"] != "MILL"){
                    // Send a message back to lewt them know we are not handling this type of machine
                    $result = 'INFO MESSAGE (resync_task_tools_to_machine)::This is an unknown machine. No tools were touched...';

                    // Determine if we have a value.
                    if ($machineTypeAssocRow["Type"]!=null){
                        // Send a message back to lewt them know we are not handling this SPECIFIC type of machine
                        $result = 'INFO MESSAGE (resync_task_tools_to_machine)::We do not currently handle tool modifications for machine type ' . $machineTypeAssocRow["Type"] . '. No tools were touched...';
                    }
                }
            }
            else {
                // Send and error message back
                return 'ABORT RESYNC (resync_task_tools_to_machine)::There is no task ' . 
                          'or machine to resync. Aborted.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT RESYNC (resync_task_tools_to_machine)::There was an error ' . 
                      'trying to resync the task ID ' . $taskID . ' for 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 RESYNC (resync_task_tools_to_machine)::Your session has expired.  ' . 
             'Refresh the page before resyncing this task.';
    }
    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 resyncTaskToolsToMachining($db, $userRow, $taskID, $machinineID);
    }
?>   

