<?php
include("includes/boot.php");

use Mango\DB\Tables\inserts;

if ($_POST)
    $action = $_POST['submit'];
else
    $action = $_GET['action'];

switch ($action)
{
    case "Update Insert":
        save_insert();
        break;

    case "Schedule Insert":
        save_schedule();
        break;

    case "Cancel and return":
        displayInsertsList();
        break;

    case "add":
        inserts('add');
        break;

    case "edit":
        inserts('edit');
        break;

    case "schedule":
        schedule();
        break;

    case "editschedule":
        schedule();
        break;

    case "deleteschedule":
        delete_schedule('list');
        break;

    case "confirm":
        inserts('confirm');
        break;

    case "receive":
        inserts('receive');
        break;

    case "delete":
        delete_insert();
        break;

    case "import":
        redirect("insertsImporter.php?action=import");
        break;

    default:
        displayInsertsList();
        break;
}

// To-do: Refactor this abomination
function inserts($action): void
{
    global $Prefs, $pubs, $advertisers, $shiptypes, $User;
    $advertisers[0] = 'Please choose (click + to add new)';

    // Terminate when not adding or editing inserts.
    if ($action != "add" && $action != "edit")
        return;

    $button = "Update Insert";

    if ($action == 'add')
    {
        $insertDate = date("Y-m-d", strtotime("+1 day"));
        $receiveDate = date("Y-m-d");
        $salesperson = '';
        $advertiserid = 0;
        $keepRemaining = 0;
        $receiveBy = $_SESSION['firstname'];
        $buyCount = 0;
        $insertCount = 0;
        $receiveCount = 0;
        $buyCount = 0;
        $receiveWeight = '0.00';
        $pieceWeight = '0.00';
        $productSize = 1;
        $productPages = 0;
        $standardPages = 0;
        $damage = 0;
        $shipType = 'pallet';
        $shipQuantity = 0;
        $singleSheet = 0;
        $slickSheet = 0;
        $stickyNote = 0;
        $tagColor = 'White';
        $storageLocation = 0;
        $insertionOrder = 0;
        $received = 0;

        //create an insert record immediately
        $dt = date("Y-m-d H:i");
        $dbInsert = dbinsertquery("INSERT INTO inserts (advertiser_id, site_id, created_datetime, created_by, temporary)
            VALUES (0, " . SITE_ID . ", '$dt', " . $User->id . ", 1)");
        $insertid = $dbInsert['insertid'];
    } 
    else
    {
        $insertid = intval($_GET['insertid']);
        $dbInsert = dbselectsingle("SELECT * FROM inserts WHERE id = $insertid");
        $insert = $dbInsert['data'];
        $advertiserid = $insert['advertiser_id'];
        $salesperson = stripslashes($insert['salesperson']);
        $insertTagline = stripslashes($insert['insert_tagline']);
        $receiveDate = stripslashes($insert['receive_date']);
        $insertDate = stripslashes($insert['insert_date']);
        $shipper = stripslashes($insert['shipper']);
        $printer = stripslashes($insert['printer']);
        $buyCount = stripslashes($insert['buy_count']);
        $insertCount = stripslashes($insert['insert_count']);
        $received = stripslashes($insert['received']);
        $receiveBy = stripslashes($insert['receive_by']);
        $receiveCount = stripslashes($insert['receive_count']);
        $receiveWeight = stripslashes($insert['receive_weight']);
        $pieceWeight = stripslashes($insert['piece_weight']);

        $productSize = stripslashes($insert['product_size']);
        $productPages = stripslashes($insert['product_pages']);
        $standardPages = stripslashes($insert['standard_pages']);

        $damage = stripslashes($insert['damage']);
        $insertDamage = stripslashes($insert['insert_damage']);
        $shipType = $insert['ship_type'];
        $shipQuantity = $insert['ship_quantity'];
        $singleSheet = $insert['single_sheet'];
        $slickSheet = $insert['slick_sheet'];
        $tagColor = $insert['tag_color'];
        $storageLocation = $insert['storage_location'];
        $insertNotes = $insert['insert_notes'];
        $insertDescription = $insert['insert_description'];
        $insertionOrder = $insert['insertion_order'];
        $stickyNote = $insert['sticky_note'];
        $keepRemaining = $insert['keep_remaining'];
        $controlNumber = $insert['control_number'];

        // check for a sub-action of "delete" now so we can fix the appropriate schedule
        if ($_GET['subaction'] == 'delete' && $_GET['schedid'] != 0)
            delete_schedule('insert');
    }

    print "<form method=post class='form-horizontal' enctype='multipart/form-data'>";
    print "<div>"; // begins wrapper for tabbed content

    if ($_GET['tab'])
        $activeTab = $_GET['tab'];
    else
        $activeTab = 'requiredInfo';

    print "<ul class='nav nav-tabs' role='tablist'>\n";
    print "<li role='presentation' class='" . ($activeTab == 'requiredInfo' ? ' active' : '') . "'><a href='#requiredInfo' aria-controls='requiredInfo' role='tab' data-toggle='tab'>Required Insert Information</a></li>\n";
    print "<li role='presentation' class='" . ($activeTab == 'schedules' ? ' active' : '') . "'><a href='#schedules' aria-controls='schedules' role='tab' data-toggle='tab'>Schedules</a></li>\n";
    print "<li role='presentation' class='" . ($activeTab == 'insertDetails' ? ' active' : '') . "'><a href='#insertDetails' aria-controls='insertDetails' role='tab' data-toggle='tab'>Insert Details</a></li>\n";
    print "<li role='presentation' class='" . ($activeTab == 'shipping' ? ' active' : '') . "'><a href='#shipping' aria-controls='shipping' role='tab' data-toggle='tab'>Shipping Details</a></li>\n";
    print "</ul>\n";

    print "<div class='tab-content'>\n";

    print "<div id='requiredInfo' role='tabpanel' class='tab-pane " . ($activeTab == 'requiredInfo' ? ' active' : '') . "'>\n";
    print "<div class='row'>
        <div class='col-xs-12 col-md-6'>
        <h3>Advertiser</h3>";
    make_text('salesperson', $salesperson, 'Salesperson');
    make_select('advertiserid', $advertisers[$advertiserid], $advertisers, 'Advertiser', '', '', true, '', '', '', 'addAdvertiserSelectOption.php');
    make_number('buyCount', $buyCount, 'Buy Count', 'How many has the customer ordered?');
    make_text('insertTagline', $insertTagline, 'Insert tagline', 'Tag line of flyer (ex. 2 day sale)', 50);
    make_text('insertionOrder', $insertionOrder, 'Insert Order #');
    make_number('productPages', $productPages, 'Product Page Count', '', '', false, 'calcStandardPages();');
    make_select('productSize', $Prefs->insertProducts[$productSize], $Prefs->insertProducts, 'Insert Type', 'Insert format, ex: booklet', '', false, 'calcStandardPages()');
    make_number('standardPages', $standardPages, 'Standard Page Count', 'Calculated Standard (broadsheet) pages');

    print "<h3>Zones</h3>";
    outputZonesToList($insertid);
    
    print "<h3>Receiving</h3>\n";
    $userHasPermission = getUserInsertReceivingPermission();
    // Do not output the Receiving options when editing an existing insert and the user lacks the appropriate permissions
    if ($action == "edit" && !$userHasPermission)
        print "<p>You do not have permission to modify the Received status of inserts.</p>";
    else
    {
        make_text(
            'controlNumber',
            $controlNumber,
            'Control Number',
            'If the insert has been received and you have the control number, enter it here to automatically tie to the received record. If you do this, you do not need to enter other receiving information.',
        );
        make_checkbox('received', $received, 'Received', 'This insert has been received. If not, uncheck and leave receive count at 0');
        make_select('receiveBy', $GLOBALS['mailers'][$receiveBy], $GLOBALS['mailers'], 'Received By');
        make_date('receiveDate', $receiveDate, 'Date received');
        make_number('receiveCount', $receiveCount, 'Receive Count', 'How many did we get?');
    }
    
    print "</div>
        <div class='col-xs-12 col-md-6'>";
    print "<h3>Miscellaneous</h3>\n";
    make_textarea('insertNotes', $insertNotes, 'General Notes', '', 80, 6, true);
    make_textarea('insertDescription', $insertDescription, 'Insert description', 'Full description of insert', 80, 6, true);
    make_checkbox('keepRemaining', $keepRemaining, 'Keep Leftover?', 'Check to keep leftover for a future run');
    make_checkbox('stickyNote', $stickyNote, 'Sticky Note?', 'Check if product is a sticky note');
    print "</div></div></div>";

    print "<div id='schedules' role='tabpanel' class='tab-pane" . ($activeTab == 'schedules' ? ' active' : '') . "'>\n";
    //lets find all inserts that share this core insert
    print "<div class='row'>\n";
    print "<div class='col-md-12 col-xs-12'>\n";
    print "<table id='scheduleTable' class='table table-striped table-bordered'>\n";
    print "<tr>\n";
    print "<td>Publication</td>\n";
    print "<td>Press Run</td>\n";
    print "<td>Date</td>\n";
    print "<td>Count</td>\n";
    print "<td>Zone Count</td>";
    print "<td>Actions</td>";
    print "</tr>\n";

    $dbShared = dbselectmulti("SELECT * FROM inserts_schedule WHERE insert_id = $insertid ORDER BY insert_date ASC");
    if ($dbShared['numrows'] > 0)
    {
        foreach ($dbShared['data'] as $shared)
        {
            $shareid = $shared['id'];
            $killstyle = '';
            if ($shared['killed'])
                $killstyle = 'color:red;text-decoration: line-through;';

            if ($shared['pressrun_id'] != 0)
            {
                $dbPressRun = dbselectsingle("SELECT run_name FROM publications_runs WHERE id = $shared[pressrun_id]");
                $pressrun = stripslashes($dbPressRun['data']['run_name']);
            }
            else
                $pressrun = "N/A";

            print "<tr id='sched-$shareid'>\n";
            print "<td style='$killstyle'>" . $pubs[$shared['pub_id']] . "</td>\n";
            print "<td>$pressrun</td>\n";
            print "<td style='$killstyle'>" . date("m/d/Y", strtotime($shared['insert_date'])) . "</td>\n";
            print "<td style='$killstyle'>" . $shared['insert_quantity'] . "</td>\n";

            $dbCount = dbselectsingle("SELECT zone_count as needed FROM inserts_zoning WHERE insert_id = $shareid");
            if ($dbCount['error'] == '')
            {
                $insertNeeded = $dbCount['data']['needed'];
                if ($insertNeeded == '')
                    $insertNeeded = 0;
            }
            else
                $insertNeeded = 0;

            print "<td style='$killstyle'>$insertNeeded</td>";
            print "<td>
                <a href='?action=edit&subaction=edit&tab=schedules&insertid=$insertid&schedid=$shareid'><i class='fa fa-pencil'></i></a>&nbsp;&nbsp;&nbsp;";
            print "<a href='?action=edit&subaction=delete&tab=schedules&insertid=$insertid&schedid=$shareid' class='delete'><i class='fa fa-trash'></i></a>\n";
            print "</td>\n";
            print "</tr>\n";
        }
    }
    print "</table>";
    print "</div><!-- close left col-->";
    print "<div class='col-md-12 col-xs-12'>";
    print "<div class='row'>";
    print "<div class='col-sm-6 col-xs-6'>";
    print "<div class='form-horizontal' style='font-weight:bold;font-size:14px;border-bottom:thin solid black;padding-bottom:2px;margin-bottom:10px;'>Book this insert into a new publication schedule</div>";
    $pressruns[0] = 'Please select';

    // use this when editing an existing insert
    if ($_GET['schedid'] != 0 && $_GET['subaction'] == 'edit')
    {
        //editing an existing schedule!
        $schedID = intval($_GET['schedid']);
        $sql = "SELECT * FROM inserts_schedule WHERE id = $schedID";
        $dbSchedule = dbselectsingle($sql);
        $schedule = $dbSchedule['data'];
        $pubID = $schedule['pub_id'];
        $pressrunID = $schedule['pressrun_id'];
        $insertCount = $schedule['insert_quantity'];
        $insertDate = $schedule['insert_date'];

        //get pressruns for this pub
        $sql = "SELECT id, run_name FROM publications_runs WHERE pub_id = $pubID AND display = 1 ORDER BY run_name";
        $dbRuns = dbselectmulti($sql);
        if ($dbRuns['numrows'] > 0)
            foreach ($dbRuns['data'] as $run)
                $pressruns[$run['id']] = stripslashes($run['run_name']);
    }
    else
    {
        $schedID = 0;
        $pubID = 0;
        $pressrunID = 0;
        $pressruns = array();
        $insertCount = 0;
        $insertDate = date("Y-m-d", strtotime("+1 week"));
    }

    make_select('pub_id', $pubs[$pubID], $pubs, 'Insert Publication', '', '', false, "getRunsAndZones()");
    make_select('pressrun_id', $pressruns[$pressrunID], $pressruns, 'Press Run Name');
    make_date('insertDate', $insertDate, 'Insertion Date', '');
    make_number('insertCount', $insertCount, 'Insertion Quantity', '');
    print "<input type='hidden' id='editScheduleID' name='editScheduleID' value='$schedID' />\n";
    print "<input type='button' onclick='saveSchedule();' class='btn btn-success pull-right' value='Save Schedule' />\n";
    print "</div><!-- close right col-->\n";
    print "<div id='zone_holder' class='col-sm-6 col-xs-6 form-horizontal'>\n";
    /* if we are editing an existing schedule, then we need to do the normal stuff to fetch zones and checks */
    print "<div id='zoningTabs'>
                            <!-- Nav tabs -->
                            <ul class='nav nav-tabs' role='tablist'>
                            <li role='presentation' class='active'><a href='#zones_list' aria-controls='zones_list' role='tab' data-toggle='tab'>Zones</a></li>
                            <li role='presentation'><a href='#trucks' aria-controls='trucks' role='tab' data-toggle='tab'>Trucks</a></li>   
                            </ul>

                            <!-- Tab panes -->
                            <div class='tab-content'>";
    print '<div role="tabpanel" class="tab-pane active" id="zones_list">';

    // Check if editing an existing schedule
    $schedID = intval($_GET['schedid']);
    // Get a list of the zones available for this publication
    $sql = "SELECT publications_insertzones.* FROM publications_insertzones, inserts_schedule
        WHERE publications_insertzones.pub_id = inserts_schedule.pub_id
        AND inserts_schedule.id = $schedID
        AND B.insert_id = $insertid";
    $dbZones = dbselectmulti($sql);
    $editingExistingInsert = $_GET['schedid'] != 0 && $_GET['subaction'] == 'edit';
    if ($editingExistingInsert)
        outputZonesToList($insertid);

    print "</div><div role='tabpanel' class='tab-pane' id='trucks'><div class='row' id='trucks_list'>";

    if ($editingExistingInsert)
    {
        if ($dbZones['numrows'] > 0)
        {
            foreach ($dbZones['data'] as $zone)
            {
                $dbTrucks = dbselectmulti("SELECT * FROM publications_inserttrucks WHERE zone_id = $zone[id] ORDER BY truck_order ASC");

                if ($dbTrucks['numrows'] <= 0)
                    continue;

                print "<div class='col-sm-3' id='truck_list_$zone[id]'>";
                foreach ($dbTrucks['data'] as $truck)
                {
                    if ($insertid != '')
                    {
                        $sql = "SELECT * FROM inserts_zoning_trucks WHERE schedule_id=$schedID
                            AND insert_id = $insertid AND zone_id = $zone[id] AND truck_id = $truck[id]";
                        $dbCheck = dbselectsingle($sql);
                        $checked = '';
                        if ($dbCheck['numrows'] > 0)
                            $checked = 'checked';
                    }
                    print "<div class='checkbox'><label><input class='zone_$zone[id]' type=checkbox id='truck_$zone[id]_$truck[id]' name='truck_$zone[id]_$truck[id]'  $checked/> $zone[zone_name] | $truck[truck_name]</label></div>";
                }
                print "</div>\n";
            }
        }
        else
            print "No zones defined for this publication.";
    }

    print "</div></div></div></div></div><!--closes the zoneholder div-->";

    print "</div></div></div> <!-- closing row -->\n";

    print "</div><!-- close schedule tab -->\n";

    print "<div id='insertDetails' role='tabpanel' class='tab-pane" . ($activeTab == 'insertDetails' ? ' active' : '') . "'>\n";
    print "<div class='row'>\n";
    print "<div class='col-md-9 col-xs-12'>\n";
    make_number('pieceWeight', $pieceWeight, 'Piece Weight', 'Weight of single piece?');
    make_checkbox('singleSheet', $singleSheet, 'Single sheet?', 'Check if product is a single sheet');
    make_checkbox('slickSheet', $slickSheet, 'Slick insert?', 'Check if product is slick');
    print "</div>\n";
    print "<div class='col-xs-12 col-md-3'>\n";
    print "</div>\n";
    print "</div><!-- closing row-->\n";
    print "</div><!-- closing details tab -->\n";

    print "<div id='shipping' role='tabpanel' class='tab-pane" . ($activeTab == 'shipping' ? ' active' : '') . "'>\n";
    make_number('receiveWeight', $receiveWeight, 'Receive Weight', 'Total weight?', 10);

    make_text('tagColor', $tagColor, 'Tag Color', 'Color of pallet tag');
    if ($GLOBALS['insertUseLocation'])
    {
        $slocations = buildLocations('inserts');
        make_select('storageLocation', $slocations[$storageLocation], $slocations, 'Storage Location', 'Storage location code');
    }
    make_text('shipper', $shipper, 'Shipper', 'Who delivered it?', 50);
    make_text('printer', $printer, 'Printer', 'Who printed it?', 50);
    make_select('shipType', $shiptypes[$shipType], $shiptypes, 'Ship type', 'How did they arrive?');
    make_number('shipQuantity', $shipQuantity, 'Ship quantity', 'How many pallets/boxes?');
    make_select('damaged', $damage, 'Damage', "Check if the inserts arrived damaged");
    make_textarea('insertDamage', $insertDamage, 'Insert Damage', 'Enter a description of any damage.');
    print "</div><!-- closing shipping tab-->";

    print "</div><!--closes tabs -->";

    print "</div><!-- closing outer tab wrapper -->";

    make_submit('submit', $button);
    make_hidden('insertid', $insertid);
    print "</form>\n";

    $scripts = 
        "function getRunsAndZones()
        {
            \$.ajax({
            url: \"includes/ajax_handlers/fetchRuns.php\",
            data: {pub_id: \$('#pub_id').val(), zero: 1},
            type:  'post',
            dataType: 'json',
            success: function (j) {
                var options = [], i = 0, o = null;
                for (i = 0; i < j.length; i++) {
                    var options = '';
                    for (var i = 0; i < j.length; i++) {
                        options += '<option value=\"' + j[i].id + '\">' + j[i].label + '</option>';
                    }
                    \$(\"#pressrun_id\").html(options);
                }

                },
                error: function (xhr, desc, er) {}
            });
            
            \$.ajax({
                url: 'includes/ajax_handlers/fetchInsertZones.php',
                type: 'POST',
                data: {pub_id: \$('#pub_id').val(), type: 'new'},
                dataType: 'json',
                success: function(response){
                    \$('#zone_holder').html('');
                    \$.each(response.zones, function(index,zone){
                        \$('#zone_holder').append(zone);
                    })
                },
                success: function(response){
                    //console.log(response);
                    \$.each(response.zones, function(index,zone){
                        \$('#zones_list').append(zone);
                    });
                    \$.each(response.zone_blocks, function(index,zone_id){
                        \$('#trucks_list').append(\"<div class='col-sm-3' id='truck_list_\"+zone_id+\"'></div>\");
                        \$.each(response.trucks, function(i, zone_truck){
                            if(i==zone_id)
                            {
                                \$('#truck_list_'+i).append(zone_truck); 
                            }
                        }) 
                    }); 
                },
                error: function (xhr, desc, er) {
                    bootbox.alert({
                        title: 'An error occurred',
                        message: xhr.status+'<br />'+desc 
                    });
                    var badresponse = {status: 404};
                    return false
                }
            });
        }
        function handleZoningUpdate(response)
        {
            console.log(response);
            \$('#zoningModal').modal('hide');
        }
        function toggleTruckChecks(id)
        {
            //get current state of this zone
            var zoneCheck = \$('#zone_'+id).prop('checked');
            
            //update all trucks with matching zone class
            \$('.zone_'+id).prop('checked',zoneCheck);   
        }
        function saveSchedule()
        {
            var schedID = \$('#editScheduleID').val();
            var insertID = \$('#insertid').val();
            var pubID = \$('#pub_id').val();
            var pressrunID = \$('#pressrun_id').val();
            var insertDate = \$('#insertDate').val();
            var insertCount = \$('#insertCount').val();
            var zones = \$('#zone_holder input:checkbox').serialize();
            var dataObj = {schedule_id: schedID, insert_id: insertID, pub_id: pubID, pressrun_id: pressrunID, insert_date: insertDate, insert_count: insertCount, zones: zones};
            
            if(pubID != 0 && insertDate != '')
            {
                \$.ajax({
                    url: 'includes/ajax_handlers/updateInsertSchedule.php',
                    type: 'POST',
                    data: dataObj,
                    dataType: 'json',
                    success: function(response){
                        console.log(response);
                        if(response.status=='success')
                        {
                            //remove existing row from schedule
                            \$('#sched-'+response.schedule_id).remove();
                            \$('#zone_holder').html('');
                            \$('#editScheduleID').val('0');
                            \$('#pub_id').val('0');
                            \$('#pressrun_id').val('0');
                            \$('#insertDate').val('');
                            \$('#insertCount').val('0');
                            \$('#scheduleTable').append(response.newRow);
                            
                        } else {
                            bootbox.alert({
                                title: 'An error occurred',
                                message: response.message 
                            });
                        }
                    },
                    error: function (xhr, desc, er) {
                        bootbox.alert({
                            title: 'An error occurred',
                            message: xhr.status+'<br />'+desc 
                        });
                        var badresponse = {status: 404};
                        return false
                    }
                });
            }
        }";
    $GLOBALS['scripts'][] = $scripts;
}
function delete_insert(): void
{
    $insertID = intval($_GET['insertid']);
    $deletionResult = inserts::delete($insertID);

    if ($deletionResult[0] === "Error")
        setUserMessage('There was a problem deleting the insert.<br>', 'error');
    else
        setUserMessage('Insert has been successfully deleted.', 'success');

    redirect("?action=list");
}
/** Lists inserts from the database. */
function displayInsertsList(): void
{
    global $pubs, $advertisers, $wePrintAdvertiserID, $Page, $User;

    $dbRuns = dbselectmulti("SELECT id, run_name FROM publications_runs");
    $runs[0] = 'None';
    if ($dbRuns['numrows'] > 0)
        foreach ($dbRuns['data'] as $run)
            $runs[$run['id']] = stripslashes($run['run_name']);

    // Construct search query.
    //we'll search by advertiser, received date, insert date, status, and pub
    $istatuses = array("Please choose", "unscheduled", "missing", "received", "confirmed", "scheduled", "planned", "inserted");
    $advertisers[0] = 'Please choose';
    if ($_POST['search'] == 'Search')
    {
        $rdate = '';
        if ($_POST['receive_date'] != '')
            $rdate = "AND receive_date >= '" . $_POST['receive_date'] . "'";

        $dfilter = array();
        $pubid = $_POST['search_pub'];
        $nomatches = false;
        $idate = addslashes($_POST['insert_date']);

        // A query for the insert date and publication was specified
        if ($_POST['insert_date'] != '' && $pubid != 0)
        {
            $sql = "SELECT insert_id FROM inserts_schedule WHERE insert_date = '$idate' AND pub_id = '$pubid'";
            DebugWriter::printDebug("A database query specifying the publish date
                and publication has been run with the following SQL: $sql");
            $dbFilter = dbselectmulti($sql);
            if ($dbFilter['numrows'] > 0)
            {
                foreach ($dbFilter['data'] as $filter)
                {
                    // Skip values of zero as these are errors
                    if ($filter['insert_id'] == 0)
                        continue;

                    $dfilter[] = $filter['insert_id'];
                }
            }

            // This is not set as an else statement because it would then miss cases where all inserted IDs are errors.
            if ($dbFilter['numrows'] <= 0 || count($dfilter) < 1)
                $nomatches = true;
        }
        // Query for the scheduled insert date ONLY was specified
        elseif ($_POST['insert_date'] != '')
        {
            $sql = "SELECT * FROM inserts_schedule WHERE insert_date = '$idate'";
            $dbFilter = dbselectmulti($sql);
            if ($dbFilter['numrows'] > 0)
            {
                foreach ($dbFilter['data'] as $filter)
                {
                    // Skip values of zero as these are errors
                    if ($filter['insert_id'] == 0)
                        continue;

                    $dfilter[] = $filter['insert_id'];
                }
            }

            // This is not set as an else statement because it would then miss cases where all inserted IDs are errors.
            if ($dbFilter['numrows'] <= 0 || count($dfilter) < 1)
                $nomatches = true;
        }
        // Query for the publisher ID ONLY was specified
        elseif ($pubid != 0)
        {
            $sql = "SELECT * FROM inserts_schedule WHERE pub_id = '$pubid'";
            $dbFilter = dbselectmulti($sql);
            if ($dbFilter['numrows'] > 0)
            {
                foreach ($dbFilter['data'] as $filter)
                    if (!in_array($filter['insert_id'], $dfilter))
                        $dfilter[] = $filter['insert_id'];
            }
            else
                $nomatches = true;
        }

        if (count($dfilter) > 0)
        {
            $dfilter = implode(",", $dfilter);
            $ifilter = "AND inserts.id IN ($dfilter)";
        }

        $advertiserid = $_POST['search_advertiser'];
        if ($advertiserid > 1)
            $advertiser = "AND inserts.advertiser_id = '$advertiserid'";
        elseif ($advertiserid == $wePrintAdvertiserID)
            $weprinted = "AND inserts.weprint_id >= 0";

        // Query for "whether this insert was printed or not" was specified
        if (isset($_POST['weprint']) && $_POST['weprint'])
        {
            $weprint = 'checked';
            $weprinted = "AND inserts.weprint_id >= 0";
        }
        else
        {
            $weprint = '';
            $weprinted = '';
        }
        $cnumber = '';
        $cnumbersearch = '';
        // Query for the control number was specified
        if ($_POST['cnumber'] != '')
        {
            $cnumber = $_POST['cnumber'];
            $cnumbersearch = "AND inserts.control_number = '$cnumber'";
        }
        $adnumber = '';
        $adnumbersearch = '';
        // Query for the ad number was specified
        if ($_POST['adnumber'] != '')
        {
            $adnumber = $_POST['adnumber'];
            $adnumbersearch = "AND inserts.ad_number = '$adnumber'";
        }

        $status = $_POST['search_status'];
        switch ($istatuses[$status])
        {
            case "missing":
                $status = "AND received = 0";
                break;

            case "received":
                $status = "AND received = 1";
                break;

            case "confirmed":
                $status = "AND confirmed = 1";
                break;

            case "scheduled":
                $status = "AND scheduled = 1";
                break;

            case "un-scheduled":
                $status = "AND scheduled = 0";
                break;

            case "planned":
                $status = "AND planned = 1";
                break;

            case "inserted":
                $status = "AND inserted = 1";
                break;

            default:
                $status = '';
                break;
        }
    }

    // Display search form
    $search = "<form method=post class='form-horizontal'>\n";
    $search .= "Insert scheduled to publish on:<br />&nbsp;&nbsp;&nbsp;";
    $search .= make_date('insert_date', $idate, '', '', '', '', '', true);
    $search .= "<br />Advertiser:<br>&nbsp;&nbsp;&nbsp;";
    $search .= make_select('search_advertiser', $advertisers[$_POST['search_advertiser']], $advertisers);
    $search .= "<br />Publication:<br>&nbsp;&nbsp;&nbsp;";
    $search .= make_select('search_pub', $pubs[$_POST['search_pub']], $pubs);
    $search .= "<br>Received between now and:<br />&nbsp;&nbsp;&nbsp;";
    $search .= make_date('receive_date', $rdate, '', '', '', '', '', true);
    $search .= "<br />Status: ";
    $search .= make_select('search_status', $istatuses[$_POST['search_status']], $istatuses);
    $search .= "<br /><label for='weprint'> <input type='checkbox' class='checkbox form-control' id='weprint' name='weprint' $weprint /> We printed it</label><br>";
    $search .= "Control #:<br /><input type='text' id='cnumber' name='cnumber' value='$cnumber' /><br>";
    $search .= "Ad #:<br /><input type='text' id='adnumber' name='adnumber' value='$adnumber' /><br>";
    $search .= "<br /><input type=submit name='search' id='search' value='Search' class='btn btn-default'></input>\n";
    $search .= "</form>\n";

    $noQueriesExist = $rdate == '' && $idate == '' && $status == '' && $advertiser == '' && $cnumber == '' && $adnumber == '';
    // Default behavior when no search queries have been made.
    if ($noQueriesExist)
    {
        $rdate = "";
        $status = '';
        $nextWeek = date("Y-m-d", strtotime("+1 week"));
        // Get inserts for the next week to filter against.
        $sql = "SELECT * FROM inserts_schedule WHERE insert_date >= NOW() AND insert_date <= '$nextWeek'";
        $dbFilter = dbselectmulti($sql);
        $dfilter = '';
        if ($dbFilter['numrows'] > 0)
        {
            foreach ($dbFilter['data'] as $filter)
            {
                // Malformed insert ID data in the schedule, therefore skip.
                if ($filter['insert_id'] == 0)
                    continue;

                $dfilter .= $filter['insert_id'] . ",";
            }
            $dfilter = substr($dfilter, 0, strlen($dfilter) - 1);
        }
        $ifilter = "AND inserts.id IN ($dfilter)";
    }

    if ($nomatches)
    {
        print "No matches with those search terms.<br>";
        $sql = "";
    }
    else
    {
        // Search based on the user query
        $sql = "SELECT inserts.*, accounts.account_name FROM inserts, accounts 
            WHERE inserts.advertiser_id = accounts.id
            $rdate $ifilter $advertiser $status $weprinted $cnumbersearch $adnumbersearch 
            ORDER BY account_name LIMIT 200";
    }
    
    if ($_POST)
        $_SESSION['queries']['inserts'] = $sql;
    elseif ($_SESSION['queries']['inserts'] != '')
        $sql = $_SESSION['queries']['inserts'];

    if ($GLOBALS['debug'])
        print
            "<p>
                Listing inserts based on an SQL query of:
                <br>
                <pre><code>$sql;</code></pre>
            </p>";

    $dbInserts['numrows'] = 0;
    // Ensure an SQL query was specified (An empty SQL string indicates no inserts exist for the current user search query)
    if ($sql != "")
        $dbInserts = dbselectmulti($sql);

    $openingPtag = "<p style='color:green;font-weight:bold;'>";
    if ($noQueriesExist)
        print $openingPtag
        . "No search query was specified. Inserts for the next week ONLY have been loaded. "
        . $dbInserts['numrows']
        . " inserts are currently loaded on the webpage.</p>\n";
    // Explain query results
    else
        print $openingPtag . $dbInserts['numrows'] . " inserts were found matching your last search query.</p>\n";
    
    tableStart(
        "<a href='?action=add'>Add insert</a>,<a href='?action=import'>Import Insert Manifest</a>",
        "Advertiser,Schedules,Status",
        10,
        $search
    );

    $mailers = $GLOBALS['mailers'];
    $receiveDialog = new bootstrapDialog('receiveDialog');

    $data['db_field'] = 'insert_details';
    $data['value'] = '';
    $data['label'] = 'Insert Details';
    $receiveDialog->addTextLabel($data);

    $data['db_field'] = 'received';
    $data['value'] = 1;
    $data['label'] = 'Receive';
    $data['explain'] = 'Check to receive';
    $receiveDialog->addCheckbox($data);

    $data['db_field'] = 'receive_by';
    $data['value'] = $mailers[$_SESSION['userid']];
    $data['label'] = 'Received By';
    $data['explain'] = 'Who is receiving';
    $data['options'] = $mailers;
    $receiveDialog->addSelect($data);

    $data['db_field'] = 'receive_count';
    $data['value'] = '0';
    $data['label'] = 'Quantity';
    $data['explain'] = 'Enter total received quantity';
    $receiveDialog->addText($data);

    $data['db_field'] = 'ship_quantity';
    $data['value'] = '0';
    $data['label'] = '# Pallets/ Boxes';
    $data['explain'] = 'Enter number of pallets (or boxes)';
    $receiveDialog->addText($data);

    $data['db_field'] = 'insert_notes';
    $data['value'] = '';
    $data['label'] = 'Notes';
    $data['explain'] = 'Enter any notes';
    $receiveDialog->addTextarea($data);

    $receiveDialog->setHeader('Receive Insert');
    $receiveDialog->setCallback('receiveCallback');
    $receiveDialog->setSource('fetchInsertReceive.php');
    $receiveDialog->setProcessor('updateInsertReceive.php');
    $receiveScript = "function receiveCallback(data)
        {
            if (data.received == 1)
            {
                " . $receiveDialog->getCaller() . ".removeClass('btn-primary').addClass('btn-default').html('Received');
            }
        }";
    $GLOBALS['scripts'][] = $receiveScript;

    if ($dbInserts['numrows'] > 0)
    {
        // Check if user has the override insert receiving permission. If so, individual checks on each insert can be skipped.
        $userHasReceivingOverridePermission = getUserInsertReceivingPermission();
        
        foreach ($dbInserts['data'] as $insert)
        {
            $insertid = $insert['id'];

            if ($insert['weprint_id'] != 0)
            {
                $dbPubname = dbselectsingle("SELECT A.pub_name
                    FROM publications A, jobs B
                    WHERE A.id = B.pub_id
                    AND B.id = $insert[weprint_id]");
                $wepubname = stripslashes($dbPubname['data']['pub_name']);
                $advertisername = "INHOUSE - $wepubname";
            }
            else
                $advertisername = stripslashes($insert['account_name']);

            $tagline = stripslashes($insert['insert_tagline']);

            $receiveLockDays = 7;

            $canReceiveAndConfirm = true;
            if (!$userHasReceivingOverridePermission)
                $canReceiveAndConfirm = canInsertBeReceived($insertid, $receiveLockDays);

            // Insert has been received when the status is anything other than 0.
            if ($insert['received'] != 0)
                $receiveStatus = "<span class='label label-success'>Received</span>";
            // Output HTML button to receive the insert
            else
                $receiveStatus = $receiveDialog->getButton('Receive Now', $insertid, $canReceiveAndConfirm);

            //status section, going from received to inserted
            if ($insert['confirmed'])
            {
                $confirmLabel = "Confirmed";
                $confirmClass = "btn-success";
                $dataConfirm = 1;
            }
            else
            {
                $confirmLabel = "Confirm";
                $confirmClass = "btn-primary";
                $dataConfirm = 0;
            }

            $disabled = "";
            if (!$canReceiveAndConfirm)
                $disabled = "disabled";
            $confirmStatus = "<button id='confirm_$insertid' data-confirmed=$dataConfirm onclick='confirmInsert($insertid)' class='btn $confirmClass' $disabled>$confirmLabel</button>\n";

            if ($insert['planned'])
                $status = 'Planned';

            if ($insert['inserted'])
                $status = 'Inserted';

            if ($insert['insert_notes'] != '')
                $notes = " <a class='insertNotes' href='' title='" . strip_tags($insert['insert_notes']) . "'><i class='fa fa-comments'> </i></a>";
            else
                $notes = "";

            // Generate HTML of insert.
            print "<tr>\n";
            print "<td><a href='?action=edit&insertid=$insertid'>$advertisername</a>";
            print "<br>$tagline<br>Control # " . ($insert['control_number'] == '' ? 'N/A' : $insert['control_number']) . "<br>$notes";
            print "</td>\n";
            print "<td style='width: 40%;'>";
            $sql = "SELECT * FROM inserts_schedule WHERE insert_id = $insertid";
            $dbSchedules = dbselectmulti($sql);
            if ($dbSchedules['numrows'] > 0)
            {
                print "<table class='table table-striped table-bordered table-condensed'>\n";
                print "<thead><tr><th>Pub</th><th>Date</th><th>Quantity</th><th>Actions</th></tr></thead>\n";
                foreach ($dbSchedules['data'] as $sched)
                {
                    print "<tr>";
                    if ($sched['killed'])
                        print "<td style='color:red;text-decoration: line-through'>";
                    else
                        print "<td>";

                    print stripslashes($pubs[$sched['pub_id']]);
                    if ($sched['pressrun_id'] != 0)
                        print "<br>" . stripslashes($runs[$sched['pressrun_id']]);

                    print "</td>\n";
                    print "<td>" . date("m/d/Y", strtotime($sched['insert_date'])) . "</td>\n";;
                    print "<td>" . $sched['insert_quantity'] . "</td>\n";
                    print "<td>
                    <a href='?action=edit&subaction=edit&tab=schedules&insertid=$insertid&schedid=$sched[id]'><i class='fa fa-pencil'></i></a>
                    <a data-toggle='modal' data-target='#zoningModal' data-insertid='$insertid' data-schedid='$sched[id]'><i class='fa fa-location-arrow' aria-hidden='true' style='cursor:pointer;'></i></a>
                    <a href='?action=edit&subaction=delete&tab=schedules&insertid=$insertid&schedid=$sched[id]' class='delete'><i class='fa fa-trash'></i></a></td>";
                    print "</tr>";
                }
                print "</table>\n";
            }
            print "<a href='?action=edit&tab=schedules&insertid=$insertid' style='font-size:10px;'><i class='fa fa-plus'></i><span style='margin-top:-6px;padding-bottom:6px;'> Add another schedule</span></a>";

            print "</td><td>";

            if (!$canReceiveAndConfirm)
                print "<p style=\"font-size: 0.8em\">You do not have permission to change the receiving status of an insert within $receiveLockDays days of the scheduled print date.</p>";
            
            print "<p>$receiveStatus</p><p>$confirmStatus</p></td>";
            print "<td style='width:130px;'>
            <div class='btn-group'>
            <a href='?action=edit&insertid=$insertid' class='btn btn-dark'>Edit Job</a>
            <button type='button' class='btn btn-dark dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>
                <span class='caret'></span>
                <span class='sr-only'>Toggle Dropdown</span>
            </button>
            <ul class='dropdown-menu'>
                <li><a href='?action=schedule&insertid=$insertid'>Schedule Insert</a></li>
                <li><a href='?action=delete&insertid=$insertid' class='delete'><i class='fa fa-trash'></i> Delete</a></li>
            </ul>
            </div>
            </td>";
            print "</tr>\n";
        }
    }

    tableEnd($dbInserts);

    //generate the modal dialog
    $receiveDialog->generate();

    //based on the fact that it's a more dynamic thing, the zoning modal will have it's check boxes loaded via ajax
    ?>
    <!-- Modal -->
    <div class="modal fade" id="zoningModal" tabindex="-1" role="dialog" aria-labelledby="zoningModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="zoningModalLabel">Zoning</h4>
                </div>
                <div class="modal-body" id='zoningContent'>
                    <form id='zoningForm' name='zoningForm' class='form-horizontal'>
                        <div id='zoningTabs'>
                            <!-- Nav tabs -->
                            <ul class="nav nav-tabs" role="tablist">
                                <li role="presentation" class="active"><a href="#zones_list" aria-controls="zones_list" role="tab" data-toggle="tab">Zones</a></li>
                                <li role="presentation"><a href="#trucks" aria-controls="trucks" role="tab" data-toggle="tab">Trucks</a></li>
                            </ul>

                            <!-- Tab panes -->
                            <div class="tab-content">
                                <div role="tabpanel" class="tab-pane active" id="zones_list">

                                </div>
                                <div role="tabpanel" class="tab-pane" id="trucks">
                                    <div class='row' id='trucks_list'>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </form>
                    <input type='hidden' id='sched_id' name='sched_id' value='' />
                    <input type='hidden' id='insert_id' name='insert_id' value='' />

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick='saveZones();'>Save zones</button>
                </div>
            </div>
        </div>
    </div>
    <?php
    $confirmScripts = 
        "function confirmInsert(insertID)
        {
            var confirm = 1;
            if(\$('#confirm_'+insertID).data('confirmed')==1)
            {
                confirm=0;
            }
            var data = {mrecordID: insertID, confirm_by: " . $User->id . ", confirmed: confirm};
            genericAjaxHandler('updateInsertConfirm.php',data,confirmCallback);
        }
        function confirmCallback(data)
        {
            if(data.confirmed==1)
            {
                \$('#confirm_'+data.id).removeClass('btn-primary').addClass('btn-success').html('Confirmed');
            } else {
                \$('#confirm_'+data.id).removeClass('btn-success').addClass('btn-primary').html('Confirm');
            }
            \$('#confirm_'+data.id).data('confirmed',data.confirmed);
        }";
    $Page->addScript($confirmScripts);

    $zoningScript = 
        "\$('#zoningModal').on('show.bs.modal', function (event) {
        \$('#zoningTabs a:first').tab('show');
        var button = \$(event.relatedTarget);
        var insertID = button.data('insertid');
        var schedID = button.data('schedid');
        \$('#sched_id').val(schedID);
        \$('#insert_id').val(insertID);
        var modal =\$(this);
        \$.ajax({
            url: 'includes/ajax_handlers/fetchInsertZones.php',
            type: 'POST',
            data: {insert_id: insertID, sched_id: schedID},
            dataType: 'json',
            success: function(response){
                //console.log(response);
                \$.each(response.zones, function(index,zone){
                    \$('#zones_list').append(zone);
                });
                \$.each(response.zone_blocks, function(index,zone_id){
                    \$('#trucks_list').append(\"<div class='col-sm-3' id='truck_list_\"+zone_id+\"'></div>\");
                    \$.each(response.trucks, function(i, zone_truck){
                            if(i==zone_id)
                            {
                                \$('#truck_list_'+i).append(zone_truck); 
                            }
                    }) 
                });
                
            },
            error: function (xhr, desc, er) {
                bootbox.alert({
                    title: 'An error occurred',
                    message: xhr.status+'<br />'+desc 
                });
                var badresponse = {status: 404};
                return false
            }
        });
        })
    function saveZones()
    {
        var schedID = \$('#sched_id').val();
        var insertID = \$('#insert_id').val();
        var formData = \$('#zoningForm').serialize();
        console.log(formData);
        var dataObj = {schedule_id: schedID, insert_id: insertID, zones: formData};
        genericAjaxHandler('updateInsertZones.php',dataObj,handleZoningUpdate);
    }
    function handleZoningUpdate(response)
    {
        console.log(response);
        \$('#zoningModal').modal('hide');
        
    }
        \$('#zoningModal').on('hidden.bs.modal', function (event) {
            \$('#zones_list').html('');
            \$('#trucks_list').html('');
            \$('#sched_id').val('');
            \$('#insert_id').val('');
        })
        \$('#stable a.insertNotes').live('mouseover', function(event) {
            \$(this).qtip({
                overwrite: false,
                show: {
                event: event.type,
                ready: true
                }   
                }, event); 
        });
        
        function toggleTruckChecks(id)
        {
            //get current state of this zone
            var zoneCheck = \$('#zone_'+id).prop('checked');
            
            //update all trucks with matching zone class
            \$('.zone_'+id).prop('checked',zoneCheck);   
        }";
    $Page->addScript($zoningScript);
}
function save_insert(): void
{
    global $Prefs;

    $insertID = intval($_POST['insertid']);
    $advertiserid = intval($_POST['advertiserid']);
    $insertTagline = addslashes($_POST['insertTagline']);

    $receiveDate = addslashes($_POST['receiveDate']);
    // Replace empty receive date with a database-safe value.
    if ($receiveDate === '')
        $receiveDate = 'NULL';

    $salesperson = addslashes($_POST['salesperson']);
    $shipper = addslashes($_POST['shipper']);
    $printer = addslashes($_POST['printer']);
    $buyCount = addslashes($_POST['buyCount']);

    $controlNumber = addslashes($_POST['controlNumber']);
    $receiveCount = addslashes($_POST['receiveCount']);
    if ($receiveCount == '')
        $receiveCount = 0;

    $receiveWeight = addslashes($_POST['receiveWeight']);
    $pieceWeight = addslashes($_POST['pieceWeight']);

    $size = intval($_POST['productSize']);
    $pages = intval($_POST['productPages']);
    $standardPages = intval($_POST['standardPages']);

    if ($standardPages == '' || $standardPages == 0)
        $standardPages = $pages * $Prefs->insertProductsOptions[$size];

    $stickyNote = 0;
    if ($_POST['stickyNote'])
        $stickyNote = 1;

    $damaged = 0;
    if ($_POST['damaged'])
        $damaged = 1;

    $singleSheet = 0;
    if ($_POST['singleSheet'])
        $singleSheet = 1;

    $slickSheet = 0;
    if ($_POST['slickSheet'])
        $slickSheet = 1;

    $received = 0;
    if (isset($_POST['received']) && $_POST['received'] == 'on')
        $received = 1;

    $keepRemaining = 0;
    if ($_POST['keepRemaining'])
        $keepRemaining = 1;

    $insertDamage = addslashes($_POST['insertDamage']);
    $shipType = addslashes($_POST['shipType']);
    $shipQuantity = addslashes($_POST['shipQuantity']);
    $tagColor = addslashes($_POST['tagColor']);
    $storageLocation = addslashes($_POST['storageLocation']);
    $insertNotes = addslashes($_POST['insertNotes']);
    $insertDescription = addslashes($_POST['insertDescription']);
    $receiveBy = addslashes($_POST['receiveBy']);
    $insertionOrder = addslashes($_POST['insertionOrder']);

    $dbUpdate = dbexecutequery("UPDATE inserts
        SET advertiser_id = '$advertiserid', insert_tagline = '$insertTagline', receive_date = '$receiveDate', 
        shipper = '$shipper', printer = '$printer', buy_count = $buyCount, receive_count = '$receiveCount', 
        receive_weight = '$receiveWeight', piece_weight = '$pieceWeight', ship_type = '$shipType',  
        ship_quantity = $shipQuantity, salesperson = '$salesperson', product_size = '$size', product_pages = '$pages',  
        received = $received, receive_by = '$receiveBy', insertion_order = '$insertionOrder', single_sheet = $singleSheet, 
        slick_sheet = $slickSheet, tag_color = '$tagColor', storage_location = '$storageLocation', damage = '$damaged', 
        insert_notes = '$insertNotes', insert_damage = '$insertDamage', insert_description = '$insertDescription',  
        sticky_note = '$stickyNote', spawned = 0, keep_remaining = '$keepRemaining', standard_pages = '$standardPages', 
        control_number = '$controlNumber', temporary = 0
        WHERE id = $insertID");
    $error = $dbUpdate['error'];

    // Set insert as received when the control number is specified.
    if ($controlNumber != '')
        $dbUpdate = dbexecutequery("UPDATE inserts_received SET received = 1 WHERE control_number = '$controlNumber'");

    if ($error != '')
        setUserMessage("There was a problem saving the insert.<br> $error", 'error');
    else
        setUserMessage('Insert has been successfully saved.', 'success');

    tie_received($controlNumber, $insertID);

    $scheduleFromDatabase = dbselectsingle("SELECT id FROM inserts_schedule WHERE insert_id = $insertID");
    $publicationID = intval($_POST['pub_id']);
    if ($scheduleFromDatabase['numrows'] > 0 && $publicationID > 0)
    {
        save_schedule($insertID);
        return;
    }

    redirect("?action=list");
}
/** Writes schedule information as HTML. */
function schedule(): void
{
    global $pubs;
    $insertid = intval($_GET['insertid']);
    $schedid = intval($_GET['schedid']);

    if ($schedid > 0)
    {
        $dbSchedule = dbselectsingle("SELECT * FROM inserts_schedule WHERE id = $schedid");
        $schedule = $dbSchedule['data'];
        $pubid = $schedule['pub_id'];
        $pressrunid = $schedule['pressrun_id'];
        $runid = $schedule['run_id'];
        $insertDate = $schedule['insert_date'];
        $insertCount = $schedule['insert_quantity'];
        $insertruns = array();
        $insertruns[0] = 'Please choose';
        $runs[0] = "Please choose or leave empty";
        $pressruns[0] = "Please choose or leave empty";
        $runsql = "SELECT id, run_name FROM publications_insertruns WHERE pub_id = $pubid ORDER BY run_name";
        $dbRuns = dbselectmulti($runsql);
        if ($dbRuns['numrows'] > 0)
            foreach ($dbRuns['data'] as $insertrun)
                $runs[$insertrun['id']] = $insertrun['run_name'];

        $pressrunsql = "SELECT id, run_name FROM publications_runs WHERE pub_id = $pubid ORDER BY run_name";
        $dbPressRuns = dbselectmulti($pressrunsql);
        if ($dbPressRuns['numrows'] > 0)
            foreach ($dbPressRuns['data'] as $pressrun)
                $pressruns[$pressrun['id']] = $pressrun['run_name'];
    }
    else
    {
        $pubid = 0;
        $pressrunid = 0;
        $runid = 0;
        $insertDate = date("Y-m-d", strtotime("+1 week"));
        $insertCount = 0;
        $insertruns = array();
        $insertruns[0] = 'Please choose';
    }

    print "<div class='row'>
        <div class='col-xs-12 col-sm-4'>
        <form method=post class='form-horizontal'>\n";
    make_select('pub_id', $pubs[$pubid], $pubs, 'Publication', '', '', false, "getPressAndInsertRuns()");
    make_select('pressrun_id', $pressruns[$pressrunid], $pressruns, 'Press Run Name', 'Select the press run for this insert');
    make_select('run_id', $insertruns[$runid], $insertruns, 'Run Name', 'Select the inserter run for this insert', '', false, "getInsertRunZones()");
    make_date('insertDate', $insertDate, 'Insertion date', 'When does it insert?');
    make_number('insertCount', $insertCount, 'Insert Count', 'How many are we supposed to insert?');
    print "</div>
        <div id='zone_holder' class='col-xs-12 col-sm-8'>\n";
    $dbZones = dbselectmulti("SELECT * FROM publications_insertzones WHERE run_id = $runid");
    if ($dbZones['numrows'] > 0)
    {
        print "<p>Please select zones:</p>";
        print "<input type='checkbox' onclick='toggleCheckBoxes(this.checked,\"insertzones\");'>Select / deselect all zones<br />";
        //we are going to format the zones in two columns to conserve space
        $zcount = $dbZones['numrows'];
        $wrapat = round($zcount / 3);
        $i = 1;
        print "<div style='float: left; width: 150px; margin-left: 4px;'>\n";
        
        $total = 0;
        foreach ($dbZones['data'] as $zone)
        {
            //see if this zone is checked
            $dbCheck = dbselectsingle("SELECT * FROM inserts_zoning WHERE sched_id = $schedid AND zone_id = $zone[id]");
            if ($dbCheck['numrows'] > 0)
            {
                $checked = 'checked';
                $total += $zone['zone_count'];
            }
            else
                $checked = '';

            print "<input rel='$zone[zone_count]' onClick=\"calcInsertZoneTotal('insertzones')\" class='insertzones' type=checkbox id='check_$zone[id]' name='check_$zone[id]' $checked/> $zone[zone_name]<br />";
            if ($i == $wrapat)
            {
                print "</div>\n";
                print "<div style='float:left;width:150px;'>\n";
            }
            $i++;
        }
        print "</div><div class='clear'></div>";
        print "<p><span id='zonetotal' style='font-weight:bold;'>$total</span> total inserts required for selected zones.</p>";
        print "<input type='hidden' id='zoned_total' name='zoned_total' value='$total' />\n";
    }

    print "</div><!--closes the zoneholder div-->\n";

    make_hidden('insertid', $insertid);
    make_hidden('schedid', $schedid);
    make_submit('submit', 'Schedule Insert');
    print "</form>\n";
}
function save_schedule($insertID = 0): void
{
    global $User;

    if ($insertID == 0)
        $insertID = intval($_POST['insertid']);

    $scheduleID = intval($_POST['schedid']);
    // If no schedule ID has been posted, check if one exists in the database for this insert.
    if ($scheduleID == 0)
    {
        $scheduleFromDatabase = dbselectsingle("SELECT id FROM inserts_schedule WHERE insert_id = '$insertID'");
        $scheduleID = $scheduleFromDatabase['data']['id'];
    }
    $publicationID = intval($_POST['pub_id']);
    $runid = intval($_POST['run_id']);
    $pressrunid = intval($_POST['pressrun_id']);
    $insertDate = addslashes($_POST['insertDate']);
    $insertCount = intval($_POST['insertCount']);

    if ($scheduleID == 0)
    {
        $dbInsert = dbinsertquery("INSERT INTO inserts_schedule (pub_id, run_id, pressrun_id, insert_id, insert_date, insert_quantity)
            VALUES ('$publicationID', '$runid', '$pressrunid', '$insertID', '$insertDate', '$insertCount')");
        $scheduleID = $dbInsert['insertid'];
        $error = $dbInsert['error'];
    }
    else
    {
        $dbUpdate = dbexecutequery("UPDATE inserts_schedule
            SET pub_id = $publicationID,
            run_id = '$runid',
            pressrun_id = '$pressrunid',
            insert_date = '$insertDate',
            insert_quantity = '$insertCount'
            WHERE id = $scheduleID");
        $error = $dbUpdate['error'];
        outputZonesToDatabase($insertID, $scheduleID);
    }

    dbexecutequery("UPDATE inserts
        SET scheduled = 1, scheduled_by = '$User->id', scheduled_datetime = '" . date("Y-m-d H:i") . "'
        WHERE id = $insertID");

    if ($error != '')
    {
        setUserMessage('There was a problem saving the insert schedule.<br>' . $error, 'error');
        return;
    }

    $zoneids = "";
    foreach ($_POST as $key)
    {
        if (substr($key, 0, 6) == 'check_')
        {
            $zid = str_replace("check_", "", $key);
            //look up the quantity needed
            $sql = "SELECT zone_count FROM publications_insertzones WHERE id = $zid";
            $dbCount = dbselectsingle($sql);
            if ($dbCount['error'] == '')
                $zonecount = $dbCount['data']['zone_count'];
            else
                $zonecount = 0;

            $zoneids .= "('$scheduleID', '$insertID','$zid','$zonecount'),";
        }
    }
    $zoneids = substr($zoneids, 0, strlen($zoneids) - 1);
    // Delete existing zone records then add new ones
    if ($zoneids != '')
    {
        $dbDelete = dbexecutequery("DELETE FROM inserts_zoning WHERE sched_id = $scheduleID");
        $error = $dbDelete['error'];
        $dbInsert = dbinsertquery("INSERT INTO inserts_zoning (sched_id, insert_id, zone_id, zone_count) VALUES $zoneids");
        $error .= $dbInsert['error'];
    }
    if ($error == '')
        setUserMessage('Insert has been successfully scheduled.', 'success');
    else
        setUserMessage("There was a problem saving the insert schedule.<br> $error", 'error');

    redirect("?action=list");
}
function delete_schedule($src = 'list'): void
{
    $insertID = intval($_GET['insertid']);
    $scheduleID = intval($_GET['schedid']);

    dbexecutequery("UPDATE inserts_schedule SET killed = 1 WHERE id = $scheduleID");
    dbexecutequery("UPDATE inserts SET confirmed = 0 WHERE id = $insertID");
    dbexecutequery("DELETE FROM jobs_packages_inserts WHERE insert_id = $insertID");

    setUserMessage("The insert schedule has been killed. Please re-schedule in your order entry system.");

    if ($src == 'list')
        redirect("?action=list");
}
/** Outputs zone information as entered by the user to the database.
 * @param int $insertID  ID of the insert in the database.
 * @param int $scheduleID  ID of the insert schedule to associate this zoning information with. */
function outputZonesToDatabase($insertID, $scheduleID): void
{
    // Get all zones from POST
    $zones = [];
    foreach ($_POST as $key => $value)
    {
        if (substr($key, 0, 5) == "zone_" && $value == "on")
        {
            $zoneID = substr($key, 5);
            $zones[] = $zoneID;
        }
    }

    dbexecutequery("DELETE FROM inserts_zoning
            WHERE schedule_id = $scheduleID
            AND insert_id = $insertID");

    foreach ($zones as $zoneID)
        dbinsertquery("INSERT INTO inserts_zoning (schedule_id, insert_id, zone_id)
            VALUES ('$scheduleID', '$insertID', '$zoneID')");
}
/** Outputs zone information and which zones the insert belongs to as a list of checkboxes.
 * @param int $insertID  ID of the insert in the database to get the zone information for. */
function outputZonesToList($insertID): void
{
    $scheduleIDFromDatabase = dbselectsingle("SELECT id FROM inserts_schedule WHERE insert_id = $insertID");
    if ($scheduleIDFromDatabase['numrows'] <= 0)
        return;

    $scheduleID = $scheduleIDFromDatabase['data']['id'];
    // Get a list of the zones available for this publication
    $dbZones = dbselectmulti("SELECT publications_insertzones.* FROM publications_insertzones, inserts_schedule
        WHERE publications_insertzones.pub_id = inserts_schedule.pub_id
        AND inserts_schedule.id = $scheduleID
        AND insert_id = $insertID");
    
    if ($dbZones['numrows'] <= 0)
    {
        // To-do: This continually prints each time a publication is changed.
        // Change to clear it each time first so it doesn't have a stack of conflicting results.
        print "No zones defined for this publication.";
        return;
    }
    ?>
    <script type='text/javascript'>
    // To-do: Change this to an imported external script.
    var unzonedCheckbox;
    var zoneCheckboxes = [];


    window.onload = function()
    {
        unzonedCheckbox = document.getElementById("unzoned");
    }
    /** Pushes the specified checkbox to the zoneCheckboxes array.
     * @param {HTMLInputElement} htmlID  HTML ID of the zone checkbox. */
    function addZoneCheckbox(htmlID)
    {
        zoneCheckboxes.push(htmlID);
    }
    /** Called when any of the Zone checkboxes (excluding the Unzoned checkbox) are clicked.
     * @param {number} zoneID  Database ID of the zone checkbox being clicked. */
    function onZoneCheckboxClick(zoneID)
    {
        toggleTruckChecks(zoneID);
        unzonedCheckbox.checked = false;
    }
    /** When any Zone checkbox is checked, toggles the Unzoned checkbox off.
     * When the Unzoned checkbox is checked, toggles all Zone checkboxes off. */
    function toggleZonesCheckOnUnzonedChecked()
    {
        if (unzonedCheckbox.checked)
            for (var i = 0; i < zoneCheckboxes.length; i++)
                zoneCheckboxes[i].checked = false;
    }
    </script>
    <?php
    /* Check state to set the Unzoned/Full Run checkbox. This should be checked when no zones are set on this insert,
     * and unchecked when any zone is set. */
    $unzonedChecked = "checked";
    foreach ($dbZones['data'] as $zone)
    {
        // Get checked status
        if ($insertID != '')
        {
            $sql = "SELECT * FROM inserts_zoning
                WHERE schedule_id = $scheduleID
                AND insert_id = $insertID 
                AND zone_id = $zone[id]";
            $dbCheck = dbselectsingle($sql);
            if ($dbCheck['numrows'] > 0)
            {
                $unzonedChecked = "";
                $checked = 'checked';
            }
            else
                $checked = '';
        }
        $htmlID = "zone_" . $zone['id'];
        print "<div class='checkbox'><label><input type=checkbox id='$htmlID' name='$htmlID' $checked onclick='onZoneCheckboxClick($zone[id]);'/> $zone[zone_name]</label></div>";
        print "<script type='text/javascript'>addZoneCheckbox($htmlID);</script>";
    }
    print "<div class='checkbox'><label><input type=checkbox id='unzoned' $unzonedChecked onclick='toggleZonesCheckOnUnzonedChecked();'/> Full Run (Unzoned)</label></div>";
}
/** Gets the current user's permission for receiving inserts.
 * @return bool  True when the user has the appropriate permissions */
function getUserInsertReceivingPermission(): bool
{
    // To-do: When this gets changed to OOP this can run once at the start for significantly better performance.
    $permissionsFromDatabase = dbselectmulti("SELECT permissionID 
        FROM user_permissions 
        WHERE user_id = {$_SESSION['userid']}
        AND value = 1");
    
    // End if no results were returned from the database.
    if ($permissionsFromDatabase['numrows'] < 1)
        return false;

    $insertReceiverPermissionID = 47;
    foreach ($permissionsFromDatabase['data'] as $result)
        if ($result['permissionID'] == $insertReceiverPermissionID)
            return true;

    return false;
}
/** @param string $printDate  Scheduled print date to calculate against.
 * @return int Days between the current date and the scheduled print date for the insert as an integer. */
function getDaysUntilPrintDate($printDate): int
{
    $currentDate = new DateTime();
    /* Convert the print date to a DateTime object.
     * Note that the parameter requires a string, as opposed to directly requiring a DateTime object.
     * This is to make it easier to immediately call the function and pass the data returned from the database. */
    $printDateFormatted = new DateTime($printDate);

    $timeUntilPrint = date_diff($currentDate, $printDateFormatted);
    return $timeUntilPrint->format("%a");
}
/** @param int|string $insertID  ID of the insert in the database to check the receiving status of.
 * @param int $receiveLockDays  Prevents receiving and confirming inserts when the scheduled print date is less days away than this amount.
 * @return bool True when the insert can be received and confirmed
 * based on the current user's permissions and the days until the scheduled print date for the insert specified. */
function canInsertBeReceived($insertID, $receiveLockDays): bool
{
    // Immediately return true when the user possesses the override permission.
    if (getUserInsertReceivingPermission())
        return true;

    
    // Get the scheduled print date associated with this insert
    $insertScheduleFromDatabase = dbselectmulti("SELECT insert_date FROM inserts_schedule WHERE insert_id = $insertID");
    
    // Allow receiving and confirming if no schedule can be found for this insert.
    if ($insertScheduleFromDatabase['numrows'] < 1)
        return true;

    $printDate = $insertScheduleFromDatabase['data'][0]['insert_date'];
    return getDaysUntilPrintDate($printDate) >= $receiveLockDays;
}

$Page->footer();
?>

<script>
    // To-do: Move this to an external file and only load it when editing an insert.

    // Reset all fields related to the insert being received if the user unchecks (un-receives) the insert.
    $('#received').click(function(){
        if (!$('#received').is(':checked'))
        {
            $('#receiveBy').val(null);
            $('#receiveCount').val(null);
            $('#receiveDate').val(null);
        }
    });
</script>
