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

    function resortMachineOrder($db, $userRow, $indexBefore, $machineBefore, $indexAfter, $machineAfter){
        $result = "";
        
        try {
            // Create a query to determine if the task that is moving is in machining.
            $sql = 'SELECT * FROM tasktomachinelinker tml 
                    LEFT JOIN tasks t on tml.TaskID = t.TaskID
                    LEFT JOIN status s on t.StatusID = s.StatusID
                    WHERE tml.TheOrder = ' . $indexBefore . '
                    AND MachineID = ' . $machineBefore . ' 
                    AND s.Name = "Machining";';
            
            // run the query to get the task ID
            $movingTaskIsMachingSQL = $db->queryDB($sql, null, "reorder_tasks_on_machines Form occurance 1");

            // Now I should determine if the machine it is going on to already has a machining task.
            $sql = 'SELECT * FROM tasktomachinelinker tml 
                    LEFT JOIN tasks t on tml.TaskID = t.TaskID
                    LEFT JOIN status s on t.StatusID = s.StatusID
                    WHERE tml.MachineID = ' . $machineAfter . ' 
                    AND s.Name = "Machining";';

            // run the query to get the task ID
            $machingMovingToHasMachingSQL = $db->queryDB($sql, null, "reorder_tasks_on_machines 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($movingTaskIsMachingSQL)==1 || 
                mysqli_num_rows($machingMovingToHasMachingSQL)>0){
                // Determine if they are moving on the same machine
                if ($machineBefore==$machineAfter){
                    // Determine if this machine has a machining task and they are trying to move a task in front of it.
                    if (mysqli_num_rows($machingMovingToHasMachingSQL)>0 &&
                        $indexAfter==1){
                        // return a message for not allowing this movement on the same machine
                        return 'ABORT MOVE (reorder_tasks_on_machines)::Cannot move this ' . 
                               'task in front of a task that is in the machining state.';
                    }
                    // Determine if the task is machining and not first slot.  Cannot move the machining task out of the first slot.
                    else if (mysqli_num_rows($movingTaskIsMachingSQL)==1 && 
                             $indexAfter !=1){
                        // return a message for not allowing this movement on the same machine
                        return 'ABORT MOVE (reorder_tasks_on_machines)::Cannot move a ' . 
                               'machining task into a slot that is NOT the first slot.';
                    }
                }
                // Else they are moving to a different machine
                else{
                    // Determine if this machine has a machining task and they are trying to move a task in front of it.
                    if (mysqli_num_rows($machingMovingToHasMachingSQL)>0 &&
                        $indexAfter==1){
                        // return a message for not allowing this movement on the same machine
                        return 'ABORT MOVE (reorder_tasks_on_machines)::Cannot move this ' . 
                               'task in front of a task that is in the machining state.';
                    }
                    // Determine if the task is machining and not first slot.  Cannot move the machining task out of the first slot.
                    else if (mysqli_num_rows($movingTaskIsMachingSQL)==1 && 
                             $indexAfter !=1){
                        // return a message for not allow this movement on the different machines
                        return 'ABORT MOVE (reorder_tasks_on_machines)::Cannot move a ' . 
                               'machining task into a slot that is NOT the first slot.';
                    }
                }
            }
            
            // Set up what the user posted at first, to be changed with logic.
            $machineID = $machineAfter;
            $oldMachineID = $machineBefore;
            $machineTaskOrder = $indexAfter;
            $oldMachineTaskOrder = $indexBefore;
            
            // Create a query to get the task ID at the position passed in
            $sql = 'SELECT * FROM tasktomachinelinker WHERE TheOrder = ' . $indexBefore . ' AND MachineID = ' . $machineBefore . ';';

            // run the query to get the task ID
            $taskIDAtQuery = $db->queryDB($sql, null, "reorder_tasks_on_machines Form occurance 1");

            // Attempt to run the query and evaluate the response
            if (mysqli_num_rows($taskIDAtQuery)==1){
                // Get the values from the query
                $taskIDAtAssoc = $taskIDAtQuery->fetch_assoc();

                // Get the task ID to use later
                $updateTaskID = $taskIDAtAssoc["TaskID"];

                // Determine if any of this has changed before I start the reorder logic
                if ($machineID != $oldMachineID ||
                    $machineTaskOrder != $oldMachineTaskOrder){
                    // Put the task moving a very the low state, so we do not lose info on it
                    $sql='UPDATE tasktomachinelinker SET TheOrder=-999 ' . 
                         'WHERE TaskID = ' . $updateTaskID . ';';

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 2");

                    // Change the order down for the old machine after this one to fill the gap
                    $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                           'WHERE TheOrder >= ' . ($oldMachineTaskOrder) . ' ' . 
                           'AND TheOrder < 99999 ' .
                           'AND MachineID = ' . $oldMachineID . ';'; 

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 3");
                }

                // Determine if we even have anything on a machine now
                if ($machineID>0){
                    // Create a query to get the max order on the machine in question
                    $sql = 'SELECT (Max(TheOrder)+1) as MaxOrder ' .
                           'FROM tasktomachinelinker ' .
                           'WHERE MachineID = ' . $machineID . ' ' .
                           'AND TheOrder < 99999;';

                    // run the query to get the max order on the machine in question
                    $currentMaxOrder = $db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 4");
                    $currentAssocMaxOrder = $currentMaxOrder->fetch_assoc();

                    // Ensure it is a number 
                    if (!is_numeric($machineTaskOrder)){
                        // Set it to the highest number to order it on the bottom
                        $machineTaskOrder=99999;
                    }

                    // Determine if there is currently ANY on the machine
                    if($currentAssocMaxOrder["MaxOrder"] == null){
                        // Set the order to the first one, because there are none
                        $machineTaskOrder=1;                    
                    }
                    // Determine if the order is greater than the current lowest order (highest number)
                    else if($machineTaskOrder  >= $currentAssocMaxOrder["MaxOrder"]){
                        // Set the order to the calculated order
                        $machineTaskOrder=$currentAssocMaxOrder["MaxOrder"];                    
                    }
                    // Then we have to make a hole for this one on this machine
                    else {
                        // Create a hole in this machine by adding existing tasks down the list
                        $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder+1 ' .
                               'WHERE TheOrder >= ' . ($machineTaskOrder) . ' ' . 
                               'AND TheOrder < 99999 ' .
                               'AND MachineID = ' . $machineID . ';'; 

                        // Attempt to run the query
                        $db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 5");
                    }

                    // Update the task to what it should be
                    $sql='UPDATE tasktomachinelinker SET TheOrder=' . $machineTaskOrder . ', ' . 
                         'MachineID = ' . $machineID . ' ' .   
                         'WHERE TaskID = ' . $updateTaskID . ';';

                    // Attempt to run the query and evaluate the response
                    if (!$db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 3")){
                        echo ('<script>alert("machine was NOT added to task. Please check the data and try again.");</script>');
                    }
                }

                // Determine if the task they are moving was the machining task on the previous machine.
                // That means that it will also have to be the machining task on the next machine if we 
                // are here in the code.                
                if (mysqli_num_rows($movingTaskIsMachingSQL)==1){
                    // Create a query to remove all suggested tools from the old and new machines
                    $sql = 'UPDATE assignedtools ' . 
                           'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' .
                               'SuggestedExposedLength=0, SuggestedNote="", SuggestedUseNewTool=0 ' . 
                           'WHERE MachineID = ' . $machineBefore . ' ' . 
                           'OR MachineID = ' . $machineAfter . ';'; 

                    // Run the update query
                    $db->queryDB($sql, $userRow, "reorder_tasks_on_machines Form occurance 4");

                    // Now set the tools appropriately for this task on the new machine
                    $result = setTaskToolsAsSuggested($db, $userRow, $taskIDAtAssoc["TaskID"], $machineAfter);   
                }                
            }
            else {
                // Setup an error message for not being able to get the task ID
                $result = 'ABORT MOVE (reorder_tasks_on_machines)::There is no task ID at machine ID ' . 
                          $machineBefore . ' and position ' . $indexBefore . ' to remove.';
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'REFRESH TASKS (reorder_tasks_on_machines)::There was an error trying to reorder  ' . 
                      'the tasks on Machine ID ' . $machineBefore . ' and position ' . 
                      $indexBefore . ' to remove.\n\n The error is: ' . $ex->getMessage();

        }

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

    $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 (reorder_tasks_on_machines)::Your session has expired.  ' . 
             'Refresh the page before reordering the tasks.';
    }
    else {
        // Set defaults for the passed in variables
        $indexBefore=-1;
        $machineBefore=-1;
        $indexAfter=-1;
        $machineAfter=-1;

        // Check for the index before moving
        if (isset($_GET['indexBefore']) ){
            // Hold on to the index before moving passed in
            $indexBefore = $_GET['indexBefore'];
        }

        // Check for the machine before moving
        if (isset($_GET['machineBefore']) ){
            // Hold on to the machine before moving passed in
            $machineBefore = $_GET['machineBefore'];
        }

        // Check for the index after moving
        if (isset($_GET['indexAfter']) ){
            // Hold on to the index after moving passed in
            $indexAfter = $_GET['indexAfter'];
        }

        // Check for machine after moving
        if (isset($_GET['machineAfter']) ){
            // Hold on to the machine after moving passed in
            $machineAfter = $_GET['machineAfter'];
        }

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

        // Go and get the machines and all of their tasks
        echo resortMachineOrder($db, $userRow, $indexBefore, $machineBefore, $indexAfter, $machineAfter);
    }
?>   

