<?php 
    // continue the session
    session_start();

    // Add includes to PHP files that I will need to access
    include_once dirname(__FILE__) . '/../php_only_scripts/database.php';
    include_once dirname(__FILE__) . '/../php_only_scripts/global_functions.php';
    
    // Init some variables
    $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();
    }
    
    // Determine if this user can even modify
    if (!$userRow["CanModify"]){
        // redirect to the users page
        echo ('<script>window.location = "users.php";</script>');
    }
    else {
        if (isset($_POST['newPosition']) && 
            isset($_POST['lastPosition']) && 
            isset($_POST['lastOneUpdated']) && 
            isset($_POST['type'])){
            // Put the posts in local variables
            $newPosition = $_POST['newPosition'];
            $realNewPriority = $newPosition - 1;
            $lastPosition = $_POST['lastPosition'];
            $realCurrentPriority = $lastPosition - 1;
            $lastOneUpdated = $_POST['lastOneUpdated'];
            $type = $_POST['type'];
            $selectedCompany = $_POST['companySelected'];

            try {
                // Setup error to be nothing for now
                $error = '';

                // Let's create the insert query off of what we have
                $sql='UPDATE tasks SET Priority=-999 ' . 
                     'WHERE Priority=' . $realCurrentPriority . ' ' .
                     'AND TypeID = ' . $type . ' ' .
                     'AND CompanyID = ' . $selectedCompany . ';';

                // Attempt to change all of the rows that need to be changed
                $db->queryDB($sql, $userRow, "reorder_tasks Form occurance 1");
                
                // Create a query to change priority down of any after the one that is moving to close the gap
                $sql = 'UPDATE tasks SET Priority = Priority-1 ' .
                       'WHERE Priority > ' . ($lastPosition-1) . ' ' .
                       'AND Priority < 99999 ' . 
                       'AND TypeID = ' . $type . ' ' .
                       'AND CompanyID = ' . $selectedCompany . ';';

                // Move them
                $db->queryDB($sql, $userRow, "reorder_tasks Form occurance 2");

                // Query to move rows up that are before the priority number moving but after where it is moving to
                $sql = 'UPDATE tasks SET Priority = Priority+1 ' .
                       'WHERE Priority >= ' . ($newPosition-1) .  ' ' .
                       'AND Priority < 99999 ' . 
                       'AND TypeID = ' . $type . ' ' .
                       'AND CompanyID = ' . $selectedCompany . ';';

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

                // Let's create the insert query off of what we have
                $sql='UPDATE tasks SET Priority=' . $realNewPriority . " " .
                     'WHERE Priority=-999 ' . 
                     'AND TypeID = ' . $type . ' ' .
                     'AND CompanyID = ' . $selectedCompany . ';';

                // Attempt to change all of the rows that need to be changed
                if ($db->queryDB($sql, $userRow, "reorder_tasks Form occurance 4")){
                    // Create a query to hopefully get the ONE row with these specs
                    $sql = 'SELECT t.*, s.Name, c.CompanyName 
                            FROM tasks t, status s, companies c 
                            WHERE t.StatusID=s.StatusID 
                            AND t.CompanyID=c.CompanyID  
                            AND t.Priority=' . $realNewPriority . '
                            AND t.TypeID = ' . $type . ' 
                            AND t.ParentID = 0 
                            AND t.CompanyID = ' . $selectedCompany . ';';
                    
                    // Make the query
                    $taskUpdated = $db->queryDB($sql, $userRow, "reorder_tasks Form occurance 5");

                    // Create a blank subject and message string for the e-mail that will eventually be created.
                    $messageToSend="";
                    $subject="";
                    
                    // There should only every be ONE row with this combination.  If more, inform an SU.
                    if (mysqli_num_rows($taskUpdated)>1){
                        // Create the message to add for this
                        $messageToSend=$messageToSend . "<br>  ++ A Priority" .
                                " has been changed from " . $realCurrentPriority . 
                                " to " . $realNewPriority . ". This resulted" . 
                                " in duplicate priorities for this company and type." .
                                " Please inform the appropriate technical support " . 
                                " person in charge of the TMS of the error.<br><br>\n";
                                        
                        // Create the entire message
                        $messageToSend= 'There have been changes made by ' . $currentUser['FirstName'] . 
                                ' ' . $currentUser['LastName'] . ' to a task from the ' . 
                                'tasks page of the company ID "' . $selectedCompany .
                                '".  <br><br>Changes Made:' . $messageToSend;

                        // Add a little more message to this notification
                        $messageToSend = $messageToSend . '<br><br>' .
                                'Regards, <br><br>Evolve Engineering and Software Support Team<br>' .
                                '(720)552-7997';

                        // Create the subject
                        $subject = htmlspecialchars_decode ("TMS Error: Priority Changes made on " . 
                                                "the tasks page resulted in duplicate priorities.");
                        
                        // Create the query of users to notify about this error state.
                        $sql='SELECT * 
                              FROM users 
                              WHERE CompanyID=1 
                              AND UserTemplateOnly=0 
                              AND SilenceAllTaskNotifications<>1
                              AND SUEmployee=1 
                              AND UserLevel="SU";';
                    }
                    elseif (mysqli_num_rows($taskUpdated)==1){
                        // Get the readable row for this
                        $taskUpdatedAssoc = $taskUpdated->fetch_assoc();
                        
                        // Create the message to add for this
                        $messageToSend=$messageToSend . "<br>  ++ The Priority " .
                                "has been changed from " . $realCurrentPriority . 
                                " to " . $realNewPriority . ".\n";
                                        
                        // Create the entire message
                        $messageToSend= 'There have been changes made by ' . $userRow['FirstName'] . 
                                ' ' . $userRow['LastName'] . ' to a task that you ' . 
                                'are currently monitoring.' . 
                                '<br><br>COMPANY: "' . $taskUpdatedAssoc['CompanyName'] . '"' .
                                '<br>Task Title: "' . $taskUpdatedAssoc['Title'] . '"' . 
                                '<br>TID: ' . $taskUpdatedAssoc['TaskID'] . 
                                '<a href="https://www.eestms.com/' . getTMSHome() . 
                                '/updateTask.php?updateTaskID=' . $taskUpdatedAssoc["TaskID"] . 
                                '&parentTaskId=0">  (Click To View)</a>.' .
                                '<br><br>Changes Made:' . $messageToSend;

                        // Add a little more message to this notification
                        $messageToSend = $messageToSend . '<br><br>If you would like to check ' .
                                'on the task, you can do so at ' .
                                '<a href="https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . 
                                $taskUpdatedAssoc["TaskID"] . '&parentTaskId=0">www.eestms.com/' . getTMSHome() . '</a>.<br><br>' .
                                'If you need help with your user name or password, you can ' .
                                'reply to this e-mail or call us at (720)552-7997.<br><br>' .
                                'Regards, <br><br>Evolve Engineering and Software Support Team<br>' .
                                '(720)552-7997';

                        // Create the subject
                        $subject = htmlspecialchars_decode ("Change Made to '" . $taskUpdatedAssoc['Title'] . "' for company '" . 
                                                            $taskUpdatedAssoc["CompanyName"] . "'.");
                        
                        // Create the query of users to notify about this priority change.
                        $sql='SELECT * 
                              FROM users 
                              WHERE UserID<>' . $userRow["UserID"] . '
                              AND UserTemplateOnly=0 
                              AND AccountStatus="Active"
                              AND SilenceAllTaskNotifications<>1
                              AND ((CompanyID = ' . $taskUpdatedAssoc["CompanyID"] . ') 
                                   OR (CompanyID = 1 AND SUEmployee=1) 
                                   OR (UserID = ' . $taskUpdatedAssoc["UserID"] . '));';
                    }
                    
                    // Decode the quotes to be shown as quotes.  Not weirdness
                    $messageToSend = htmlspecialchars_decode ($messageToSend, ENT_COMPAT | ENT_HTML401);

                    // Create the headers
                    $headers = "From: EES Mail Admin"." <admin@eestms.com>\r\n"; 
                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                        
                    // First determine if they care about any changes
                    if ($messageToSend!=""){
                        // Make the query
                        $usersToNotify = $db->queryDB($sql, $userRow, "reorder_tasks Form occurance 6");

                        // Loop through the returned results
                        while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                            // Determine if this user really needs to see this info and that their e-mail is good
                            if ((preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])) && 
                                (($userToNotify["ReceivePriorityChangeUpdate"]) || 
                                 ($userToNotify["CompanyID"]==1 &&
                                  $userToNotify["UserID"]==$userID))){
                                try {
                                    // Attempt to mail it
                                    mail($userToNotify["EMail"],$subject,$messageToSend,$headers);
                                } 
                                catch (Exception $e) {
                                    echo("The notification was not sent to " . $userToNotify["EMail"] .
                                         " because of an error.");
                                }
                            }
                        }
                    }
                }
            } catch (Exception $ex) {
                // Inform the user that there was an error in calculations
                echo ("Error: There was an error while changing the priority. " . 
                      "The error is:\n\n " . $e->getMessage());
            }
        }
        else {
            // Inform the user that we cannot get variables that are necessary 
            echo ('Error: There are variables that cannot be seen for calculations ' .
                  'to be made.  Please contact TMS technical support.');
        }
    }
?>