<?php 
    // continue the session
    session_start();
    
    include_once dirname(__FILE__) . '/../php_only_scripts/database.php';
    include_once dirname(__FILE__) . '/../php_only_scripts/global_functions.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();
    }
    
    // Set passing variables to defaults
    $selectedCompany=-1;
    $blanksPerPage=0;
    $showWhatFinishedState=0;
    $taskSearchPhrase='';
    $sortNumber=1;
    $statusNumber=-1;

    // Set the return to be the main blanks page at first
    $webSiteBase='../blanks.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 tasks per page is passed in
    if (isset($_GET['bpp'])){
        // Set the session variable tasks per page to the one passed in
        $blanksPerPage = $_GET['bpp'];
    }

    // 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 there is a status preference
    if (isset($_GET['s']) ){
        // Hold onto the status info
        $statusNumber = $_GET['s'];
    }

    // Create the page to go to
    $pageParams = "?sfs=" . $showWhatFinishedState . "&cs=" .  $selectedCompany. 
                  "&sp=" .  $taskSearchPhrase. "&bpp=" .  $blanksPerPage. "&sn=" .  
                  $sortNumber. "&s=" . $statusNumber;

    // Determine if the task ID to update has been sent via post
    if ($userRow["CanModify"] == 1 && isset($_GET['readyBlankID'])){
        // Get the task ID to work with
        $jobBlanksID = $_GET['readyBlankID'];
        
        // update the blank row 
        // TODO: Our server is central.  We are mountain.  Handle it so that we don't have to have this time adjusted.
        $sql = 'UPDATE jobblanks SET BlankReady=1, BlankReadiedDate=(SUBTIME(CURTIME(), "01:00:00")), BlankReadiedByID=' . 
               $userRow["UserID"] . ', IsPendingStock=0, IsPendingStockDate=NULL, IsPendingStockByID=NULL ' . 
               'WHERE JobBlanksID=' . $jobBlanksID . ';';

        // Attempt to change the row that needs to be changed
        if ($db->queryDB($sql, $userRow, "ready_blank Form occurance 1")){
            // Create a query to get information on this blank, it's material and the task related to it
            $sql = 'SELECT jb.*, ' .
                   '       ru.FirstName AS ReadiedByFirstName, ru.LastName AS ReadiedByLastName, ' .
                   '       t.ParentID, t.CompanyID, t.TypeID AS TaskTypeID, t.StatusID, ' .
                   '       m.Category AS MaterialCategory, m.Name AS MaterialName ' .
                   'FROM jobblanks jb ' . 
                   'LEFT JOIN users ru ON jb.BlankReadiedByID = ru.UserID ' .
                   'LEFT JOIN tasks t  ON jb.TaskID = t.TaskID ' .
                   'LEFT JOIN material m ON jb.MaterialID = m.MaterialID ' .
                   'WHERE jb.JobBlanksID=' . $jobBlanksID . ' ' .
                   'ORDER BY jb.TaskID;';
            
            // Attempt to get the row
            $row = $db->queryDB($sql, $userRow, "ready_blank Form occurance 2");

            // Attempt to get the blank row
            $assocBlank = $row->fetch_assoc();

            // Set the things we can
            $taskID = $assocBlank["TaskID"];
            $parentTaskNumber  = $assocBlank["ParentID"];
            $createdByID = $assocBlank["CreatedByID"];
            $type = $assocBlank["Type"];
            $dimension1 = $assocBlank["Dimension1"];
            $dimension1Clean = $assocBlank["Dimension1Clean"];
            $dimension1Precise = $assocBlank["Dimension1Precise"];
            $dimension1Worded = 'Rough';
            $dimension2 = $assocBlank["Dimension2"];
            $dimension2Clean = $assocBlank["Dimension2Clean"];
            $dimension2Precise = $assocBlank["Dimension2Precise"];
            $dimension2Worded = 'Rough';
            $dimension3 = $assocBlank["Dimension3"];
            $dimension3Clean = $assocBlank["Dimension3Clean"];
            $dimension3Precise = $assocBlank["Dimension3Precise"];
            $dimension3Worded = 'Rough';
            $blankReadiedByID = $assocBlank["BlankReadiedByID"];
            $reason = $assocBlank["Reason"];
            $quantity = $assocBlank["Quantity"];
            $materialCategory = $assocBlank["MaterialCategory"];
            $materialName = $assocBlank["MaterialName"];
            $readiedByFirstName = $assocBlank["ReadiedByFirstName"];
            $readiedByLastName = $assocBlank["ReadiedByLastName"];
            
            $wallThickness = $assocBlank["WallThickness"];
            $rush = $assocBlank["Rush"];

            // Determine if Dimension 1 is precise or clean
            if ($dimension1Clean==1){
                // Set it to say Clean
                $dimension1Worded='Clean';
            }
            else if ($dimension1Precise==1){
                // Set it to say precise
                $dimension1Worded='Precise';
            }
                
            // Determine if Dimension 2 is precise or clean
            if ($dimension2Clean==1){
                // Set it to say Clean
                $dimension2Worded='Clean';
            }
            else if ($dimension2Precise==1){
                // Set it to say precise
                $dimension2Worded='Precise';
            }
                
            // Determine if Dimension 3 is precise or clean
            if ($dimension3Clean==1){
                // Set it to say Clean
                $dimension3Worded='Clean';
            }
            else if ($dimension3Precise==1){
                // Set it to say precise
                $dimension3Worded='Precise';
            }
            
            // Create the visualized task orientation as though this IS the parent
            $firstFour = str_pad($taskID,4,"0",STR_PAD_LEFT);
            $lastFour = '0000';

            // Determine if we are making a child of the parent right now
            if ($parentTaskNumber != 0){
                // Create the visualized task orientation as though this IS the parent
                $firstFour = str_pad($parentTaskNumber,4,"0",STR_PAD_LEFT);
                $lastFour = $taskID;
            }

            // Create blank specs
            $blankSpecs = $quantity . " blanks of " . 
                          $dimension1 . " (" . $dimension1Worded . 
                          ") x " . $dimension2 . " (" . $dimension2Worded . 
                          ") x " . $dimension3 . " (" . $dimension3Worded . ") " .
                          "<br>Material Category: " . $materialCategory . 
                          "<br>Material Name:" . $materialName . 
                          " " . $type;

            // Create the subject for just a readied blank
            $subject = " Blank for TaskID " . $taskID . ": With specs of - " . 
                       $blankSpecs . " HAS BEEN readied. ";

            // Create the generic message for just a submitted blank
            $messageToSend= 'There has been a blank READIED by ' . 
                    $readiedByFirstName . ' ' . $readiedByLastName . 
                    ' for task ID ' . $firstFour . '-' . $lastFour . 
                    '<a href="https://www.eestms.com/' . 
                    getTMSHome() . '/updateTask.php?updateTaskID=' . 
                    $taskID . '&parentTaskId=' . $parentTaskNumber . 
                    '"> (Click To View)</a>' . '.<br><br>The specs were:<br>' . 
                    $blankSpecs . '<br><br>Reason is: ' . $reason . '<br><br>' . 
                    'If you would like to check on this blank, ' . 
                    'you can do so at www.eestms.com/' . getTMSHome() . '.<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';

            // Add the condition to not include submittor
            $extraConditionalSQL = ' AND   UserID <> ' . $blankReadiedByID . ' AND SUEmployee=1 AND AccountStatus="Active" ';

            // Add 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";

            // Let's create and get the users to inform
            $sql='SELECT * 
                  FROM users 
                  WHERE (UserID = ' . $createdByID . '  
                         OR ReceiveBlankCutNotificationUpdate = 1) 
                  AND UserTemplateOnly=0 '
                  .
                  $extraConditionalSQL
                  . ';';
            $usersToNotify = $db->queryDB($sql, $userRow, "ready_blank Form occurance 3.");

            // Loop through the returned results
            while ($userToNofity=mysqli_fetch_array($usersToNotify)){
                try {
                    // Attempt to mail it
                    mail($userToNofity["EMail"],$subject,$messageToSend,$headers);
                } 
                catch (Exception $e) {
                    echo("The notification was not sent to " . $assocUser["EMail"] .
                         " because of an error.");
                }
            }
        }
    }

    // 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>');
    }
?>