<?php    
    include_once dirname(__FILE__) . '/../global_after_session.php';
    include_once dirname(__FILE__) . '/../database.php';
    include_once dirname(__FILE__) . '/../global_functions.php';

    function copyBlank($db, $userRow, $blankIDToCopy, $quantity, $inAddedReason, $rushed){
        // Set nothing for the return for now
        $result="";
        try {
            // Determine if they are currently successful as well as the proper variables are passed in
            if ($blankIDToCopy!= null && $blankIDToCopy>0 && 
                $quantity!= null && $quantity>0){
                    // Determine if there is an added reason
                    $addedReason='';
                    if ($inAddedReason!=null && $inAddedReason!=""){
                        // Create the reason to add to the query
                        $addedReason="\r\n\r\n" . date('d/m/y H:i:s') . " - " . $inAddedReason;
                    }
                
                    // Create the query as if there is a parent
                    $sql='INSERT INTO jobblanks(TaskID, MaterialID, CreatedByID, ' . 
                            'SuggestedMaterialStockID, Category, Type, ' . 
                            'Dimension1, Dimension1Precise, Dimension1Clean, ' . 
                            'Dimension2, Dimension2Precise, Dimension2Clean, ' . 
                            'Dimension3, Dimension3Precise, Dimension3Clean, ' . 
                            'QuantityDimension, WallThickness, Quantity, Reason, ' . 
                            'Submitted, SubmittedByID, SubmittedDate, Rush) ' . 
                          'SELECT TaskID, MaterialID, CreatedByID, ' . 
                            'SuggestedMaterialStockID, Category, Type, ' . 
                            'Dimension1, Dimension1Precise, Dimension1Clean, ' . 
                            'Dimension2, Dimension2Precise, Dimension2Clean, ' . 
                            'Dimension3, Dimension3Precise, Dimension3Clean, ' . 
                            'QuantityDimension, WallThickness, ' . $quantity . ', ' . 
                            'CONCAT(IF(Reason IS NULL,\'\',Reason), \'' . $addedReason . '\'), ' .
                            '1, ' . $userRow["UserID"] . ', NOW(), ' . $rushed . ' ' . 
                            'FROM jobblanks WHERE JobBlanksID=' . $blankIDToCopy . ';';

//return 'ABORT BLANK COPY (copy_task_blank)::' . $inAddedReason . ' -- ' . $sql;

                // Attempt to update the task
                if ($db->queryDB($sql, $userRow, "copy_task_blank occurance 1")){
                    // Get the most recent ID (task)
                    $newBlankID = mysqli_insert_id($db->getDBConnection());
                    
                    // Now create a query to get the blank(s) information that we just submitted
                    $sql='SELECT *, t.ParentID ' . 
                         'FROM jobblanks jb ' . 
                         'LEFT JOIN tasks t ON jb.TaskID = t.TaskID ' . 
                         'WHERE JobBlanksID=' . $newBlankID . ';';
                    
                    // Attempt to get the row
                    $blankRow = $db->queryDB($sql, $userRow, "copy_task_blank occurance 2");

                    // Attempt to get the blank row
                    $assocBlank = $blankRow->fetch_assoc();
                    
                    // Set dimension one text to be rough 
                    $dimension1Text = 'Rough';

                    // Determine if it is other than rough
                    if ($assocBlank["Dimension1Precise"]==1){
                        // Add the text to indicated that it is precise
                        $dimension1Text = 'Precise';
                    }
                    else if ($assocBlank["Dimension1Clean"]==1){
                        // Add the title to indicated that it is clean
                        $dimension1Text = 'Clean';
                    }
    
                    // Set dimension two text to be rough 
                    $dimension2Text = 'Rough';

                    // Determine if it is other than rough
                    if ($assocBlank["Dimension2Precise"]==1){
                        // Add the text to indicated that it is precise
                        $dimension2Text = 'Precise';
                    }
                    else if ($assocBlank["Dimension2Clean"]==1){
                        // Add the title to indicated that it is clean
                        $dimension2Text = 'Clean';
                    }
    
                    // Set dimension three text to be rough 
                    $dimension3Text = 'Rough';

                    // Determine if it is other than rough
                    if ($assocBlank["Dimension3Precise"]==1){
                        // Add the text to indicated that it is precise
                        $dimension3Text = 'Precise';
                    }
                    else if ($assocBlank["Dimension3Clean"]==1){
                        // Add the title to indicated that it is clean
                        $dimension3Text = 'Clean';
                    }
    
                    // Determine if this blank is awaiting stock
                    $rushSubjectString = '';

                    // Determine if this is a rush part
                    $rushString = 'in a timely mannner. It is not rushed';
                    if (boolval($rushed)){
                        // Create the rush strings
                        $rushSubjectString = "** RUSH **";
                        $rushString = " with the greatest of haste. This is a rush job";
                    }

                    // Finish off the rush string
                    $rushString='This blank is to be cut ' . $rushString . '.';

                    // We need to query the material
                    $materialSQL="SELECT * FROM material WHERE MaterialID = " . $assocBlank["MaterialID"] . ";";
                    $row = $db->queryDB($materialSQL, $userRow, "copy_task_blank occurance 3");
                    $assocMaterial = $row->fetch_assoc();

                    // Create blank specs
                    $blankSpecs = $quantity . " blanks of " . 
                                  $assocBlank["Dimension1"] . " (" . $dimension1Text . 
                                  ") x " . $assocBlank["Dimension2"] . " (" . $dimension2Text . 
                                  ") x " . $assocBlank["Dimension3"] . " (" . $dimension3Text . ") " .
                                  $assocMaterial["Category"] . " " . $assocMaterial["Name"] . 
                                  " " . $assocBlank["Type"];

                    // Create the generic subject for just a submitted blank
                    $subject = $rushSubjectString . " TaskID " . $assocBlank["TaskID"] . ": " . 
                               $blankSpecs . " to be cut. " . $rushSubjectString;

                    // Create the generic message for just a submitted blank
                    $messageToSend= 'There has been a blank creation submitted by ' . 
                            $userRow['FirstName'] . ' ' . $userRow['LastName'] . 
                            ' for task ID ' . $assocBlank["TaskID"] .  
                            '<a href="https://www.eestms.com/' . getTMSHome() . 
                            '/updateTask.php?updateTaskID=' . $assocBlank["TaskID"] . 
                            '&parentTaskId=' . $assocBlank["ParentID"] . '"> (Click To View)</a>' .
                            '.  ' . $rushString . '<br><br>The specs are:<br>' . 
                            $blankSpecs . '<br><br>Reason is:<br>' . str_replace("\r\n","<br>",$assocBlank["Reason"]) .  
                            '<br><br>Cut Dimension is:<br>' . $assocBlank["QuantityDimension"] . '<br><br>' . 
                            '<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 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 = ' . $assocBlank["CreatedByID"] . ' 
                          OR    ReceiveBlankCutNotificationUpdate = 1) 
                          AND   UserTemplateOnly=0 
                          AND   UserID <> ' . $userRow["UserID"] . ' AND SUEmployee=1 AND AccountStatus="Active";';
                    $usersToNotify = $db->queryDB($sql, $userRow, "blank_presentation Form occurance 9.");

                    // 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) {
                        }
                    }
                }
                else{
                    // Set all as a fail
                    return 'ABORT BLANK COPY (copy_task_blank)::The blank(s) to copy failed.  ' . 
                           'Please check the data submitted. If correct, contact TMS admin.';
                }
                
            }
            else {
                // Set all as a fail
                return 'ABORT BLANK COPY (copy_task_blank)::The blank(s) to copy failed.  ' . 
                       'The data seems to be incorrect. Please try to submit again.';
            }
        } 
        catch (Exception $ex) {
            // Assign the output string as to what happened
            return 'ABORT BLANK COPY (copy_task_blank)::There was an erro caught when attempting ' . 
                   'to copy the blank(s). The error is: \n\n' . $ex->getMessage();
        } 

        // Return whatever we got
        return $result;
    }

    $db = new Database();
    $db->setupTmsDB();

    // Set defaults for the passed in variables
    $sessionID=-1;

    // check the passed in session ID
    if (isset($_GET['sessionID']) ){
        // get the passed in session ID
        $sessionID = $_GET['sessionID'];
    }

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser($sessionID);
    if (mysqli_num_rows($currentUser)!=1){
        echo 'ABORT BLANK COPY (copy_task_blank)::Your session has expired.  ' . 
             'Refresh the page before adding a sticky note.';
    }
    else {
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();

        // Set defaults for the passed in variables
        $blankIDToCopy=-1;
        $quantity=0;
        $addedReason='';
        $rushed=0;

        // Check for the blank ID to copy
        if (isset($_GET['blankIDToCopy']) ){
            // Hold on to the Blank ID
            $blankIDToCopy = $_GET['blankIDToCopy'];
        }

        // Check for the quantity to copy
        if (isset($_GET['quantity']) ){
            // Hold on to the quantity to copy
            $quantity = $_GET['quantity'];
        }

        // Check for the additional reason 
        if (isset($_GET['addedReason']) ){
            // Hold on to the additional reason
            $addedReason = htmlspecialchars($_GET['addedReason']);
        }

        // Check for the rushed flag
        if (isset($_GET['rushed']) ){
            // Hold on to the rushed flag
            $rushed = htmlspecialchars($_GET['rushed']);
        }

        // Attempt to add the blanks
        $blankToCopyReturn = copyBlank($db, $userRow, $blankIDToCopy, $quantity, $addedReason, $rushed);
        
        // Return the note ID
        echo $blankToCopyReturn;
    }
?>   

