<?php 
    // continue the session
    session_start();
    
    // init variables
    $updateCompanyId=-1;
    
    // now determine if it was posted via get.  That will override it.
    if (isset($_GET['updateCompanyID']) ){
        // Hold onto the Company ID in a local variable
        $updateCompanyId = $_GET['updateCompanyID'];
    }
    
    // Add includes to PHP files that I will need to access
    include 'php_only_scripts/database.php';
    include 'php_only_scripts/presentation.php';
    include 'php_only_scripts/global_functions.php';
    include 'php_only_scripts/company_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 has access to this page
        if ($userRow["UserLevel"] != 'SU' || 
            $updateCompanyId == -1 ||
            $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"]){
                // redirect to the companies page
                echo ('<script>window.location = "companies.php";</script>');
            }
            else {
                // Change the form back to NOT being submitted
                $_SESSION['formSubmitted']='FALSE';

                // Set today as the quarter to check
                $quarterStart = new DateTime();

                // Set the local variables from what was posted
                $companyName=htmlspecialchars($_POST['companyName'], ENT_QUOTES, 'UTF-8');
                $companyRowColor=htmlspecialchars($_POST['companyRowColor'], ENT_QUOTES, 'UTF-8');
                $defaultTaskStatusCompletionFactor=htmlspecialchars($_POST['defaultTaskStatusCompletionFactor'], ENT_QUOTES, 'UTF-8');
                $weekdayStartTime=htmlspecialchars($_POST['weekdayStartTime'], ENT_QUOTES, 'UTF-8');
                $weekdayEndTime=htmlspecialchars($_POST['weekdayEndTime'], ENT_QUOTES, 'UTF-8');
                $weekendStartTime=htmlspecialchars($_POST['weekendStartTime'], ENT_QUOTES, 'UTF-8');
                $weekendEndTime=htmlspecialchars($_POST['weekendEndTime'], ENT_QUOTES, 'UTF-8');
                $allowCreditPayment=(isset($_POST['allowCreditPayment'])?1:0);
                $active=(isset($_POST['active'])?1:0);
                $mainSubCompany=(isset($_POST['mainSubCompany'])?1:0);
                $setAsStore=(isset($_POST['setAsStore'])?1:0);

                // Let's create the update query off of what we have
                $sql='UPDATE companies SET ';
                if ($companyName!=null) {$sql = $sql . 'CompanyName="' . $companyName . '"';}
                $sql = $sql . ', AllowCredit=' . $allowCreditPayment;
                $sql = $sql . ', Active=' . $active;
                $sql = $sql . ', MainSubCompany=' . $mainSubCompany;
                $sql = $sql . ', Store=' . $setAsStore;
                if ($companyRowColor!=null) {$sql = $sql . ', CompanyRowColor="' . $companyRowColor . '"';}
                if ($defaultTaskStatusCompletionFactor!=null) {$sql = $sql . ', DefaultTaskStatusCompletionFactor=' . $defaultTaskStatusCompletionFactor;}
                if ($weekdayStartTime!=null) {$sql = $sql . ', WeekdayStartWorkingTime="' . $weekdayStartTime . '"';}
                if ($weekdayEndTime!=null) {$sql = $sql . ', WeekdayEndWorkingTime="' . $weekdayEndTime . '"';}
                if ($weekendStartTime!=null) {$sql = $sql . ', WeekendStartWorkingTime="' . $weekendStartTime . '"';}
                if ($weekendEndTime!=null) {$sql = $sql . ', WeekendEndWorkingTime="' . $weekendEndTime . '"';}
                $sql=$sql .' WHERE CompanyID=' . $updateCompanyId . ';';

                // Attempt to run the query and evaluate the response
                if (!$db->queryDB($sql, $userRow, "updateCompany Form occurance 1")){
                    echo '<script>alert("Company 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?
                }
                else {
                    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, "updateCompany Form occurance 2")){
                                // 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 ($updateCompanyId!=null) {$sql = $sql . ',CompanyID';}
                                if ($addressTypeText!=null) {$sql = $sql . ',Type';}
                                $sql=$sql .') VALUES (';
                                if ($newAddressID!=null) {$sql = $sql . $newAddressID;}
                                if ($updateCompanyId!=null) {$sql = $sql . ', ' . $updateCompanyId;}
                                if ($addressTypeText!=null) {$sql = $sql . ', "' . $addressTypeText . '"';}
                                $sql=$sql .');';

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

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

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

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

                    // redirect to the companies page
                    echo ('<script>window.location = "companies.php";</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 Company</title>

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

    <script src="./javascript/general.js" type="text/javascript"></script>
    <script src="./javascript/addresses.js" type="text/javascript"></script>
    
    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    <script src="scripts/jpicker-1.1.6/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="scripts/jpicker-1.1.6/jpicker-1.1.6.min.js" type="text/javascript"></script>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>
    
    <link rel="icon" href="images/ees_ico.ico"/> 
    
    <link href="scripts/jpicker-1.1.6/css/jPicker-1.1.6.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" >

    <script type="text/javascript">
      $(function()
        {
          $.fn.jPicker.defaults.images.clientPath='scripts/jpicker-1.1.6/images/';
        });
    </script>
        
    <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;
        }
        .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;
        }
        
    </style>
</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, 'companies');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Update Company</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 Company </a></div>

    <br>
    <?php
        // Determine if they are GTG
        if ($gtg){
            echo getCompany($db, $userRow, $updateCompanyId);
        }
        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>