<?php
/* Allows a mailroom worker to quickly receive an insert from a truck.
 * The only information required from the user is the advertiser.
 * it allows the gathering of date, number of pallets/boxes, pieces, notes, and receive date/time/by
 * 
 * data is placed directly into inserts table with a "received" flag being set to true.
 * when they select the insert, they will have the option of selecting from a list of already booked ones
 * if they can't find a match, then a new record will be created */

include("includes/boot.php");

if ($_POST)
  $action = $_POST['submit'];
else
  $action = $_GET['action'];

switch ($action)
{
  case "Save Insert":
    save_insert();    
    break;
  
  default:
    insert();
    break;
}

function insert()
{
    global $pubs, $advertisers, $shiptypes, $User, $Prefs;


    print "<form enctype='multipart/form-data' method=post>
        <ul class='nav nav-tabs' role='tablist'>
            <li role='presentation active'><a href='#basic' aria-controls='basic' role='tab' data-toggle='tab'>Basic Information</a></li>
        </ul>
        <div class='tab-content'>
        <div id='basic' role='tabpanel' class='tab-pane active'>";
            make_text('control_number', '', 'Control Number', 'Enter the control/tracking number. If left blank, the system will generate one for you (preferred).');
            make_select('pub', $pubs[0], $pubs, 'Publication');
            make_date('pubdate', date("Y-m-d", strtotime("+1 day")), 'Publication Date', '', 1, '', '', true);
            make_select('advertiserid', $advertisers[0], $advertisers, 'Advertiser', 'For new advertiser, enter in the space below');
            make_text('advertiserName', '', 'New advertiser', 'Only enter here if the advertiser was not in the selection above');
            make_text('salesperson', '', 'Salesperson', 'Salesperson associated with this insert.');
            make_text('insertTagline', '', 'Insert tagline', 'Tag line of flyer (ex. 2 day sale)', 50);
            
            make_checkbox('received', 1, 'Received', 'This insert has been received. If not, uncheck and leave receive count at 0');
            make_select('receiveBy', $GLOBALS['productionStaff'][$User->id], $GLOBALS['productionStaff'], 'Received By');
            make_date('receiveDate', '', 'Date received');
            make_number('receiveCount', 0, 'Receive Count', 'How many did we get?');
            
            ?>
            <div class="form-group">
                <label for="productPages" class="col-sm-2 control-label">Product Page Count</label>
                <div class='col-sm-10'>
                    <div class='row'>
                    
                        <div class="col-sm-3">
                            <small>Pages in product</small>
                            <input type="number" id="productPages" name="productPages" value="" size=10 onChange="calcStandardPages();" step='1'></input>
                        </div>
                        <div class="col-sm-3">
                            <small>Insert format, ex: booklet</small><br>  
                            <select name='productSize' id='productSize' class='form-control'  autocomplete='off'  onChange="calcStandardPages()" >
                                <?php
                                   if (count($Prefs->insertProducts) > 0)
                                       foreach ($Prefs->insertProducts as $key => $val)
                                           print "<option value='$key'>$val</option>";
                                ?>
                            </select>
                        </div>
                        <div class="col-sm-4">
                            <small>Calculated Standard (broadsheet) pages</small><br>
                            <input type="number" id="standardPages" name="standardPages" value="" size=10 readonly></input>
                        </div>
                    </div>
                </div>
            </div>
                 
            <?php
            make_checkbox('stickyNote',  0, 'Sticky Note?', 'Check if product is a sticky note');
            make_checkbox('singleSheet', 0, 'Single sheet?', 'Check if product is a single sheet');

        print "</div>";
            make_select('shipType', 0, $shiptypes, 'Ship type', 'How did they arrive?');
            make_number('shipQuantity', 0, 'Ship quantity', 'How many pallets/boxes?');
            make_number('runability', 0, 'Runability', 'Enter the degree of runability for this insert, 1=hard, 10=easy');
            make_number('pieceWeight', 0, 'Piece Weight', 'Weight of single piece?');
            make_checkbox('multiple_dates', 0, 'Multiple Dates', 'Are there multiple dates on the pallet?');
            make_textarea('insertDescription', '','Insert description','Full description of insert', 50, 3, false);
            make_text('tagColor', '', 'Tag Color', 'Color of pallet tag');
            if ($GLOBALS['insertUseLocation'])
            {
                $slocations = buildLocations('insert');
                make_select('storageLocation', $slocations[0], $slocations,'Storage Location', 'Storage location code');
            }
            make_text('printer', '', 'Printer', 'Not required', 50);
            make_text('shipper', '', 'Shipper', 'Not required', 50);
            
            make_checkbox('damaged', 0, 'Damage', "Check if the inserts arrived damaged");
            print "<div id='iDam' style='display:none;'>\n";
            make_textarea('insertDamage','','Insert Damage','Enter a brief description of the damage',50,10,false);
            print "</div>\n";
            
            ?>
            <script>
            $('#damaged').on('click',function(){
                if($(this).prop('checked'))
                {
                    $('#iDam').show();
                } else {
                    $('#iDam').hide();
                    $('#insertDamage').val('');
                }
            })
            </script>
            <?php  
        make_submit('submit','Save Insert');
        print "</form>\n";
    print "</div>";
}
function save_insert()
{
    global $Prefs;
    $pub = intval($_POST['pub']);
    $pubdate = addslashes($_POST['pubdate']);
    $advertiserid = intval($_POST['advertiserid']);
    $advertisername = addslashes($_POST['advertiserName']);
    if ($advertiserid == 0 && $advertisername != '')
    {
        $dbInsert = dbinsertquery("INSERT INTO accounts (account_name, account_advertiser, site_id)
            VALUES ('$advertisername', 1, " . SITE_ID . ")");
        $advertiserid = $dbInsert['insertid'];
    }
    $tagline = addslashes($_POST['insertTagling']);

    $received = 0;
    if ($_POST['received'])
        $received = 1;

    $singleSheet = 0;
    if ($_POST['singleSheet'])
        $singleSheet = 1;

    $stickyNote = 0;
    if ($_POST['stickyNote'])
        $stickyNote = 1;

    $damaged = 0;
    if($_POST['damaged'])
        $damaged = 1;

    $multipleDates = 0;
    if($_POST['multiple_dates'])
        $multipleDates = 1;

    $receiveBy = $_POST['receiveBy'];
    $receiveDate = $_POST['receiveDate'];
    $receiveDateTime = date("Y-m-d H:i");
    $receiveCount = $_POST['receiveCount'];
    $pieceWeight = $_POST['pieceWeight'];
    $pageCount = $_POST['productPages'];
    $productSize = $_POST['productSize'];
    $standardPages = $_POST['standardPages'];
    
    if ($standardPages=='' || $standardPages == 0)
        $standardPages=$pageCount * $Prefs->insertProductsOptions[$productSize];
    
    $shipType = $_POST['shipType'];
    $shipQuantity = $_POST['shipQuantity'];
    $insertDescription = addslashes($_POST['insertDescription']);
    $insertDamage = addslashes($_POST['insertDamage']);
    $shipper = addslashes($_POST['shipper']);
    $storageLocation = addslashes($_POST['storageLocation']);
    $tagColor = addslashes($_POST['tagColor']);
    $printer = addslashes($_POST['printer']);
    $runability = addslashes($_POST['runability']);
    $salesperson = addslashes($_POST['salesperson']);
    
    if ($receiveCount == '')
        $receiveCount = 0;

    if ($pageCount == '')
        $pageCount = 0;

    if ($standardPages == '')
        $standardPages = 0;

    if ($shipQuantity == '')
        $shipQuantity = 0;
    
    $error = "";
    $insertInsertIntoDatabase = dbinsertquery("INSERT INTO inserts (advertiser_id, insert_tagline, receive_date,
        shipper, printer, receive_count,
        piece_weight, ship_type, ship_quantity,
        salesperson, received, receive_by,
        single_sheet, tag_color,
        storage_location, damage, insert_damage,
        insert_description, sticky_note, standard_pages)
        VALUES ('$advertiserid', '$tagline', '$receiveDate', 
        '$shipper', '$printer', $receiveCount,
        '$pieceWeight', '$shipType', $shipQuantity,
        '$salesperson', $received, '$receiveBy',
        $singleSheet, '$tagColor',
        '$storageLocation', $damaged, '$insertDamage',
        '$insertDescription', $stickyNote, $standardPages)");
    $error .= $insertInsertIntoDatabase['error'];
    $dbInsert = dbinsertquery("INSERT INTO inserts_received (received, receive_date, receive_count, receive_datetime, shipper, 
        printer, piece_weight, ship_type, ship_quantity, advertiser_id,
        product_size, pages, std_pages, receive_by, single_sheet,
        tag_color, storage_location, damage, insert_damage,
        insert_tagline, insert_description, sticky_note, site_id, insert_pub_id,
        matched, scheduled_pubdate, runability, multiple_dates)
        VALUES ('$received', '$receiveDate', '$receiveCount', '$receiveDateTime', '$shipper',
        '$printer', '$pieceWeight', '$shipType', '$shipQuantity', '$advertiserid',
        '$productSize', '$pageCount', '$standardPages', '$receiveBy', '$singleSheet',
        '$tagColor', '$storageLocation', '$damaged', '$insertDamage', 
        '$tagline', '$insertDescription', '$stickyNote', '" . SITE_ID . "', '$pub', 
        0, '$pubdate', '$runability', '$multipleDates')");
    $error .= $dbInsert['error'];
    $insertid = $dbInsert['insertid'];
    
    $dbPub = dbselectsingle("SELECT * FROM publications WHERE id = $pub");
        
    if($_POST['control_number'] != '')
    {
        $controlNumber = str_replace(" ", "", addslashes($_POST['control_number']));
        $controlNumber = str_replace("-", "", $controlNumber);
    }
    else
    {
        $pubcode = $dbPub['data']['pub_code'];
        $controlNumber = $pubcode . $insertid;
    }

    $controlNumber = strtoupper($controlNumber);
    dbexecutequery("UPDATE inserts SET control_number = '$controlNumber' WHERE id = {$insertInsertIntoDatabase['insertid']}");
    dbexecutequery("UPDATE inserts_received SET control_number = '$controlNumber' WHERE id = $insertid");
    
    if($dbPub['numrows'] > 0)
    {
        /* To-do: If mail sending needs to be re-added then it can be done here.
         * The old htmlMimeMail does not work and PHPMailer must be used instead.
        $pubInfo = $dbPub['data'];
        if($pubInfo['insert_receive_email'] != '')
        {
            //send an email
            if($_POST['advertiserid'] == 0)
                $advertisername=$_POST['advertiserName'];
            else
                $advertisername=$advertisers[$advertiserid];

            if($pub != 0)
                $pubName=$pubs[$pub];
            else
                $pubName='Not specified';

            $message = "Hello, the following insert has been received:<br /><br />";
            $message .= "Advertiser Name: $advertisername<br />";
            $message .= "Paperwork shows this is for Publication Name: $pubName<br />";
            $message .= "Paperwork shows this is for Insert date: ".date("D m/d/Y",strtotime($pubdate))."<br />";
            $message .= "It was given a tag line of ".$tagline.".<br />";
            $message .= "It was received on ".date("D m/d/Y H:i",strtotime($receiveDateTime))." by ".$GLOBALS['productionStaff'][$receiveBy]."<br />";
            $message .= "The insert has been given a control number of: <b>$controlNumber</b><br />";
            $message .= "Please add the following to the description field in the Vision Data ad order: C#$controlNumber <br />";
            $message .= "The product is a $pageCount ".$Prefs->insertProducts[$productSize].".<br />";
            $message .= "A total of $receiveCount were received <br />";

            if($shipType == 'pallet')
                $message .= "on $shipQuantity pallets.<br />";
            else
                $message .= "in $shipQuantity boxes.<br />";

            if($tagColor != '')
                $message .= "The \"$shipType\"s were marked with a $tagColor tag";

            if ($Prefs->insertUseLocation)
            {
                $slocations = buildLocations();
                $message .= " and stored on " . $slocations[$storageLocation] . "<br />";
            }
            else
                $message .= ".<br />";

            if($singleSheet)
                $message .= "Product is a single sheet.<br />";

            if($stickyNote)
                $message .= "Product is a sticky note.<br />";

            if($damaged)
                $message .= "We noted some damage to the inserts when they arrived:<br />$insertDamage<br />";

            if($filename != '')
            {
                $message .= "Here is a photo of the cover: <br />
                <a href='$GLOBALS[serverIPaddress]/artwork/inserts/$foldername/$filename'>
                    Click here to view online at full size.</a><br /><br />
                    <img src='$GLOBALS[serverIPaddress]/artwork/inserts/$foldername/$filename' width=400 />";
            }
            
            $sendTo=stripslashes($pubInfo['insert_receive_email']);
            $subject=htmlentities("A new insert has been received in production for $advertisername for $pubName.");

            $mail = new htmlMimeMail();
            $mail->setHtml($message);
            $mail->setFrom($GLOBALS['systemEmailFromAddress']);
            $mail->setSubject($subject);
            $mail->setHeader('Sender','Mango');
            
            if ($sendTo!='')
                $result = $mail->send(array($sendTo),'mail');                                    
        }
        else
        {
            print "<div class='alert alert-danger' role='alert'>No email address defined for who to send the receipt notification to.</div><br><br>";
        }
        */
    }
    else
        print "<div class='alert alert-danger' role='alert'>Unable to find a corresponding publication for id $pub</div><br><br>";

    print "<div class='panel panel-success'>
      <div class='panel-heading'>Insert Received Successfully</div>
      <div class='panel-body'>
        Please write the following control number on the insert and deliver it to the preprint coordinator or the appropriate bucket<br>
        <span style='font-size:24px;'>$controlNumber</span>
      </div>
      <div class='panel-footer clearfix'><a href='?action=add' class='btn btn-success pull-right'>Receive another insert</a></div>
    </div>
    ";
    
    if ($error != '')
        print $error;
}

$Page->footer();
?>
