<?php 
    // continue the session
    session_start();
    
    include '../php_only_scripts/database.php';
    
    // Init 
    $userRow=null;

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());

    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        exit;
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
    }
    
    // Create a variable to hold the built page to go to
    $pageParams='';

    // Determine if the task ID to update has been sent via post
    if ($userRow["CanModify"] == 1 && isset($_GET['deleteTaskID'])){
        // Set passing variables to defaults
        $selectedCompany=-1;
        $typeTab=1;
        $showWhatFinishedState=0;
        $taskSearchPhrase='';
        $sortNumber=1;
        $assignedToID=-1;
        
        // Set the return to be the main tasks page at first
        $webSiteBase='../tasks.php';

        // Determine if the company combo box changed
        if (isset($_GET['cs'])){
            // Set the session variable to the new value of the combo box
            $selectedCompany = $_GET['cs'];
        }
        
        // Determine if the type is passed in
        if (isset($_GET['ts'])){
            // Set the session variable type to the one passed in
            $typeTab = $_GET['ts'];
        }
        
        // Determine if they want to see the completed tasks
        if (isset($_GET['sfs'])){
            // Change the option to show whatever they are asking for
            $showWhatFinishedState=$_GET['sfs'];
        }
        
        // Determine if there is a search phrase
        if (isset($_GET['sp'])){
            // Set the search phrase
            $taskSearchPhrase=$_GET['sp'];
        }

        // Determine if there is a sort preference
        if (isset($_GET['sn']) ){
            // Hold onto the sort info
            $sortNumber = $_GET['sn'];
        }
        
        // Determine if they are checking for a certain person
        if (isset($_GET['at']) ){
            // Hold onto the assigned to id
            $assignedToID = $_GET['at'];

            // Set the return HTML to be the employee deletiated tasks
            $webSiteBase='../etasks.php';
        }
        
        // Create the page to go to
        $pageParams = "?sfs=" . $showWhatFinishedState . "&cs=" .  $selectedCompany. 
                      "&sp=" .  $taskSearchPhrase. "&ts=" .  $typeTab. "&sn=" .  
                      $sortNumber. "&at=". $assignedToID;
        
        // Get the task ID to work with
        $taskID = $_GET['deleteTaskID'];
        
        // 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, "delete_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();
            
            // Determine if this is a child task or parent
            if ($taskRowAssoc["ParentID"]==0){
                // Create the query to update any rows priority that are after this task
                $sql = 'UPDATE tasks t SET t.Priority=t.Priority-1 ' .
                       'WHERE t.Priority > ' . $taskRowAssoc["Priority"] . ' ' .
                       'AND t.TypeID=' . $taskRowAssoc["TypeID"] . ' ' .
                       '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, "delete_task Form occurance 2");
            }
            else {
                // 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, "delete_task Form occurance 3");

                // Determine if the assigned to is NOT assigned.  Then we know the delete came from within a parent.
                if (!isset($_GET['at'])){
                    // Set the return HTML to be in the update task
                    $webSiteBase='../updateTask.php';
                    
                    // Create the page parameters for the parent 
                    $pageParams = "?updateTaskID=" . $taskRowAssoc["ParentID"] . 
                                  "&parentTaskId=0";
                }
            }

            // 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, "delete_task Form occurance 4");
            
            // 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, "delete_task Form occurance 5");
            
            // 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, "delete_task Form occurance 6");

            // 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, "delete_task Form occurance 7");

            // Get the query to delete all taskstatus info current table for this task
            $sql="DELETE FROM taskstatusinfo_current WHERE TaskID=" . $taskID . ";";

            // Run the delete query for the taskstatus info current table
            $db->queryDB($sql, $userRow, "delete_task Form occurance 8");

            // Get the query to delete all taskstatus info initial table for this task
            $sql="DELETE FROM taskstatusinfo_initial WHERE TaskID=" . $taskID . ";";

            // Run the delete query for the taskstatus info initial table
            $db->queryDB($sql, $userRow, "delete_task Form occurance 9");

            // Determine if this is a child task or parent so we can remove notes, 
            // attachments and task statuses for them as well.
            if ($taskRowAssoc["ParentID"]==0){
                // Create a query to loop through any children that this parent might have
                $sql = 'SELECT * FROM tasks WHERE ParentID=' . $taskID . ';';

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

                // Loop through the returned results
                while ($childTaskAssocRow=mysqli_fetch_array($childrenOfParentTaskQuery)){
                    // Get the query to delete all attachments that this task's children had on them
                    $sql="DELETE FROM attachments where TaskID = " . $childTaskAssocRow["TaskID"] . ";";

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

                    // Get the query to delete all jobblanks that this task's children had on them
                    $sql="DELETE FROM jobblanks where TaskID = " . $childTaskAssocRow["TaskID"] . ";";

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

                    // Get the query to delete all notes that this task's children had on them
                    $sql="DELETE FROM notes where Category = 'TASK' " . 
                         "   AND AssociatedCategoryID = " . $childTaskAssocRow["TaskID"] . ";";

                    // Run the delete query for the notes table
                    $db->queryDB($sql, $userRow, "delete_task Form occurance 13");
                    
                    // Get any and all machines that this task may be on.  Should only ever be on one though.
                    $sql = "SELECT * FROM tasktomachinelinker WHERE TaskID = " . $childTaskAssocRow["TaskID"] . ";";

                    // Run the query and get result
                    $machinesWithChildTaskQuery = $db->queryDB($sql, $userRow, "delete_task Form occurance 14");

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

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

                    // 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, "tasktomachinelinker 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 = ' . $childTaskAssocRow["TaskID"] . ";";

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "delete_task Form occurance 17");
                    
                    // Remove all tools from the linker table.
                    $sql = 'DELETE FROM tooltotasklinker WHERE TaskID = ' . $childTaskAssocRow["TaskID"] . ";";

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "delete_task Form occurance 18");
                    
                    // Create a query to get all of the setups in this task
                    $sql = 'SELECT MachiningSetupID FROM machiningsetups WHERE TaskID = ' . $childTaskAssocRow["TaskID"] . ";"; 
                    
                    // Run the query and get result
                    $setupIDsUnderThisTaskQuery = $db->queryDB($sql, $userRow, "delete_task Form occurance 19");

                    // 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, "delete_task Form occurance 20");
                    
                        // 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, "delete_task Form occurance 21");
                    
                        // 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, "delete_task Form occurance 22");
                    
                        // Create a query to delete this setup
                        $sql = 'DELETE FROM machiningsetups WHERE MachiningSetupID = ' . $setupID["MachiningSetupID"] . ';';

                        // Attempt to run the query
                        $db->queryDB($sql, $userRow, "delete_task Form occurance 24");
                    }
                }
            }
            
            // 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, "delete_task Form occurance 25");

            // Get the query to delete this task's children
            $sql="DELETE FROM tasks where ParentID=" . $taskID . ";";

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

            // Determine if this is a child task or parent
            if ($taskRowAssoc["ParentID"]!=0){
                // 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, "delete_task Form occurance 27");

                // 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, "delete_task Form occurance 28");
                }
            }
            
            // Remove all tools from the linker table.
            $sql = 'DELETE FROM tooltotasklinker WHERE TaskID = ' . $taskID . ";";

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

            // 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, "delete_task Form occurance 30");

            // 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, "delete_task Form occurance 31");
            }

            // 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, "tasktomachinelinker Form occurance 32");

            // 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, "delete_task Form occurance 33");
            
            // 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, "delete_task Form occurance 34");

            // 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, "delete_task Form occurance 35");

                // 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, "delete_task Form occurance 36");

                // 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, "delete_task Form occurance 37");

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

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

    // Determine if they had a certain place in mind to go to
    if ($_SESSION['pageToGoTo']!=''){
        // redirect to the tasks page
        echo ('<script>window.location = "' . $_SESSION['pageToGoTo'] . '";</script>');
    }
    else {
        // redirect to the tasks page
        echo ('<script>window.location = "' . $webSiteBase . $pageParams . '";</script>');
    }
?>