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

    function checkForGoodOrder($db, $indexBefore, $machineBefore, $statusBefore, 
                                    $indexAfter,  $machineAfter,  $statusAfter,
                                    $taskID){
        $result = "";
        
        try {
            // Double-Check these.  Should have checked them before being passed in though. 
            // Determine if ANYTHING relevant is changing
            if ($indexBefore!=$indexAfter ||
                $machineBefore!=$machineAfter ||
                $statusBefore!=$statusAfter){
                // Set and initialize variables
                $wasMachining = 0;
                $wantsMachining = 0;
                $isThereAMachingTaskOnTargetMachine = 0;
                $isThisMachingTaskOnTargetMachine = 0;
                
                // Create a query to get check on both phases to see if either was or wants to be machining
                $sql = 'SELECT IF(' . $statusBefore . '=s.StatusID, 1, 0) AS WasMachining, ' .
                       '       IF(' . $statusAfter . '=s.StatusID, 1, 0) AS WantsMachining  ' .
                       'FROM status s ' .
                       'WHERE Name = "Machining";';
                
                
                // Run the query
                $machiningStatusQuery = $db->queryDB($sql, null, "check_to_allow_tasks_on_machines Form occurance 1");

                // Determine if we have one row to look at
                $machiningStatusAssocRow=null;
                if (mysqli_num_rows($machiningStatusQuery)==1){
                    // Get the Row returned
                    $machiningStatusAssocRow = $machiningStatusQuery->fetch_assoc();
                    
                    // Set the values we are looking for
                    $wasMachining = $machiningStatusAssocRow["WasMachining"];
                    $wantsMachining = $machiningStatusAssocRow["WantsMachining"];
                }
                
                // Now I should determine if the machine it is going on to already has a machining task.
                $sql = 'SELECT tml.*, 
                        IF(' . $taskID . '=tml.TaskID, 1, 0) AS IsMachiningTaskOnTargetMachine
                        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
                $machingMovingToHasMachingQuery = $db->queryDB($sql, null, "check_to_allow_tasks_on_machines Form occurance 2");

                // Determine if the machine moving to already has a machining task .
                $machiningStatusAssocRow=null;
                if (mysqli_num_rows($machingMovingToHasMachingQuery)>0){
                    // Since there is a row returned, then there is already a machining task on the target machine
                    $isThereAMachingTaskOnTargetMachine = 1;

                    // Get the Row returned
                    $machiningStatusAssocRow = $machingMovingToHasMachingQuery->fetch_assoc();

                    // Determine if this task IS the machining task on the target machine
                    $isThisMachingTaskOnTargetMachine = $machiningStatusAssocRow["IsMachiningTaskOnTargetMachine"];
                }
                
                
                
                // Determine if this dude wants to be the machining task
                if ($wantsMachining) {
                    // Determine if they even have a machine selected
                    if ($machineAfter <= 0){
                        // return a message for not allowing this movement on the same machine
                        return 'ABORT MOVE (check_to_allow_tasks_on_machines)::You cannot put a task into ' . 
                               'the machining phase and not pick a machine to go onto. Please choose ' . 
                               'a machine.';
                    }
                    
                    // Priority after has to be correct
                    if ($indexAfter != 1){
                            // Return an error code
                        return 'ABORT MOVE (check_to_allow_tasks_on_machines)::You cannot have a task in ' . 
                               'the machining phase and not have it in the FIRST position.';
                    }
                    else {
                        // Determine if we are moving to a machine with a machining task
                        if ($isThereAMachingTaskOnTargetMachine == 1 &&
                            $isThisMachingTaskOnTargetMachine != 1){
                            // return a message for not allowing this movement on the same machine
                            return 'ABORT MOVE (check_to_allow_tasks_on_machines)::The current machine already ' . 
                                   'has a machining task.  There can only be one.';
                        }
                    }
                }
                else {
                    // ensure we are not moving forward of a machining task other than ourselves
                    if ($indexAfter == 1  && 
                        $isThereAMachingTaskOnTargetMachine == 1 && 
                        $isThisMachingTaskOnTargetMachine == 0){
                            // Return an error code
                            return 'ABORT MOVE (check_to_allow_tasks_on_machines)::Cannot move this ' . 
                                   'task in front of the task that is in the machining state  ' . 
                                   'on the different machine.';
                    }
                }
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'ABORT MOVE (check_to_allow_tasks_on_machines)::There was an error ' . 
                      'trying determine if machine has machining tasks. \n\n The error is: ' . 
                      $ex->getMessage();
        }

        // Return whatever we got
        return $result;
    }
    
    function checkForStrayTools($db, $machineBefore, $statusBefore, 
                                     $machineAfter,  $statusAfter,
                                     $taskID){
        $result = "";
        
        try {
            // Double-Check these.  Should have checked them before being passed in though. 
            // Determine if ANYTHING relevant is changing
            if ($machineBefore!=$machineAfter ||
                $statusBefore!=$statusAfter){
                // Set and initialize variables
                $wasMachining = 0;
                $wantsMachining = 0;
                $machiningStatusID = -1;
                $isThereAMachingTaskOnTargetMachine = 0;
                $isThisMachingTaskOnTargetMachine = 0;
                
                // Create a query to get check on both phases to see if either was or wants to be machining
                $sql = 'SELECT IF(' . $statusBefore . '=s.StatusID, 1, 0) AS WasMachining, ' .
                       '       IF(' . $statusAfter . '=s.StatusID, 1, 0) AS WantsMachining, ' .
                       '       s.StatusID AS MachiningStatusID ' .
                       'FROM status s ' .
                       'WHERE Name = "Machining";';
                
                
                // Run the query
                $machiningStatusQuery = $db->queryDB($sql, null, "check_to_allow_tasks_on_machines Form occurance 3");

                // Determine if we have one row to look at
                $machiningStatusAssocRow=null;
                if (mysqli_num_rows($machiningStatusQuery)==1){
                    // Get the Row returned
                    $machiningStatusAssocRow = $machiningStatusQuery->fetch_assoc();
                    
                    // Set the values we are looking for
                    $wasMachining = $machiningStatusAssocRow["WasMachining"];
                    $wantsMachining = $machiningStatusAssocRow["WantsMachining"];
                    $machiningStatusID = $machiningStatusAssocRow["MachiningStatusID"];
                }
                
                // Now I should determine if the machine it is going on to already has a machining task.
                $sql = 'SELECT tml.*, 
                        IF(' . $taskID . '=tml.TaskID, 1, 0) AS IsMachiningTaskOnTargetMachine
                        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
                $machingMovingToHasMachingQuery = $db->queryDB($sql, null, "check_to_allow_tasks_on_machines Form occurance 2");

                // Determine if the machine moving to already has a machining task .
                $machiningStatusAssocRow=null;
                if (mysqli_num_rows($machingMovingToHasMachingQuery)>0){
                    // Since there is a row returned, then there is already a machining task on the target machine
                    $isThereAMachingTaskOnTargetMachine = 1;

                    // Get the Row returned
                    $machiningStatusAssocRow = $machingMovingToHasMachingQuery->fetch_assoc();

                    // Determine if this task IS the machining task on the target machine
                    $isThisMachingTaskOnTargetMachine = $machiningStatusAssocRow["IsMachiningTaskOnTargetMachine"];
                }
                
                
                
                // Determine if this dude wants to be the machining task
                if ($wantsMachining) {
                    // Determine if they even have a machine selected
                    if ($machineAfter <= 0){
                        // return a message for not allowing this movement on the same machine
                        return 'ABORT MOVE (check_to_allow_tasks_on_machines)::You cannot put a task into ' . 
                               'the machining phase and not pick a machine to go onto. Please choose ' . 
                               'a machine.';
                    }
                    
                    // Priority after has to be correct
                    if ($indexAfter != 1){
                            // Return an error code
                        return 'ABORT MOVE (check_to_allow_tasks_on_machines)::You cannot have a task in ' . 
                               'the machining phase and not have it in the FIRST position.';
                    }
                    else {
                        // Determine if we are moving to a machine with a machining task
                        if ($isThereAMachingTaskOnTargetMachine == 1 &&
                            $isThisMachingTaskOnTargetMachine != 1){
                            // return a message for not allowing this movement on the same machine
                            return 'ABORT MOVE (check_to_allow_tasks_on_machines)::The current machine already ' . 
                                   'has a machining task.  There can only be one.';
                        }
                    }
                }
                else {
                    // ensure we are not moving forward of a machining task other than ourselves
                    if ($indexAfter == 1  && 
                        $isThereAMachingTaskOnTargetMachine ==1 && 
                        $isThisMachingTaskOnTargetMachine ==0){
                            // Return an error code
                            return 'ABORT MOVE (check_to_allow_tasks_on_machines)::Cannot move this ' . 
                                   'task in front of the task that is in the machining state  ' . 
                                   'on the different machine.';
                    }
                }
            }
        } catch (Exception $ex) {
            // Set up an error message for the exception
            $result = 'ABORT MOVE (check_to_allow_tasks_on_machines)::There was an error ' . 
                      'trying determine if machine has machining tasks. \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
        $indexBefore=-1;
        $machineBefore=-1;
        $statusBefore=-1;
        $indexAfter=-1;
        $machineAfter=-1;
        $statusAfter=-1;
        $taskID=-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 status before moving
        if (isset($_GET['statusBefore']) ){
            // Hold on to the status before moving passed in
            $statusBefore = $_GET['statusBefore'];
        }

        // 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'];
        }

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

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

        // Go and get the machines and all of their tasks
        $return = checkForGoodOrder($db, $indexBefore, $machineBefore, $statusBefore, 
                                         $indexAfter,  $machineAfter,  $statusAfter,
                                         $taskID);
    }
    
    echo $return;
?>   

