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

    // Determine if the form was submitted recently
    if (!isset($_POST['formSubmitted']) || 
        !htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
        // Require the login since we are not submitting the form
        require_once('php_only_scripts/protector.php');
    }
    
    // init variables
    $updateUserId=-1;
    $resultOfCopyPreferences="";
    
    // now determine if it was posted
    if (isset($_GET['updateUserID'])){
        // Default for the user ID is as a posted variable
        $updateUserId=$_GET['updateUserID'];
    }
    
    // Add includes to PHP files that I will need to access
    require_once 'php_only_scripts/global_functions.php';
    require_once 'php_only_scripts/database.php';
    require_once 'php_only_scripts/presentation.php';
    require_once 'php_only_scripts/user_presentation.php';
    require_once 'php_only_scripts/note_presentation.php';

    // Init some variables
    $userRow=null;

    // Assume NOT gtg
    $gtg = false;

    // 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 is allowed here or not
        if (($userRow["UserLevel"]=='MINIMAL' || 
             $userRow["UserLevel"]=='TIMECARD ONLY') &&
            $userRow["UserID"]!=$updateUserId ||
            $userRow["AccountStatus"]!='ACTIVE'){
                // redirect to the invalid access page
                echo ('<script>window.location = "invalid_access.php";</script>');
                
                exit;
        }
        
        // Set the good to go until they log out
        $gtg = true;

        // Determine if BOTH the user name AND password has been set
        if (isset($_POST['formSubmitted']) && 
            htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
            // Determine if this user can even modify
            if (!$userRow["CanModify"]){
                // Let them know they cannot modify
                echo "<script type=\"text/javascript\">window.alert('Your profile does not allow you to modify.\nContact a higher level to request this privilege.');</script>"; 

                // Bypass the protector
                $_SESSION['bypassProtector']="True";

                // redirect to the update page
                echo ('<script>window.location = "updateUser.php?updateUserID=' . $userRow["UserID"] . '";</script>');
            }
            else {
                // Change the form back to NOT being submitted
                $_SESSION['formSubmitted']='FALSE';
                
                // Create a query to get the user level of the user that is being modified
                $sql='SELECT UserLevel FROM users WHERE UserID=' . $updateUserId . ';';

                // Attempt to get the user level
                $row = $db->queryDB($sql, $userRow, "updateUser Form occurance 1");

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

                // Get a comparison of the two levels
                $compareUserLevelResult=compareUserLevel ($db, $userRow, $userRow["UserLevel"], $assocUserLevel["UserLevel"]);

                // Determine if this use has the ability to change user main characteristics
                if ($userRow["UserLevel"]=='SU' || 
                    $compareUserLevelResult==1 ||
                    $userRow["UserID"]==$updateUserId){
                    // Calculate the start of this current quarter
                    $quarterStart = calculateQuarterStart(null);

                    // Set the local variables from what was posted
                    $accountStatus = htmlspecialchars($_POST['accountStatus'], ENT_QUOTES, 'UTF-8');
                    $addDate = htmlspecialchars($_POST['addDate'], ENT_QUOTES, 'UTF-8');
                    $companyID = htmlspecialchars($_POST['company'], ENT_QUOTES, 'UTF-8');
                    $eMail = htmlspecialchars($_POST['newUserEMail'], ENT_QUOTES, 'UTF-8');
                    $firstName = htmlspecialchars($_POST['firstName'], ENT_QUOTES, 'UTF-8');
                    $initials = htmlspecialchars($_POST['initials'], ENT_QUOTES, 'UTF-8');
                    $lastName = htmlspecialchars($_POST['lastName'], ENT_QUOTES, 'UTF-8');
                    $password = htmlspecialchars($_POST['pw'], ENT_QUOTES, 'UTF-8');
                    $userLevel = htmlspecialchars($_POST['userLevel'], ENT_QUOTES, 'UTF-8');
                    $userName = htmlspecialchars($_POST['userName'], ENT_QUOTES, 'UTF-8');
                    $firstPayDate = htmlspecialchars($_POST['payDateStart'], ENT_QUOTES, 'UTF-8');
                    $payPeriod = htmlspecialchars($_POST['PayPeriod'], ENT_QUOTES, 'UTF-8');
                    $hourlyPayQ1 = htmlspecialchars($_POST['hourlyPayQ1'], ENT_QUOTES, 'UTF-8');
                    $hourlyPayQ2 = htmlspecialchars($_POST['hourlyPayQ2'], ENT_QUOTES, 'UTF-8');
                    $hourlyPayQ3 = htmlspecialchars($_POST['hourlyPayQ3'], ENT_QUOTES, 'UTF-8');
                    $hourlyPayQ4 = htmlspecialchars($_POST['hourlyPayQ4'], ENT_QUOTES, 'UTF-8');
                    $showWhatFinishedState = htmlspecialchars($_POST['showWhatFinishedState'], ENT_QUOTES, 'UTF-8');
                    $tasksPerPage = htmlspecialchars($_POST['tasksPerPage'], ENT_QUOTES, 'UTF-8');
                    $laborCategory=htmlspecialchars($_POST['laborCategory'], ENT_QUOTES, 'UTF-8');
                    $silenceAllNotifications=(isset($_POST['silenceAllNotifications'])?1:0);
                    $defaultNewUserPassword=htmlspecialchars($_POST['defaultNewUserPassword'], ENT_QUOTES, 'UTF-8');
                    $canModify=(isset($_POST['canModify'])?1:0);
                    $cannotViewUnsubmittedBlanks=(isset($_POST['cannotViewUnsubmittedBlanks'])?1:0);
                    $canModifyChildren=(isset($_POST['canModifyChildren'])?1:0);
                    $canCopyTasks=(isset($_POST['canCopyTasks'])?1:0);
                    $canAddAllParent=(isset($_POST['canAddAllParent'])?1:0);
                    $canModifyRouting=(isset($_POST['canModifyRouting'])?1:0);

                    // Let's create the update query off of what we have
                    $sql='UPDATE users SET ';
                    if ($companyID!=null) {$sql = $sql . 'CompanyID=' . $companyID;}
                    if ($accountStatus!=null) {$sql = $sql . ', AccountStatus="' . $accountStatus . '"';}
                    if ($addDate!=null) {$sql = $sql . ', AddDate="' . $addDate . '"';}
                    if ($eMail!=null) {$sql = $sql . ', EMail="' . $eMail . '"';}
                    if ($firstName!=null) {$sql = $sql . ', FirstName="' . $firstName . '"';}
                    if ($initials!=null) {$sql = $sql . ', Initials="' . $initials . '"';}
                    if ($lastName!=null) {$sql = $sql . ', LastName="' . $lastName . '"';}
                    if ($password!=null) {$sql = $sql . ', Password="' . $password . '"';}
                    if ($userLevel!=null) {$sql = $sql . ', UserLevel="' . $userLevel . '"';}
                    if ($userName!=null) {$sql = $sql . ', UserName="' . $userName . '"';}
                    if ($firstPayDate!=null) {$sql = $sql . ', FirstPayDate="' . $firstPayDate . '"';}
                    if ($payPeriod!=null) {$sql = $sql . ', PayPeriod="' . $payPeriod . '"';}
                    if ($hourlyPayQ1!=null) {$sql = $sql . ', HourlyPayQ1=' . $hourlyPayQ1;}
                    if ($hourlyPayQ2!=null) {$sql = $sql . ', HourlyPayQ2=' . $hourlyPayQ2;}
                    if ($hourlyPayQ3!=null) {$sql = $sql . ', HourlyPayQ3=' . $hourlyPayQ3;}
                    if ($hourlyPayQ4!=null) {$sql = $sql . ', HourlyPayQ4=' . $hourlyPayQ4;}
                    if ($tasksPerPage!=null) {$sql = $sql . ', TasksPerPage=' . $tasksPerPage;}
                    if ($hourlyPayQ4!=null) {$sql = $sql . ', HourlyPayQ4=' . $hourlyPayQ4;}
                    if ($defaultNewUserPassword!=null) {$sql = $sql . ', DefaultNewUserPassword="' . $defaultNewUserPassword . '"';}
                    if ($userRow["UserLevel"]=='SU') {$sql = $sql . ', CanModify=' . $canModify;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', SilenceAllTaskNotifications=' . $silenceAllNotifications;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CannotViewUnsubmittedBlanks=' . $cannotViewUnsubmittedBlanks;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanModifyChildren=' . $canModifyChildren;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanCopyTasks=' . $canCopyTasks;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanAddAllParent=' . $canAddAllParent;}
                    if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanModifyRouting=' . $canModifyRouting;}
                    if ($laborCategory!=null) {$sql = $sql . ', StandardLaborCategoryID=' . $laborCategory;}
                    if ($showWhatFinishedState!=null) {$sql = $sql . ', ShowWhatFinishedState=' . $showWhatFinishedState;}
                    $sql=$sql .' WHERE UserID=' . $updateUserId . ';';

                    // Attempt to run the query and evaluate the response
                    if (!$db->queryDB($sql, $userRow, "updateUser Form occurance 2.")){
                        echo '<script>alert("User was NOT updated in the database. Please check the data and try again.");</script>';
                        // TODO: How do I want to display a failure to the user?
                        
                        // Do NOT go on to any other updates if the main user is not updated
                        exit;
                    }
                }
               
                // Determine if this user is allowed here or not
                if ($userRow["UserID"]==$updateUserId ||
                    $userRow["UserLevel"]=='SU'|| $userRow["UserLevel"]=='EXECUTIVE' ||
                    ($compareUserLevelResult==1 && $userRow["CompanyID"]==1 && $userRow["SUEmployee"]==1 && $userRow["AccountStatus"]=='ACTIVE')){

                    // Set the user template value to none at first
                    $userTemplateValue=-1;
                    
                    // Determine if it is set
                    if (isset($_POST['applyPreferencesRadio'])){
                        // Get the value from the radio button
                        $userTemplateValue = htmlspecialchars($_POST['applyPreferencesRadio'], ENT_QUOTES, 'UTF-8');
                    }
 
                    // Determine if they are applying a template to this user
                    if ($userTemplateValue==0 || $userTemplateValue==1 &&
                        ($compareUserLevelResult==1 && $userRow["CompanyID"]==1 && $userRow["SUEmployee"]==1 && $userRow["AccountStatus"]=='ACTIVE')){
                        // create a variable to hold the user ID to copy from
                        $userIDToCopyFrom=-1;

                        // Determine where we should be getting the 'template' ID from
                        if ($userTemplateValue==0){
                            // Get the user ID from the USERs drop down
                            $userIDToCopyFrom=htmlspecialchars($_POST['userToCopy'], ENT_QUOTES, 'UTF-8'); 
                        }
                        else if ($userTemplateValue==1){
                            // Get the user ID from the USERs drop down
                            $userIDToCopyFrom=htmlspecialchars($_POST['userTemplateToCopy'], ENT_QUOTES, 'UTF-8'); 
                        }

                        // Copy preferences and return the result
                        $resultOfCopyPreferences=copyPreferences($db, $userRow, $updateUserId, $userIDToCopyFrom);
                    }
                    else {
                        // Get the posted preferences
                        $suEmployee=(isset($_POST['suEmployee'])?1:0);
                        $refreshRate=htmlspecialchars($_POST['refreshRate'], ENT_QUOTES, 'UTF-8');
                        $primaryTaskType=htmlspecialchars($_POST['primaryTaskType'], ENT_QUOTES, 'UTF-8');
                        $receiveAttachmentUpdate=(isset($_POST['receiveAttachmentUpdate'])?1:0);
                        $receivePriorityChangeUpdate=(isset($_POST['receivePriorityChangeUpdate'])?1:0);
                        $receiveAddTaskUpdate=(isset($_POST['receiveAddTaskUpdate'])?1:0);
                        $receiveMaterialLowStockNotificationUpdate=(isset($_POST['receiveMaterialLowStockNotificationUpdate'])?1:0);
                        $receiveToolLowStockNotificationUpdate=(isset($_POST['receiveToolLowStockNotificationUpdate'])?1:0);
                        $receivePayPeriodRolloverUpdate=(isset($_POST['receivePayPeriodRolloverUpdate'])?1:0);
                        $receiveBlankCutNotificationUpdate=(isset($_POST['receiveBlankCutNotificationUpdate'])?1:0);
                        $receiveNotesNotificationUpdate=(isset($_POST['receiveNotesNotificationUpdate'])?1:0);

                        // Let's create the insert query off of what we have
                        $sql='UPDATE users SET UserID=UserID';
                        if ($refreshRate!=null) {$sql = $sql . ', RefreshRate=' . $refreshRate . '';}
                        if ($primaryTaskType!=null) {$sql = $sql . ', PrimaryTaskType="' . $primaryTaskType . '"';}
                        $sql = $sql . ' WHERE UserID=' . $updateUserId . ';';

//echo '<script>alert("sql:' . $_POST['refreshRate'] . '");</script>';
//echo '<script>alert("sql:' . addslashes($sql) . '");</script>';
                        // Run the query to update the preferences
                        $db->queryDB($sql, $userRow, "updateUser Form occurance 3");

                        // Determine if this user can make other users
                        if ($userRow["UserLevel"]=='SU' ||
                            $userRow["UserLevel"]=='EXECUTIVE') {
                            // Update the general notifications are that only exac and SU can do
                            $sql='UPDATE users SET ' .
                                 'ReceiveAttachmentUpdate=' . $receiveAttachmentUpdate . 
                                 ', SUEmployee=' . $suEmployee .
                                 ', ReceivePriorityChangeUpdate=' . $receivePriorityChangeUpdate . 
                                 ', ReceiveAddTaskUpdate=' . $receiveAddTaskUpdate . 
                                 ', ReceiveMaterialLowStockNotificationUpdate=' . $receiveMaterialLowStockNotificationUpdate .
                                 ', ReceiveToolLowStockNotificationUpdate=' . $receiveToolLowStockNotificationUpdate .
                                 ', ReceivePayPeriodRolloverUpdate=' . $receivePayPeriodRolloverUpdate .
                                 ', ReceiveBlankCutNotificationUpdate=' . $receiveBlankCutNotificationUpdate . 
                                 ', ReceiveNotesNotificationUpdate=' . $receiveNotesNotificationUpdate . 
                                 ' WHERE UserID=' . $updateUserId . ';';

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

                            // Update the user notification status checkboxes with values
                            updateUserStatusNotificationsCheckboxes($db, $userRow, $updateUserId);

                            // Update the user status viewable checkboxes with values
                            updateUserStatusViewableCheckboxes($db, $userRow, $updateUserId);
                            
                            // Update the user machine viewable checkboxes with values. 
                            // Not visible for non-SU company users, so will set them all to 
                            // not seeable. This is totally acceptable and even wanted behavior.
                            updateUserMachineViewableCheckboxes($db, $userRow, $updateUserId);
                        }
                        
                        // Get the overwrite or newly write as template information
                        $saveAsTemplate=(isset($_POST['saveAsTemplate'])?1:0);
                        $saveAsTemplateName=htmlspecialchars($_POST['saveAsTemplateName'], ENT_QUOTES, 'UTF-8');
                        $originalTemplateID=htmlspecialchars($_POST['originalTemplateID'], ENT_QUOTES, 'UTF-8');
                        $originalTemplateName=htmlspecialchars($_POST['originalTemplateName'], ENT_QUOTES, 'UTF-8');
                        
                        // Determine if the user is wanting to copy the current preferences back to the last applied template
                        if ($saveAsTemplate==1){
                            // Determine if the template name is GTG
                            if ($saveAsTemplateName!=null && trim($saveAsTemplateName)!=''){
                                // Determine if they just want to overwrite the last preferences with this current one
                                if ($saveAsTemplateName==$originalTemplateName){
                                    // Copy preferences and return the result
                                    $resultOfCopyPreferences=copyPreferences($db, $userRow, $originalTemplateID, $updateUserId);
                                }
                                else {
                                    // First create a query to determine if there is already a template with the name they chose
                                    $sql='SELECT * FROM users WHERE UserName="' . $saveAsTemplateName . '";';

                                    // Run the query
                                    $preferenceToCheck=$db->queryDB($sql, $userRow, "updateUser Form occurance 5.");

                                    // Evaluate the response
                                    if ($preferenceToCheck!==FALSE){
                                        // Determine if the number of rows is one or greater
                                        if (mysqli_num_rows($preferenceToCheck)==0){
                                            // Let's create the insert query off of what we have
                                            $sql='INSERT INTO users (UserTemplateOnly';
                                            $sql = $sql . ', SUEmployee';
                                            $sql = $sql . ', CompanyID';
                                            if ($userRow["UserLevel"]=='SU') {$sql = $sql . ', CanModify';}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CannotViewUnsubmittedBlanks';}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanModifyChildren';}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanCopyTasks';}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanAddAllParent';}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', CanModifyRouting';}
                                            if ($accountStatus!=null) {$sql = $sql . ', AccountStatus';}
                                            if ($password!=null) {$sql = $sql . ', Password';}
                                            if ($userLevel!=null) {$sql = $sql . ', UserLevel';}
                                            if ($userName!=null) {$sql = $sql . ', UserName';}
                                            if ($primaryTaskType!=null) {$sql = $sql . ', PrimaryTaskType';}
                                            if ($defaultNewUserPassword!=null) {$sql = $sql . ', DefaultNewUserPassword';}
                                            if ($laborCategory!=null) {$sql = $sql . ', StandardLaborCategoryID';}
                                            if ($showWhatFinishedState!=null) {$sql = $sql . ', ShowWhatFinishedState';}
                                            if ($tasksPerPage!=null) {$sql = $sql . ', TasksPerPage';}
                                            $sql=$sql .') VALUES (1';
                                            $sql = $sql. ", " . $suEmployee;
                                            $sql = $sql . ", " . $userRow["CompanyID"];
                                            if ($userRow["UserLevel"]=='SU') {$sql = $sql . ', ' . $canModify;}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', ' . $cannotViewUnsubmittedBlanks;}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', ' . $canModifyChildren;}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', ' . $canCopyTasks;}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', ' . $canAddAllParent;}
                                            if ($userRow["UserLevel"]=='SU'||$userRow["UserLevel"]=='EXECUTIVE') {$sql = $sql . ', ' . $canModifyRouting;}
                                            if ($accountStatus!=null) {$sql = $sql . ', "' . $accountStatus . '"';}
                                            if ($password!=null) {$sql = $sql . ', "' . random_password(50) . '"';}
                                            if ($userLevel!=null) {$sql = $sql . ', "' . $userLevel . '"';}
                                            if ($userName!=null) {$sql = $sql . ', "' . $saveAsTemplateName . '"';}
                                            if ($primaryTaskType!=null) {$sql = $sql . ', "' . $primaryTaskType . '"';}
                                            if ($defaultNewUserPassword!=null) {$sql = $sql . ', "' . $defaultNewUserPassword . '"';}
                                            if ($laborCategory!=null) {$sql = $sql . ', "' . $laborCategory . '"';}
                                            if ($showWhatFinishedState!=null) {$sql = $sql . ', "' . $showWhatFinishedState . '"';}
                                            if ($tasksPerPage!=null) {$sql = $sql . ', "' . $tasksPerPage . '"';}
                                            $sql=$sql .');';

                                            // Attempt to run the query and evaluate the response
                                            if (!$db->queryDB($sql, $userRow, "updateUser Form occurance 6")){
                                                // Let them know of the template add failure
                                                echo ('<script>alert("User template was NOT added to the database. Please check the data and try again.");</script>');
                                            }
                                            else {
                                                // Get the most recent ID (company)
                                                $newUserID = mysqli_insert_id($db->getDBConnection());

                                                // Get the posted preferences
                                                $refreshRate=htmlspecialchars($_POST['refreshRate'], ENT_QUOTES, 'UTF-8');
                                                $primaryTaskType=htmlspecialchars($_POST['primaryTaskType'], ENT_QUOTES, 'UTF-8');
                                                $defaultNewUserPassword=htmlspecialchars($_POST['defaultNewUserPassword'], ENT_QUOTES, 'UTF-8');
                                                $receiveAttachmentUpdate=(isset($_POST['receiveAttachmentUpdate'])?1:0);
                                                $receivePriorityChangeUpdate=(isset($_POST['receivePriorityChangeUpdate'])?1:0);
                                                $receiveAddTaskUpdate=(isset($_POST['receiveAddTaskUpdate'])?1:0);
                                                $receiveMaterialLowStockNotificationUpdate=(isset($_POST['receiveMaterialLowStockNotificationUpdate'])?1:0);
                                                $receiveToolLowStockNotificationUpdate=(isset($_POST['receiveToolLowStockNotificationUpdate'])?1:0);
                                                $receivePayPeriodRolloverUpdate=(isset($_POST['receivePayPeriodRolloverUpdate'])?1:0);
                                                $receiveBlankCutNotificationUpdate=(isset($_POST['receiveBlankCutNotificationUpdate'])?1:0);
                                                $receiveNotesNotificationUpdate=(isset($_POST['receiveNotesNotificationUpdate'])?1:0);

                                                // Let's create the insert query off of what we have
                                                $sql='UPDATE users SET ';
                                                if ($refreshRate!=null) {$sql = $sql . 'RefreshRate=' . $refreshRate . '';}
                                                if ($primaryTaskType!=null) {$sql = $sql . ',PrimaryTaskType="' . $primaryTaskType . '"';}
                                                if ($defaultNewUserPassword!=null) {$sql = $sql . ',DefaultNewUserPassword="' . $defaultNewUserPassword . '"';}
                                                $sql = $sql . ', ShowWhatFinishedState=' . $showWhatFinishedState . 
                                                ' WHERE UserID=' . $newUserID . ';';

                                                // Run the query to update the preferences
                                                $db->queryDB($sql, $userRow, "updateUser Form occurance 7");

                                                // Update the general notifications are that only exac and SU can do
                                                $sql='UPDATE users SET ' .
                                                     'ReceiveAttachmentUpdate=' . $receiveAttachmentUpdate . 
                                                     ', ReceivePriorityChangeUpdate=' . $receivePriorityChangeUpdate . 
                                                     ', ReceiveAddTaskUpdate=' . $receiveAddTaskUpdate . 
                                                     ', ReceiveMaterialLowStockNotificationUpdate=' . $receiveMaterialLowStockNotificationUpdate .
                                                     ', ReceiveToolLowStockNotificationUpdate=' . $receiveToolLowStockNotificationUpdate .
                                                     ', ReceivePayPeriodRolloverUpdate=' . $receivePayPeriodRolloverUpdate .
                                                     ', ReceiveBlankCutNotificationUpdate=' . $receiveBlankCutNotificationUpdate . 
                                                     ', ReceiveNotesNotificationUpdate=' . $receiveNotesNotificationUpdate . 
                                                     ' WHERE UserID=' . $newUserID . ';';

                                                // Run the query to update the preferences
                                                $db->queryDB($sql, $userRow, "updateUser Form occurance 8");

                                                // Update the user notification status checkboxes with values
                                                updateUserStatusNotificationsCheckboxes($db, $userRow, $newUserID);

                                                // Update the user status viewable checkboxes with values
                                                updateUserStatusViewableCheckboxes($db, $userRow, $newUserID);

                                                // Update the user machine viewable checkboxes with values
                                                updateUserMachineViewableCheckboxes($db, $userRow, $newUserID);
                                                
                                                // Update one more to update the original user with the new template name as last updated
                                                $sql='UPDATE users SET ' .
                                                     'LastAppliedUserTemplateID=' . $newUserID . ' ' .
                                                     'WHERE UserID=' . $updateUserId . ';';

                                                // Run the query to update the preferences
                                                $db->queryDB($sql, $userRow, "updateUser Form occurance 9");

                                                // Let the user know that the template was added
                                                echo '<script>alert("A template named ' . $saveAsTemplateName . ' was added based on this user\'s preferences.");</script>';
                                            }
                                        }
                                        else if (mysqli_num_rows($preferenceToCheck)==1){
                                            // Get the row to update nicely formatted
                                            $preferenceToCheckAssoc = $preferenceToCheck->fetch_assoc();

                                            // Copy preferences and return the result
                                            $resultOfCopyPreferences=copyPreferences($db, $userRow, $preferenceToCheckAssoc["UserID"], $updateUserId);

                                            // Check to see if the update happened without incident
                                            if ($resultOfCopyPreferences == ''){
                                                // Let the user know that the template was updated
                                                echo '<script>alert("The template named ' . $saveAsTemplateName . ' was updated with this user\'s preferences.");</script>';
                                            }
                                            else {
                                                // Let them know there was an error updating the template
                                                echo '<script>alert("There was an error updating the template named ' . $saveAsTemplateName . '.");</script>';
                                            }
                                        }
                                        else {
                                            // Let them know there are multiple rows with the same name
                                            echo '<script>alert("There are already multiple templates with the same name. No template update will happen.");</script>';
                                        }
                                    }
                                }
                            }
                            else {
                                // Let them know the template name cannot be nothing
                                echo ('<script>alert("User template was NOT added to the database because the name cannot be nothing. Please add a name.");</script>');
                            }
                        }
                    }
                }
                
                // Check if there are any mods to old notes
                updateOldNotes($db, $userRow);

                // Add any new notes that the user added
                addNewNotesToDB($db, $userRow, $updateUserId, $userRow["UserID"], "EMPLOYEE");

                // Handle any new addresses
                if (isset($_POST['newAddressNumbers']) and $_POST['newAddressNumbers']!=0){
                    // Get the amount of new addresses as a variable
                    $addressNumStrings=$_POST['newAddressNumbers'];
                    $addressNums=explode('|', $addressNumStrings);

                    // Loop through and get all new address elements
                    foreach ($addressNums as $loopNumber){
                        // Get the posted items that I am worried about
                        $address1=htmlspecialchars($_POST['address1Text'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $address2=htmlspecialchars($_POST['address2Text'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $city=htmlspecialchars($_POST['cityText'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $state=htmlspecialchars($_POST['stateText'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $zip=htmlspecialchars($_POST['zipText'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $phoneNumber1=htmlspecialchars($_POST['phone1Text'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $phoneNumber2=htmlspecialchars($_POST['phone2Text'.$loopNumber], ENT_QUOTES, 'UTF-8');

                        // Let's create the insert query off of what we have
                        $sql='INSERT INTO addresses (';
                        if ($state!=null) {$sql = $sql . 'State';}
                        if ($address1!=null) {$sql = $sql . ',Address1';}
                        if ($address2!=null) {$sql = $sql . ',Address2';}
                        if ($city!=null) {$sql = $sql . ',City';}
                        if ($zip!=null) {$sql = $sql . ',Zip';}
                        if ($phoneNumber1!=null) {$sql = $sql . ',PhoneNumber1';}
                        if ($phoneNumber2!=null) {$sql = $sql . ',PhoneNumber2';}
                        $sql=$sql .') VALUES (';
                        if ($state!=null) {$sql = $sql . '"' . $state . '"';}
                        if ($address1!=null) {$sql = $sql . ', "' . $address1 . '"';}
                        if ($address2!=null) {$sql = $sql . ', "' . $address2 . '"';}
                        if ($city!=null) {$sql = $sql . ', "' . $city . '"';}
                        if ($zip!=null) {$sql = $sql . ', "' . $zip . '"';}
                        if ($phoneNumber1!=null) {$sql = $sql . ', "' . $phoneNumber1 . '"';}
                        if ($phoneNumber2!=null) {$sql = $sql . ', "' . $phoneNumber2 . '"';}
                        $sql=$sql .');';

                        // Attempt to run the query and get the response
                        if ($db->queryDB($sql, $userRow, "updateUser Form occurance 10.")){
                            // Get the most recent ID (address)
                            $newAddressID = mysqli_insert_id($db->getDBConnection());

                            // Get the posted items that I am worried about
                            $addressTypeText=htmlspecialchars($_POST['addressTypeText'.$loopNumber], ENT_QUOTES, 'UTF-8');

                            // Let's create the insert query off of what we have
                            $sql='INSERT INTO addresslinker (';
                            if ($newAddressID!=null) {$sql = $sql . 'AddressID';}
                            if ($updateUserId!=null) {$sql = $sql . ',UserID';}
                            if ($addressTypeText!=null) {$sql = $sql . ',Type';}
                            $sql=$sql .') VALUES (';
                            if ($newAddressID!=null) {$sql = $sql . $newAddressID;}
                            if ($updateUserId!=null) {$sql = $sql . ', ' . $updateUserId;}
                            if ($addressTypeText!=null) {$sql = $sql . ', "' . $addressTypeText . '"';}
                            $sql=$sql .');';

                            // Attempt to run the query and evaluate the response
                            $db->queryDB($sql, $userRow, "updateUser Form occurance 11");
                        }
                    }
                }

                // Determine if there are current addresses to look at
                if (isset($_POST['currentAddressesArray']) and $_POST['currentAddressesArray']!=0){
                    // Remove the last delimiter
                    $numbersToRemoveAsString = substr($_POST['currentAddressesArray'], 0, -1);

                    // Get the amount of current addresses as a variable
                    $addressNums=explode('|', $numbersToRemoveAsString);

                    // Loop through and get all new address elements
                    foreach ($addressNums as $loopNumber){
                        // Get the posted items that I am worried about
                        $address1=htmlspecialchars($_POST['currentAddress1'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $address2=htmlspecialchars($_POST['currentAddress2'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $city=htmlspecialchars($_POST['currentCity'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $state=htmlspecialchars($_POST['currentState'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $zip=htmlspecialchars($_POST['currentZip'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $phoneNumber1=htmlspecialchars($_POST['currentPhone1'.$loopNumber], ENT_QUOTES, 'UTF-8');
                        $phoneNumber2=htmlspecialchars($_POST['currentPhone2'.$loopNumber], ENT_QUOTES, 'UTF-8');

                        // Let's create the insert query off of what we have
                        $sql='UPDATE addresses SET ';
                        if ($state!=null) {$sql = $sql . 'State="' . $state . '"';}
                        if ($address1!=null) {$sql = $sql . ',Address1="' . $address1 . '"';}
                        if ($address2!=null) {$sql = $sql . ',Address2="' . $address2 . '"';}
                        if ($city!=null) {$sql = $sql . ',City="' . $city . '"';}
                        if ($zip!=null) {$sql = $sql . ',Zip="' . $zip . '"';}
                        if ($phoneNumber1!=null) {$sql = $sql . ',PhoneNumber1="' . $phoneNumber1 . '"';}
                        if ($phoneNumber2!=null) {$sql = $sql . ',PhoneNumber2="' . $phoneNumber2 . '"';}
                        $sql=$sql .' WHERE AddressID=' . $loopNumber . ';';

                        // Run the query to update the current address
                        $db->queryDB($sql, $userRow, "updateUser Form occurance 12");
                    }
                }

                // Determine if there are previous ones to delete
                if (isset($_POST['deleteCurrentAddresses']) and $_POST['deleteCurrentAddresses']!=''){
                    // Get the numbers to remove in order to trim and then work with it
                    $numbersToRemoveAsString = substr($_POST['deleteCurrentAddresses'], 0, -1);

                    echo("numbersToRemoveAsString = $numbersToRemoveAsString");

                    // Should be in a good form already. Let's delete them from the addresses.
                    $sql = "DELETE FROM addresses where AddressID in (" . 
                           $numbersToRemoveAsString . ");";

                    // Run the delete query the selected attachments from that table
                    $db->queryDB($sql, $userRow, "updateUser Form occurance 13");

                    // Should be in a good form already. Let's delete them from the address linker.
                    $sql = "DELETE FROM addresslinker where AddressID in (" . 
                           $numbersToRemoveAsString . ");";

                    // Run the delete query the selected attachments from that table
                    $db->queryDB($sql, $userRow, "updateUser Form occurance 14");
                }
                
                // Determine if user template applying was NOT successful
                if ($resultOfCopyPreferences !== ''){
                    // Check to see if there is a reason NOT to allow the move
                    if (strpos($resultOfCopyPreferences, "ABORT PREFERENCE COPY")!==false){
                        // Split the string on the double colon
                        $errorStrings=explode("::", (trim($resultOfCopyPreferences)));

                        // Give an alert popup of the problem
                        echo '<script>alert("' . addslashes($errorStrings[1]) . '");</script>';
                    }
                }
            }
            
            // Bypass the protector
            $_SESSION['bypassProtector']="True";

             // redirect them back to their own page
             echo ('<script>window.location = "updateUser.php?updateUserID=' . $updateUserId . '";</script>');
        }
        else {
            // Set the form submitted session variable to FALSE
            $_POST['formSubmitted']='FALSE';
        }
    }
?>
        
﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Task Management System - Update User</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />

    <script src="scripts/jquery-ui-1.10.4.custom/js/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="scripts/jquery-ui-1.11.4.custom/jquery-ui.js" type="text/javascript"></script>
    <script src="./javascript/general.js" type="text/javascript"></script>
    <script src="./javascript/addresses.js" type="text/javascript"></script>
    <script src="./javascript/notes.js" type="text/javascript"></script>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>
    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    
    <link rel="icon" href="images/ees_ico.ico"/> 
    <link href="scripts/jquery-ui-1.10.4.custom/development-bundle/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <link href="./SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    <link href="./SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
    <link rel = "stylesheet" type="text/css" href="./css/contentpage.css" >
    <link rel="shortcut icon" href="../images/logo_EES_trans_256x256.png">
    <style type="text/css">
        .Table
        {
            display: table;
            width: 100%;
        }
        .Title
        {
            display: table-caption;
            text-align: center;
            font-weight: bold;
            font-size: larger;
            width: 100%;
        }
        .Heading
        {
            display: table-row;
            font-weight: bold;
            text-align: center;
            width: 100%;
        }
        .Row
        {
            display: table-row;
            width: 100%;
        }
        .cell
        {
            display: table-cell;
            border: solid;
            border-width: thin;
            padding-left: 2px;
            padding-right: 2px;
            font-weight: bold;
            font-size: 10px;
        }
        .noteTableCell
        {
            display: table-cell;
        }
        .fullNoteLabelCell
        {
            width: 20%;
            text-align: right;
        }
        .fullNoteTextCell
        {
            width: 80%;
            text-align: left;
        }
        .fullLabelCell
        {
            width: 20%;
            text-align: center;
        }
        .fullTextCell
        {
            width: 80%;
            text-align: left;
        }
        .fileInputCell
        {
            width: 50%;
            text-align: center;
        }
        
        /* Start CSS for the addresses */
        .cell1
        {
            width: 2%;
            text-align: center;
            vertical-align: middle;
        }
        .addressCell
        {
            width: 32%;
            text-align: left;
        }
        .cityCell
        {
            width: 20%;
            text-align: center;
        }
        .stateCell
        {
            width: 10%;
            text-align: center;
        }
        zipCell
        {
            width: 8%;
            text-align: center;
        }
        phoneCell
        {
            width: 20%;
            text-align: center;
        }
        .checkCell 
        {
            width: 8%;
            text-align: center;
            vertical-align: middle;
        }
        .buttonCell
        {
            width: 8%;
            text-align: center;
            vertical-align: middle;
        }
        
        /* Start CSS for the current attachments */
        .numberCell
        {
            text-align: center;
            width: 3%;
        }
        .nameCell
        {
            text-align: center;
            width: 35%;
        }
        .typeCell
        {
            text-align: center;
            width: 20%;
        }
        .sizeCell
        {
            text-align: center;
            width: 20%;
        }
        /* Simulate the disabled atribute, but still pass the values */
        .disable{
            pointer-events:none;
            background:lightgrey;
            /* border: solid red 1px; */
        }        
        #updateDiv {
            position: sticky;
            left: 50%;
            top: 45%;
            float:right;
            display:inline-block;
            padding:0px 777px;
            clear: right;
            background-color: rgba(49, 49, 49, 0);
            pointer-events: none;
        }   
        /* Style the tab content (and add height:100% for full page content) */
        .tabcontent {
          border: 1px solid gray;
          padding: 5px 5px;
        }
        .childtablink {
          float: left;
          border-left: 1px solid gray;
          border-right: 1px solid gray;
          border-top: 1px solid gray;
          border-bottom: 2px solid forestgreen;
          outline: none;
          cursor: pointer;
          padding: 5px 5px;
          font-size: 11px;
          width: 16.66666666%;
        }
        .childtablinkblack {
          color:black;
          font-size: 8px;
        }
        .childtablinkred {
          color:red;
          font-size: 8px;
        }
        .childtablinkgreen {
          color:green;
          font-size: 8px;
        }
        .childtablink:hover {
          background-color: #777;
        }
        .childtabcontent {
          border-left: 2px solid forestgreen;
          border-right: 2px solid forestgreen;
          border-top: none;
          border-bottom: 2px solid forestgreen;
          text-align: left;
        }
        
/*        .disabled {
            opacity:0.5;
        }*/
        /* End CSS for the current attachments */
    </style>
    <script>
        function sortStatusCheckboxState(ctrlStatus, statusID){
            // Determine first if the one that is changing is the not wanting status notifications
            if (ctrlStatus.name.includes("_NoStatusChangeToNotification")){
                // If it is being checked, then it easy.  Uncheck the others.
                if (ctrlStatus.checked){
                    // Set the others to unchecked
                    document.getElementById(statusID + "_StatusChangeToNotification").checked=false;
                    document.getElementById(statusID + "_MainTaskStatusChangeNotification").checked=false;
                }
                else {
                    // Do not allow for this to be unchecked.  If it is checked, then it cannot be unchecked.
                    ctrlStatus.checked=true;
                }
            }
            else {
                // Determine if it is getting checked
                if (ctrlStatus.checked){
                    // Set the no status to unchecked
                    document.getElementById(statusID + "_NoStatusChangeToNotification").checked=false;
                }
                else {
                    // Determine which one is being unchecked
                    if (ctrlStatus.name.includes("_StatusChangeToNotification")){
                        // Determine if the other is still checked
                        if (document.getElementById(statusID + "_MainTaskStatusChangeNotification").checked==false){
                            // Check the no status control
                             document.getElementById(statusID + "_NoStatusChangeToNotification").checked=true;
                        }
                    }
                    else {
                        // Determine if the other is still checked
                        if (document.getElementById(statusID + "_StatusChangeToNotification").checked==false){
                            // Check the no status control
                             document.getElementById(statusID + "_NoStatusChangeToNotification").checked=true;
                        }
                    }
                }
            }
        }  
        
        $(function() {
              $( "#tabs" ).tabs();
        });
        
        
    </script>
</head>

<body class="thrColElsHdr">

<div id="container">
  
<!-- start of banner wrap --->

<div id="topContent">
  
<div>
   <div class="MenuBarHorizontal" id="navBar">  <ul id="TopNav" class="MenuBarHorizontal">

    <script type="text/javascript">
    <!--
    var MenuBar2 = new Spry.Widget.MenuBar("TopNav", {imgDown:"./SpryAssets/SpryMenuBarDownHover.gif", imgRight:"./SpryAssets/SpryMenuBarRightHover.gif"});
    //-->
    </script>

    </div>
  </div>
</div>
<!-- end of banner wrap --->

  <!-- end #header -->
  <br class="clearfloat" />
  <div id="sidebar1">
      <?php 
        // Determine if we are GTG
        if ($gtg){
          // Render the appropriate presentation for the tasks sidebar
          getSidebar($userRow, 'accounts');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Update User</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href=
          "<?php echo ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'?"https" : "http") . "://" . $_SERVER['HTTP_HOST'] .  $_SERVER['REQUEST_URI']); ?>"> Update User </a></div>

    <br>
    <?php
        // Determine if they are GTG
        if ($gtg){
            // Populate the user info
            echo getUser($db, $userRow, $updateUserId);
        }
        else {
            // Set the login failed to true
            $_SESSION['failedLogin']='TRUE';

            // Add a session variable that is this page URL
            $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

            // redirect to the login page
            echo ('<script>window.location = ".";</script>');
        }
    ?>       
    
  <!-- end #mainContent -->
  
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  
  <!-- start #footer --></div>
   <div id="footer">
    <p>© 2018 Evolve Engineering and Software. EES, Evolve Engineering and Software, EES Logo are registered marks of Evolve Engineering and Software.</p>
  <!-- end #footer -->
   </div>
<!-- end #container -->
</div>

</body>

</html>