<?php 
    include_once dirname(__FILE__) . '/../global_after_session.php';
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';
    
    function deleteSubtask($db, $userRow, $taskID){
        // create a try catch around all database statements
        try {
            // Get the task row we will update
            $sql = 'SELECT * FROM tasks WHERE TaskID=' . $taskID . ';';

            // Get the task row that is being deleted
            $taskRow = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 1");

            // Check to ensure there is a row to delete
            if (mysqli_num_rows($taskRow)==1){
                // Get the row as an assoc row
                $taskRowAssoc = $taskRow->fetch_assoc();

                // Create the query to update any rows subpriority that are after this task
                $sql = 'UPDATE tasks t SET t.SubPriority=t.SubPriority-1 ' .
                       'WHERE t.SubPriority > ' . $taskRowAssoc["SubPriority"] . ' ' .
                       'AND t.TypeID=' . $taskRowAssoc["TypeID"] . ' ' .
                       'AND t.ParentID=' . $taskRowAssoc["ParentID"] . ' ' .
                       'AND t.Priority < 99999 ' .
                       'AND t.CompanyID = ' . $taskRowAssoc["CompanyID"] . ';';

                // Attempt to change all of the rows that need to be changed
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 2");

                // Get the query to delete all attachments that this task had on it
                $sql="DELETE FROM attachments where TaskID=" . $taskID . ";";

                // Run the delete query for the attachments table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 3");

                // Get the query to delete all job blanks that this task had on it
                $sql="DELETE FROM jobblanks where TaskID=" . $taskID . ";";

                // Run the delete query for the attachments table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 4");

                // Get the query to delete all notes that this task had on it
                $sql="DELETE FROM notes where Category = 'TASK' " . 
                     "       AND AssociatedCategoryID = " . $taskID . ";";

                // Run the delete query for the notes table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 5");

                // Get the query to delete all subtasks that this task had on it
                $sql="DELETE FROM taskstatus WHERE TaskID=" . $taskID . " " .
                                            "OR ParentID=" . $taskID . ";";

                // Run the delete query for the taskstatus table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 6");

                // Get the query to delete this task
                $sql="DELETE FROM tasks where TaskID=" . $taskID . ";";

                // Run the delete query for the tasks table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 7");

                // Remove all tools from the linker table.
                $sql = 'DELETE FROM tooltotasklinker WHERE TaskID = ' . $taskID . ";";

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

                // Remove all tasks from the copied tasks linker table, if it is there. 
                $sql = 'DELETE FROM copiedtaskslinker WHERE CopiedToTaskID = ' . $taskID;

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

                // Create a query to get all of the setups in this task
                $sql = 'SELECT MachiningSetupID FROM machiningsetups WHERE TaskID = ' . $taskID . ";"; 

                // Run the query and get result
                $setupIDsUnderThisTaskQuery = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 10");

                // Loop through the returned results
                while ($setupID=mysqli_fetch_array($setupIDsUnderThisTaskQuery)){
                    // Create a query to delete the setup notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "SETUP_NOTE";';

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

                    // Create a query to delete the M00 notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "SETUP_M00";';

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

                    // Create a query to delete the operator feedback notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "OPERATOR_FEEDBACK_NOTE";';

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

                    // Create a query to delete this setup
                    $sql = 'DELETE FROM machiningsetups WHERE MachiningSetupID = ' . $setupID["MachiningSetupID"] . ';';

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

                // get any and all machines that this task may be on.  Should only ever be on one though.
                $sql = 'SELECT * FROM tasktomachinelinker WHERE TaskID=' . $taskID . ';';

                // Run the query and get result
                $machinesWithTasksQuery = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 15");

                // Loop through the returned results
                while ($machineWithTasksAssocRow=mysqli_fetch_array($machinesWithTasksQuery)){
                    // Change the order down for the old machine after this one to fill the gap
                    $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                           'WHERE TheOrder >= ' . $machineWithTasksAssocRow["TheOrder"] . ' ' . 
                           'AND MachineID = ' . $machineWithTasksAssocRow["MachineID"] . ' ' . 
                           'AND TheOrder < 99999;'; 

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

                // Remove all tasks from the linker table, if it is there. Should only be one though.
                $sql = 'DELETE FROM tasktomachinelinker WHERE TaskID = ' . $taskID;

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

                // Create a query to determine if the parent has any more children
                $sql = 'SELECT (count(*)>0) AS HasChildren FROM tasks WHERE ParentID = ' . 
                        $taskRowAssoc["ParentID"] . ';';

                // Get the task row that is being deleted
                $hasChildrenRow = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 18");

                // Check to ensure there is a row to use
                if (mysqli_num_rows($hasChildrenRow)==1){
                    // Get the row so I can read it
                    $hasChildrenAssocRow = $hasChildrenRow->fetch_assoc();

                    // Create an update query to set has children as it should be
                    $sql = 'UPDATE tasks SET HasChildren = ' . $hasChildrenAssocRow["HasChildren"] .
                           ' WHERE TaskID = ' . $taskRowAssoc["ParentID"] . ';';

                    // Try to update the parent appropriately
                    $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 19");
                    
                    // Determine if the parent now has no children
                    if ($hasChildrenAssocRow["HasChildren"]==0){
                        // Create the error string to return back to the caller
                        return 'FULL REFRESH (surface_clean_task)::The parent no longer has children, so it is now considered a machining task.  Full refresh required.';
                    }
                }
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT CLEAN (surface_clean_task)::There was an uncaught error while cleaning this task.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
    }
    
    
    // attempt to copy all tasks inside of or this particular task to the task requested
    function cleanParent($db, $userRow, $updateTaskID, $withSubtaskDelete) {
        try {
            // Determine if we have an update task number to work on
            if ($updateTaskID==null || !is_numeric($updateTaskID) || $updateTaskID<1){
                // Return an error string to be reported to the user
                return 'ABORT CLEAN (surface_clean_task)::The task number (' . $updateTaskID . ')to clean is not valid.  Try a different TID. Aborting...';
            }

            // Determine if we have an update task number to work on
            if ($userRow["CanModify"] != 1){
                // Return an error string to be reported to the user
                return 'ABORT CLEAN (surface_clean_task)::You do not have access to modify this task for cleaning. Aborting...';
            }

            // Get the task row we will update
            $sql = 'SELECT * FROM tasks WHERE TaskID=' . $updateTaskID . ';';

            // Get the task row that is being deleted
            $taskRow = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 20");

            // Check to ensure there is a row to update
            if (mysqli_num_rows($taskRow)==1){
                // Get the query to delete all job blanks that this task had on it
                $sql="DELETE FROM jobblanks where TaskID=" . $updateTaskID . ";";

                // Run the delete query for the job blanks table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 21");

                // Get the query to delete all notes that this task had on it
                $sql="DELETE FROM notes where Category = 'TASK' " . 
                     "       AND AssociatedCategoryID = " . $updateTaskID . ";";

                // Run the delete query for the notes table
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 22");

                // Remove all tools from the linker table.
                $sql = 'DELETE FROM tooltotasklinker WHERE TaskID = ' . $updateTaskID . ";";

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

                // get any and all machines that this task may be on.  Should only ever be on one though.
                $sql = 'SELECT * FROM tasktomachinelinker WHERE TaskID=' . $updateTaskID . ';';

                // Run the query and get result
                $machinesWithTasksQuery = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 24");

                // Loop through the returned results
                while ($machineWithTasksAssocRow=mysqli_fetch_array($machinesWithTasksQuery)){
                    // Change the order down for the old machine after this one to fill the gap
                    $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                           'WHERE TheOrder >= ' . $machineWithTasksAssocRow["TheOrder"] . ' ' . 
                           'AND MachineID = ' . $machineWithTasksAssocRow["MachineID"] . ' ' . 
                           'AND TheOrder < 99999;'; 

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

                // Remove all tasks from the linker table, if it is there. Should only be one though.
                $sql = 'DELETE FROM tasktomachinelinker WHERE TaskID = ' . $updateTaskID;

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

                // Remove all tasks from the copied tasks linker table, if it is there. 
                $sql = 'DELETE FROM copiedtaskslinker WHERE CopiedToTaskID = ' . $updateTaskID;

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

                // Create a query to get all of the setups in this task
                $sql = 'SELECT MachiningSetupID FROM machiningsetups WHERE TaskID = ' . $updateTaskID . ";"; 

                // Run the query and get result
                $setupIDsUnderThisTaskQuery = $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 28");

                // Loop through the returned results
                while ($setupID=mysqli_fetch_array($setupIDsUnderThisTaskQuery)){
                    // Create a query to delete the setup notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "SETUP_NOTE";';

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

                    // Create a query to delete the M00 notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "SETUP_M00";';

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

                    // Create a query to delete the operator feedback notes for this setup
                    $sql = 'DELETE FROM notes WHERE AssociatedCategoryID = ' . $setupID["MachiningSetupID"] . 
                           ' AND Category = "OPERATOR_FEEDBACK_NOTE";';

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

                    // Create a query to delete this setup
                    $sql = 'DELETE FROM machiningsetups WHERE MachiningSetupID = ' . $setupID["MachiningSetupID"] . ';';

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 32");
                }
            }
            
            // Determine if they want to delete the row as well or just clean
            if ($withSubtaskDelete==1){
                // Delete everything associated with the subtask inclucing the task itself
                return deleteSubtask($db, $userRow, $updateTaskID);
            }
            else {
                // Create a query to update values in the main task that do not apply to tasks that are NOT to be machined
                $sql = 'UPDATE tasks ' . 
                       'SET IssuedToMachineDate=NULL, FixtureToUseID=-1, PartHardware=NULL, ' .
                           'IsVacuumClean=0, IsWashForAnodize=0, IsSandblasted=0, SandBlastingInstructions=NULL, ' .
                           'HasAllowableCosmeticDamage=0, IsTappedPostMachining=0, ' .
                           'PostMachiningTappingInstructions=NULL, MachineOperatorFeedback=NULL, ' .
                           'PostMachiningFeedback=NULL, PostMachiningNotes=NULL, ProgrammerID=-1, ' .
                           'ProgramCheckedByID=-1 ' .
                       'WHERE TaskID=' . $updateTaskID . ';';

                // Attempt to run the query
                $db->queryDB($sql, $userRow, "surface_clean_task Form occurance 33");
            }
        } 
        catch (Exception $exc) {
            // Create the error string to return back to the caller
            return 'ABORT CLEAN (surface_clean_task)::There was an uncaught error while cleaning this task.  The exception is: ' . $exc->getMessage() . '. Aborting...';
        }
        
        // If we got here then assume success
        return "";
    }
    
    $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 CLEAN (surface_clean_task)::Your session has expired.  ' . 
             'Refresh the page before cleaning this task.';
    }
    else {
        // Set defaults for the passed in variables
        $updateTaskNumber=-1;
        $withSubtaskDelete=0;
        
        // check the passed in update task ID
        if (isset($_GET['updateTaskNumber']) ){
            // get the passed in update task ID
            $updateTaskNumber = $_GET['updateTaskNumber'];
        }

        // check to see if the sent the with delete variable
        if (isset($_GET['withSubtaskDelete']) ){
            // get the value that they set for the delete variable
            $withSubtaskDelete = $_GET['withSubtaskDelete'];
        }

        // Attempt to log in with this user
        $userRow = $currentUser->fetch_assoc();

        // Attempt to clean the task of the task passed in.
        $returnString=cleanParent($db, $userRow, $updateTaskNumber, $withSubtaskDelete);

        // Determine if we are gtg onto the next phase
        if (strpos($returnString,'ABORT CLEAN')===false && 
            strpos($returnString,'FULL REFRESH')===false){
            // Now we can modify the Tool Details in the table to match new tools
            $returnString = retrieveChildTasksAsList($db, $userRow, $updateTaskNumber, true, -1, -1);
        }
        
        // return the result
        echo $returnString;
    }
    
?>