$versions{'order_logs_textfiles.pl'} = '06.6.00.0001';

# Contains all sub routines (functions) for managing text-based flatfile (CSV / TSV)
# order log files for the store manager areas.

#######################################################################
#
# AgoraCart and all associated files, except where noted, are
# Copyright 2001 to Present jointly by K-Factor Technologies, Inc.
# and by C E Mayo (aka Mister Ed) at AgoraCart.com & K-Factor.net
#
# This file and related program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# This copyright notice may not be removed or altered in any way.
#
#######################################################################

$scm_orderdata_ext  = '-orderdata2';
$scm_monthyearmasterlog_name = '_MasterOrderLog.log2';
$scm_monthyearindexlog_name  = '_indexOrderLog.log2';
$scm_productlog_name   = '_productSalesLog.prd2';
$scm_order_report_string = q{};
$sc_avalara_logging_string = '';
$avalara_cancel_error_message = '';
$avalara_cancel_response = '';

{
    local ($modname) = 'order_log_management';
    register_extension( $modname, 'Order Log Management', $versions{$modname} );

    register_menu(
        'select_individual_order_screen',
        'select_individual_order_screen',
        $modname, 'View Individual Order'
    );
    register_menu(
        'select_orders_by_date_range_screen',
        'select_orders_by_date_range_screen',
        $modname, 'View Orders by Date Range'
    );
    add_ordermanage_settings_choice(
        'View Orders - by Date Range',
        ' View Orders - by Date Range ',
        'select_orders_by_date_range_screen'
    );
    register_menu( 'CompileOrdersByDateRange',
        'compile_Orders_by_date_range_output',
        $modname, 'Create Order List for a Date Range' );
    register_menu(
        'display_productsales_snapshot_screen',
        'display_productsales_snapshot_screen',
        $modname, 'Product Sales Snapshot'
    );
    add_ordermanage_settings_choice(
        'Product Sales Snapshot',
        ' Product Sales Snapshot ',
        'display_productsales_snapshot_screen'
    );
    add_performance_metrics_choice(
        'Product Sales Snapshot',
        ' Product Sales Snapshot ',
        'display_productsales_snapshot_screen'
    );
    register_menu( 'archive_order_from_new_order_log', 'archive_order_from_new_order_log',
        $modname, 'Archive (Remove) Order from New Orders Log' );
    register_menu( 'select_delete_order_screen', 'select_delete_order_screen',
        $modname, 'Remove or Delete Order or log entry' );
    add_ordermanage_settings_choice(
        'Remove or Delete Order or log entry',
        ' Remove Order Files / Log Entry ',
        'select_delete_order_screen'
    );
    register_menu(
        'display_sales_snapshot_selection_screen',
        'display_sales_snapshot_selection_screen',
        $modname, 'Display Sales Snapshot Report Selection'
    );
    if ($sc_shall_i_log_accesses =~ /yes/i) {
        register_menu(
            'visitor_access_display',
            'visitor_access_display',
            $modname, 'Display Visitor Access Logs'
        );
    }
    add_ordermanage_settings_choice(
        'Sales Snapshot Report',
        ' Sales Snapshot Report ',
        'display_sales_snapshot_selection_screen'
    );
    add_performance_metrics_choice(
        'Sales Snapshot Report',
        ' Sales Snapshot Report ',
        'display_sales_snapshot_selection_screen'
    );
    register_menu(
    'CompileOrderPerformanceSnapshot', 'compile_sales_snapshot_information',
    $modname,  'Create and Display Sales Snapshot Report'
    );
}
register_menu( 'viewertrigger', 'select_individual_order_screen',
    $modname, 'viewertrigger' );
register_menu(
    'invoiceviewertrigger', 'print_order_invoice',
    $modname, 'invoiceviewertrigger'
);
register_menu( 'packingviewertrigger', 'print_order_packingslip', $modname,
    "packingviewertrigger" );
register_menu( 'deleteviewertrigger', 'select_delete_order_screen', $modname,
    'deleteviewertrigger' );
register_menu( 'OpenIndividualOrder', 'select_individual_order_screen',
    $modname, 'View Order builder' );
register_menu( 'UpdateIndividualOrder', 'write_individual_Order_information',
    $modname, 'Write Order updates' );
register_menu(
    'ViewProductSnapshot', 'display_productsales_snapshot_screen',
    $modname,  'Product Sales Snapshot - New Lookup'
);
register_menu( 'DeleteIndividualOrder', 'delete_Order_or_Order_Log', $modname,
    'Delete Order files or sales logs routines' );

if ( $sc_avalara_enabled eq 'yes' ) {
    register_menu( 'avataxcanceltrigger', "select_cancel_avatax_screen",
        $modname, "avataxcanceltrigger" );
    register_menu( 'CancelAvaTaxOrder', 'cancel_individual_avatax_order',
        $modname,  'Cancel an Individual AvaTax Order/Amount' );

    %avalara_response;
}

#######################################################################

sub display_order_log {
    local ($errs) = q{};
    my ($lines) = 0;
    local ($logfile) = "$sc_logs_dir/$sc_order_log_name";
    my ( $year, $month, $day, $stuff, $order_filename, $junk2, $Location, $sorry_thingy );
    my $counter = 0;
    my (%orderLoggingHash);

    print &$manager_page_header( 'Display Order Log', '', '', '' );

    print qq~
<div class='row'>
    <br>
    <h1 class='mgr-page-title'>New Orders Overview</h1>
    <p><br></p>
    <p class="well">This log contains the newest orders received by your store. It is meant to be a temporary log. When orders are completed, you should remove them from this log. You will still be able to retrieve the orders by number, date, month, etc in other screens.</p>
    <p><br></p>
</div>
<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered"><tr>
<td bgcolor="#FFCC00">&nbsp;</td>
<td align=center bgcolor="#FFCC00"><b>Order Status</b></td>
<td align=center bgcolor="#FFCC00"><b>Order Date</b></td>
<td align=center bgcolor="#FFCC00"><b>Invoice #</b></td>
<td align=center bgcolor="#FFCC00"><b>Customer Name</b></td>
<td align=center bgcolor="#FFCC00"><b>Order Total</b></td>
<td bgcolor="#FFCC00">&nbsp;</td>
</tr>
~;

    get_file_lock("$logfile.lockfile");
    open( LOGFILE, "$logfile" )
      || print
"<tr><td colspan=9 align=center>Sorry, Cannot Find Order Log File</td></tr>\n";
    while (<LOGFILE>) {

        (
            $year,
            $month,
            $day,
            $orderLoggingHash{'cart_invoiceNumber'},
            $orderLoggingHash{'cart_and_order_id'},
            $orderLoggingHash{'orderStatus'},
            $orderLoggingHash{'firstName'},
            $orderLoggingHash{'lastName'},
            $orderLoggingHash{'fullName'},
            $orderLoggingHash{'companyName'},
            $orderLoggingHash{'emailAddress'},
            $orderLoggingHash{'orderFromState'},
            $orderLoggingHash{'orderFromPostal'},
            $orderLoggingHash{'orderFromCountry'},
            $orderLoggingHash{'shipMethod'},
            $orderLoggingHash{'shippingTotal'},
            $orderLoggingHash{'salesTax'},
            $orderLoggingHash{'tax1'},
            $orderLoggingHash{'tax2'},
            $orderLoggingHash{'tax3'},
            $orderLoggingHash{'discounts'},
            $orderLoggingHash{'COGSitem'},
            $orderLoggingHash{'subTotal'},
            $orderLoggingHash{'orderTotal'},
            $orderLoggingHash{'affiliateTotal'},
            $orderLoggingHash{'affiliateID'},
            $orderLoggingHash{'affiliateMisc'},
            $orderLoggingHash{'GatewayUsed'},
            $orderLoggingHash{'buySafe'}
        ) = split( /\t/, $_ );

        $counter++;

        $orderLoggingHash{'orderTotal'} =
          format_pricemgr( $orderLoggingHash{'orderTotal'} );

        if ( ( $orderLoggingHash{'cart_invoiceNumber'} eq '' ) && ( $_ eq '' ) ) {
            print
"<tr><td colspan=9 align=center>Sorry, No Orders</td></tr>\n";
            $sorry_thingy = 'stop';
        }
################ edit here ################
        # need to advance number.
        #
        my $buysafe_display = q{};
        if (
            (
                   ( $orderLoggingHash{'GatewayUsed'} =~ /Offline/i )
                || ( $orderLoggingHash{'GatewayUsed'} =~ /paypal standard/i )
            )
            && ( $sc_buySafe_is_enabled =~ /yes/ )
            && ( $orderLoggingHash{'buySafe'} > 0 )
          )
        {

# if (($sc_buySafe_is_enabled =~ /yes/) && ($orderLoggingHash{'buySafe'} > 0)) {
            $buysafe_display =
qq~<a href="manager.cgi?mgr_seshun=$mgr_seshun&buysafecanceltrigger=yes&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&invNumber=$orderLoggingHash{'cart_invoiceNumber'}&buyMonth=$month&buyYear=$year">Cancel buySAFE Bond</a><br>~;
        }
################ edit here ################
        if ( $sorry_thingy ne 'stop' ) {
            print qq~<tr>
<td align=center><a href="manager.cgi?mgr_seshun=$mgr_seshun&archive_order_from_new_order_log=archive_order_from_new_order_log&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}" target="_new"><i class="fa fa-archive fa-2x" data-toggle="tooltip" data-placement="right" title="Archive this order: removes from New Order log only" aria-hidden="true"></i></a></td>
<td align=center>$orderLoggingHash{'orderStatus'}</td>
<td align=center>$month, $day, $year</td>
<td align=center>$orderLoggingHash{'cart_invoiceNumber'}</td>
~;

            if ( $orderLoggingHash{'lastName'} ) {
                print qq~
<td  align=center>$orderLoggingHash{'firstName'} $orderLoggingHash{'lastName'}</td>
~;
            }
            else {
                print qq~
<td align=center>$orderLoggingHash{'fullName'}</td>
~;
            }

            $order_filename =
                "$scm_order_logpath/$orderLoggingHash{'cart_invoiceNumber'}" . '-'
              . "$orderLoggingHash{'cart_and_order_id'}";
            my $mgr_avalara_string = '';
            if ( ( $sc_avalara_enabled eq 'yes' ) && ( $sc_avalara_tax_enable eq 'yes' ) ) {
                $mgr_avalara_string = qq|<a href="manager.cgi?mgr_seshun=$mgr_seshun&avataxcanceltrigger=avataxcanceltrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}">Cancel AvaTax</a><br>|;
            }
            #https://png.icons8.com/invoice/p1em/22/000000 invoice icon

            print qq~
<td align=center>$sc_money_symbol $orderLoggingHash{'orderTotal'}</td>
<td valign='middle' align=center>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&viewertrigger=viewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month"><i class="fa fa-pencil-square-o fa-lg" data-toggle="tooltip" data-placement="top" title="View / Edit this order. All customer and order info and cart items presented in form format for viewing and/or editing." aria-hidden="true"></i></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&invoiceviewertrigger=invoiceviewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month" target="_new"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADnSURBVEhL7dQxDgFRFIXhsQVRqARRYwFKW1CqJHYgdAqFNViAml6pnw2IQqVUKEQU/IcpZOZO5j1CInGTL3nJ3HMyJnmCn58cmmh7UkZZc/RgieuLFjDLG9BCF1VPyihbR2Ja0MMSKhg6KkMZZdWRmOdiBS7YGo44RWftTOBcPMIO1syxfhzvO1N4FeutVoY9DtFZO97F+skzwwYq11k73sUf+RSD6OxiDOfiAnroZ9COdp2L08a6zjW8Xazncc7fWDcpbazrnIcyqcVFnKE/ovi1zaKMsuowp4MQ8WucRRll//O1CYIbFUSKVjC73wAAAAAASUVORK5CYII=" class="fa fa-2x" data-toggle="tooltip" data-placement="top" title="View Invoice - view this order in invoice format. This individual order is presented using the your store's invoice template."></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&packingviewertrigger=packingviewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month" target="_new"><i class="fa fa-truck fa-lg" data-toggle="tooltip" data-placement="top" title="View Packing Slip - view this order in invoice format. This individual order is presented using the your store's invoice template."></i></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&deleteviewertrigger=yes&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month"><i class="fa fa-trash-o fa-lg" data-toggle="tooltip" data-placement="top" title="Delete this order. You will be taken to a screen where you can chose to delete the order from various log files as well as option to delete all orders from a specific month or year." aria-hidden="true"></i></a>
<br>$mgr_avalara_string$buysafe_display</td>
</tr>
~;
        }

    }    # End of while LOGFILE
    close(LOGFILE);
    release_file_lock("$logfile.lockfile");
    if ( $counter > 24 ) {
    print qq~<tr>
<td bgcolor="#FFCC00">&nbsp;</td>
<td align=center bgcolor="#FFCC00"><b>Order Status</b></td>
<td align=center bgcolor="#FFCC00"><b>Order Date</b></td>
<td align=center bgcolor="#FFCC00"><b>Invoice #</b></font></td>
<td align=center bgcolor="#FFCC00"><b>Customer Name</b></td>
<td align=center bgcolor="#FFCC00"><b>Order Total</b></td>
<td bgcolor="#FFCC00">&nbsp;</td>
</tr>
</table>
<p><br><br><br><br><br><br></p>
</div>
~;
    }

    print &$manager_page_footer;

}

#######################################################################

sub delete_Order_or_Order_Log {

    #untaint a few thingies
    $in{'cart_invoiceNumber'} =~ /([\w\=\+]+)/;
    my $invoiceNum = "$1";
    $in{'cart_and_order_id'} =~ /([\w\-\=\+\/]+)\.(\w+)/;
    my $cust_id = "$1.$2";
    $in{'month'} =~ /([\w\=\+]+)/;
    my $month = "$1";
    $in{'year'} =~ /([\w\=\+]+)/;
    my $year = "$1";

    my (
        $cart_string, $cart_string_short, $orderLogString, $orderLogString2
    ) = '';
    my ($filename3) = "$sc_order_log_directory_path/$year/$month/$month$year";
    my ($filename8) =
        "$sc_order_log_directory_path/$year/$month/$invoiceNum" . "-"
      . "$cust_id"
      . "$scm_orderdata_ext";
    my ($filename10) = "$sc_order_log_directory_path/$year/$month/";
    my ($filename11) = "$sc_order_log_directory_path/$year/$month$year";
    my ($filename12) = "$sc_order_log_directory_path/$year/";

    if (   ( $in{'deletionType'} =~ /individual/i )
        && ( $in{'deleteIndividualData'} =~ /yes/i ) )
    {
        unlink("$filename8") || print "Error: could not unlink $filename8<br>";
    }

    # delete a specific month in a year
    if (   ( $in{'deletionType'} =~ /month/i )
        && ( $month )
        && ( $year ) )
    {
        if ( -e $filename10 ) {
            opendir( LOGFILEDIR, "$filename10" )
              || print "Cannot open $filename10 Directory<br>";
            my @dirfilenames = readdir(LOGFILEDIR);
            close(LOGFILEDIR);
            foreach $dirfilenames (@dirfilenames) {
                if ( $dirfilenames =~ /[\d]+/ ) {
                    my $tempfilename = "$filename10$dirfilenames";
                    $tempfilename =~ /([\w\=\+\.\-\/]+)/;
                    $tempfilename = "$1";
                    unlink("$tempfilename")
                      || print "Error: could not delete $tempfilename<br>";
                }
            }
            rmdir("$filename10");
        }
    }

    #delete an entire year
    if ( ( $in{'deletionType'} =~ /year/i ) && ( $year ) ) {
        opendir( LOGFILEDIR, "$filename12" )
          || print "Error: Cannot open $filename12 Directory<br>";
        my @dirfilenames = readdir(LOGFILEDIR);
        close(LOGFILEDIR);
        foreach $dirfilenames (@dirfilenames) {
            if ( $dirfilenames =~ /[\w]+/ ) {
                if ( -d "$filename12$dirfilenames" ) {
                    opendir( MONTHLOGFILES, "$filename12$dirfilenames" )
                      || print
"Error: Cannot open $filename12$dirfilenames Directory!<br>";
                    my @permonthfilenames = readdir(MONTHLOGFILES);
                    close(MONTHLOGFILES);
                    foreach $permonthfilenames (@permonthfilenames) {
                        if ( $permonthfilenames =~ /[\w]+/ ) {
                            my $permonthtempfilename =
                              "$filename12$dirfilenames/$permonthfilenames";
                            $permonthtempfilename =~ /([\w\=\+\.\-\/]+)/;
                            $permonthtempfilename = "$1";
                            unlink("$permonthtempfilename");
                        }
                    }
                    $dirfilenames =~ /([\w\=\+\.\-\/]+)/;
                    $dirfilenames = "$1";
                    rmdir("$filename12$dirfilenames");
                }
                else {
                    my $tempfilename = "$filename12$dirfilenames";
                    $tempfilename =~ /([\w\=\+\.\-\/]+)/;
                    $tempfilename = "$1";
                    unlink("$tempfilename")
                      || print "Error: could not unlink $tempfilename<br>";
                }
            }
        }

        rmdir("$filename12");
    }    # end delete entire year

    if (   ( $sc_write_monthly_short_order_logs =~ /yes/i )
        && ( $in{'deletionType'} =~ /individual/i )
        && ( $in{'deleteIndividualOverviewSalesLog'} =~ /yes/i ) )
    {
        $filename4 = "$filename3$scm_monthyearindexlog_name";
        open( ORDERLOG4, "$filename4" );
        while (<ORDERLOG4>) {
            if ( ( $_ =~ /$invoiceNum/ ) && ( $_ =~ /$cust_id/ ) ) {

                # dead space
            }
            else {
                $orderLogString .= $_;
            }
        }
        close(ORDERLOG4);
        get_file_lock("$filename4.lockfile");
        open( ORDERLOG4, ">$filename4" );

        # debug
        # print "$filename4<br>$orderLogString<br><br>";
        print ORDERLOG4 $orderLogString;
        close(ORDERLOG4);
        release_file_lock("$filename4.lockfile");
    }

    # master log - all details for all orders each month of each year
    if (   ( $sc_write_monthly_master_order_logs =~ /yes/i )
        && ( $in{'deletionType'} =~ /individual/i )
        && ( $in{'deleteIndividualMasterSalesLog'} =~ /yes/i ) )
    {
        $filename5 = "$filename11$scm_monthyearmasterlog_name";
        open( ORDERLOG5, "$filename5" );
        while (<ORDERLOG5>) {
            if ( ( $_ =~ /$invoiceNum/ ) && ( $_ =~ /$cust_id/ ) ) {

                # dead space
            }
            else {
                $orderLogString2 .= $_;
            }
        }
        close(ORDERLOG5);
        get_file_lock("$filename5.lockfile");
        open( ORDERLOG5, ">$filename5" );

        # debug
        # print "$filename5<br>$orderLogString2<br><br>";
        print ORDERLOG5 $orderLogString2;
        close(ORDERLOG5);
        release_file_lock("$filename5.lockfile");
    }

    # overview log - new orders
    if (   ( $sc_send_order_to_log =~ /yes/i )
        && ( $in{'deletionType'} =~ /individual/i )
        && ( $in{'deleteIndividualNewOrderLog'} =~ /yes/i ) )
    {
        &delete_order_in_new_order_log($invoiceNum,$cust_id);
    }

    undef(%in);

    if ( ( $sc_avalara_enabled eq 'yes' ) && ( $sc_avalara_tax_enable eq 'yes' ) ) {
        $in{'cart_invoiceNumber'} = $invoiceNum;
        &cancel_individual_avatax_order;
    }
    else {
        &select_delete_order_screen();
    }

}

#######################################################################

sub delete_order_in_new_order_log {

    my $invoiceNum = shift;
    my $cust_id = shift;
    my ( $orderLogLines ) = '';
    my ($file)   = "$sc_logs_dir/$sc_order_log_name";

    open( ORDERLOG, "$file" );
    while (<ORDERLOG>) {
        if ( ( $_ =~ /$invoiceNum/ ) && ( $_ =~ /$cust_id/ ) ) {
            # dead space
        }
        else {
            $orderLogLines .= $_;
        }
    }
    close(ORDERLOG);
    get_file_lock("$file.lockfile");
    open( ORDERLOG, ">$file" );

    # debug
    # print "$logfile<br>$orderLogString3<br><br>";
    print ORDERLOG $orderLogLines;
    close(ORDERLOG);
    release_file_lock("$file.lockfile");
}

#######################################################################

sub archive_order_from_new_order_log {
    #untaint a few thingies
    $in{'cart_invoiceNumber'} =~ /([\w\=\+]+)/;
    my $invoiceNum = "$1";
    $in{'cart_and_order_id'} =~ /([\w\-\=\+\/]+)\.(\w+)/;
    my $cust_id = "$1.$2";
    &delete_order_in_new_order_log($invoiceNum,$cust_id);
    &display_order_log;
    exit;
}

#######################################################################

sub display_productsales_snapshot_screen {
    my ( $year, $filename, $stuff, $item, $qty, $id,  $new_output ) = q{};
    $year  = $in{'year'};
    $filename = "$sc_order_log_directory_path/$year" . "$scm_productlog_name";

    if ( -e $filename ) {
        open( PRODUCTLOGLOOK, "$filename" );
        while ( $stuff = <PRODUCTLOGLOOK> ) {
            ( $item, $qty ) = split( "\t", $stuff );
            ( $item, $id ) = split( "    ID ", $item );
            $new_output .= qq{<tr><td align=left>&nbsp;&nbsp;$item</td><td>&nbsp;&nbsp;&nbsp;&nbsp;$id</td><td align="center">$qty</td></tr>};
        }
        close(PRODUCTLOGLOOK);
    }

    print &$manager_page_header( 'Product Item Sales Snapshot', '', '', '', '' );

    print qq~
<h1 class='mgr-page-title'><b>Product Sales Snapshot for $year</b></h1>
<br><br>

<center>
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">

<p><b>Select a Snapshot to View (by year): </b><span style="padding-left: 25px;"></span><select name="year">
$scm_yearlinks
</select>
<input type="hidden" name="system_edit_success" value="yes">
<input name="ViewProductSnapshot" type="hidden" value="Submit">
<button class="btn btn-primary btn-sm mgr-center">Update Products Sold Snapshot</button>
</p>
</form>
<p><br></p>

<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered"><tr>
<td bgcolor="#FFCC00"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Item Name</b></td>
<td align=center bgcolor="#FFCC00"><b>Item ID #</b></td>
<td align=center bgcolor="#FFCC00"><b>Qty Sold</b></td>
</tr>
$new_output
</table>
</div>
~;

    print &$manager_page_footer;

}

#######################################################################

sub print_order_packingslip {
    my (
        $year, $month, $inv_number, $filename, $filename2,
        $cust_id, $stuff, $line, $new_output
    );

    my $cartContentsStringViewer = q{};
    my (@cart_contents_rows)     = q{};
    my $cartrow_counter          = '0';
    %cart_contents_rowsHash;
    $month      = $in{'month'};
    $year       = $in{'year'};
    $inv_number = $in{'cart_invoiceNumber'};
    $cust_id    = $in{'cart_and_order_id'};
    $filename =
        "$sc_order_log_directory_path/$year/$month/$inv_number" . "-"
      . "$cust_id"
      . "$scm_orderdata_ext";
    $filename2 = "$sc_orderViewing_dir/mgrpackingslipTemplate.html";

    if (
        (
               ( $in{'cart_invoiceNumber'} )  && ( $in{'cart_and_order_id'} )
            && ( $in{'year'} )  && ( $in{'month'} )
        )
        || ( $in{'packingviewertrigger'} )
      )
    {

        if ( -e $filename ) {
            open( ORDERLOGLOOK, "$filename" );
            $stuff = <ORDERLOGLOOK>;

            # &format_pricemgr(
            (
                $in{'year'},
                $in{'month'},
                $in{'day'},
                $in{'cart_invoiceNumber'},
                $in{'cart_and_order_id'},
                $in{'orderStatus'},
                $in{'shiptrackingID'},
                $in{'firstName'},
                $in{'lastName'},
                $in{'fullName'},
                $in{'companyName'},
                $in{'customerPhone'},
                $in{'faxNumber'},
                $in{'emailAddress'},
                $in{'orderFromAddress'},
                $in{'customerAddress2'},
                $in{'customerAddress3'},
                $in{'orderFromCity'},
                $in{'orderFromState'},
                $in{'orderFromPostal'},
                $in{'orderFromCountry'},
                $in{'shipToName'},
                $in{'shipToAddress'},
                $in{'shipToAddress2'},
                $in{'shipToAddress3'},
                $in{'shipToCity'},
                $in{'shipToState'},
                $in{'shipToPostal'},
                $in{'shipToCountry'},
                $in{'shiptoResidential'},
                $in{'insureShipment'},
                $in{'shipMethod'},
                $in{'shippingTotal'},
                $in{'salesTax'},
                $in{'tax1'},
                $in{'tax2'},
                $in{'tax3'},
                $in{'discounts'},
                $in{'COGSitem'},
                $in{'subTotal'},
                $in{'orderTotal'},
                $in{'affiliateTotal'},
                $in{'affiliateID'},
                $in{'affiliateMisc'},
                $in{'user1'},
                $in{'user2'},
                $in{'user3'},
                $in{'user4'},
                $in{'user5'},
                $in{'adminMessages'},
                $in{'cartContents'},
                $in{'GatewayUsed'},
                $in{'shippingMessages'},
                $in{'xcomments'},
                $in{'termsOfService'},
                $in{'discountCode'},
                $in{'user6'},
                $in{'user7'},
                $in{'user8'},
                $in{'user9'},
                $in{'user10'},
                $in{'buySafe'},
                $in{'order_payment_status'},
                $in{'order_payment_type_user1'},
                $in{'GiftCard_number'},
                $in{'GiftCard_amount_used'},
                $in{'internal_company_notes1'},
                $in{'internal_company_notes2'},
                $in{'internal_company_notes2'},
                $in{'customer_order_notes1'},
                $in{'customer_order_notes2'},
                $in{'customer_order_notes3'},
                $in{'customer_order_notesDLtext'},
                $in{'customer_order_notesDLhtml'},
                $in{'mailinglist_subscribe'},
                $in{'wishlist_subscribe'},
                $in{'insurance_cost'},
                $in{'trade_in_allowance'},
                $in{'rma_number'},
                $in{'customer_contact_notes1'},
                $in{'customer_contact_notes2'},
                $in{'account_number'},
                $in{'sales_rep'},
                $in{'sales_rep_notes1'},
                $in{'sales_rep_notes2'},
                $in{'how_did_you_find_us'},
                $in{'suggestion_box'},
                $in{'preferrred_shipping_date'},
                $in{'ship_order_items_as_available'},
                $in{'shipToCompany'},
                $in{'member'},
                $in{'pricingLevel'},
                $in{'orderDate'}
            ) = split( /\t/, $stuff );
            close(ORDERLOGLOOK);

            # incase of v5 order log import, orderDate will be missing, so build one
            if ( $in{'orderDate'} eq '') {
                $in{'orderDate'} = qq|$in{'month'} $in{'day'}, $in{'year'}|;
            }

            @cart_contents_rows =
              split( /::/, $in{'cartContents'}, $in{'GatewayUsed'} );
            foreach $cart_contents_rows (@cart_contents_rows) {
                $cart_contents_rowsHash{$cartrow_counter} = $cart_contents_rows;
                $cartrow_counter++;
            }

        }
        else {
            $in{'system_edit_success'} = 'notexist';
        }

    }

    my (
        $quantity,              $product,          $pid,
        $category,              $price,            $shipping,
        $optionids,             $productStatus,    $downladables,
        $altorigin,             $nontaxable,       $cartuser5,
        $cartuser6,             $formattedoptions, $priceafteroptions,
        $product_options_sting, $isDownloadble
    ) = q{};
    my $Key;
    foreach $Key ( sort keys(%cart_contents_rowsHash) ) {
        my @cart_fields2 = split( /\|/, $cart_contents_rowsHash{$Key} );
        $quantity         = $cart_fields2[0];
        $pid              = $cart_fields2[1];
        $category         = $cart_fields2[2];
        $product          = $cart_fields2[4];
        $shipping         = $cart_fields2[5];
        $downladables     = $cart_fields2[7];
        $altorigin        = $cart_fields2[8];
        $nontaxable       = $cart_fields2[9];
        $cartuser5        = $cart_fields2[10];
        $cartuser6        = $cart_fields2[11];
        $formattedoptions = $cart_fields2[12];
        $productStatus    = $cart_fields2[14];

        my @product_formatted_cartoptions = split( /\{/, $formattedoptions );

        foreach $product_formatted_cartoptions (@product_formatted_cartoptions)
        {
            if ( $downladables eq '' ) {
                $product_options_sting .= "$product_formatted_cartoptions &nbsp;&nbsp;&nbsp;";
            }
        }

        if ( $downladables ) {
            $isDownloadable =
"&nbsp;&nbsp;&nbsp;<font color=red>Downloadable Product - Delivered Electronically / Separately</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        else {
            $isDownloadable =
"&nbsp;&nbsp;&nbsp;<b>Product Status:</b> $productStatus&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        my $itemTotalWeight = format_pricemgr( $quantity * $shipping );
        $cartContentsStringViewer .= qq~
<tr>
<td colspan=8><font size=1><hr width=99%></font>
</td></tr>
<tr>
<td><font size=1>$product  &nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp; $pid &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $isDownloadable
<b>$sc_item_Total_Weight :</b> $itemTotalWeight
<br><b>Options:</b>&nbsp;&nbsp;$product_options_sting</font></td>
<td><font size=1>$quantity</font></td>
<td><font size=1>&nbsp;</font></td>
</tr>
~;
        $product_options_sting = q{};
    }

    if (   ( $in{'fullName'} eq '' )
        && ( ( $in{'lastName'} ) && ( $in{'firstName'} ) ) )
    {
        $in{'fullName'} = "$in{'firstName'} $in{'lastName'}";
    }

    open( TEMPLATE, "$filename2" );
    while ( $line = <TEMPLATE> ) {
        $line =~ s/\[\[year\]\]/$in{'year'}/g;
        $line =~ s/\[\[day\]\]/$in{'day'}/g;
        $line =~ s/\[\[month\]\]/$in{'month'}/g;
        $line =~ s/\[\[invoiceNumber\]\]/$in{'cart_invoiceNumber'}/g;
        $line =~ s/\[\[customerNumber\]\]/$in{'cart_and_order_id'}/g;
        $line =~ s/\[\[orderStatus\]\]/$in{'orderStatus'}/g;
        $line =~ s/\[\[shiptrackingID\]\]/$in{'shiptrackingID'}/g;
        $line =~ s/\[\[firstName\]\]/$in{'firstName'}/g;
        $line =~ s/\[\[lastName\]\]/$in{'lastName'}/g;
        $line =~ s/\[\[fullName\]\]/$in{'fullName'}/g;
        $line =~ s/\[\[companyName\]\]/$in{'companyName'}/g;
        $line =~ s/\[\[customerPhone\]\]/$in{'customerPhone'}/g;
        $line =~ s/\[\[faxNumber\]\]/$in{'faxNumber'}/g;
        $line =~ s/\[\[emailAddress\]\]/$in{'emailAddress'}/g;
        $line =~ s/\[\[orderFromAddress\]\]/$in{'orderFromAddress'}/g;
        $line =~ s/\[\[customerAddress2\]\]/$in{'customerAddress2'}/g;
        $line =~ s/\[\[customerAddress3\]\]/$in{'customerAddress3'}/g;
        $line =~ s/\[\[orderFromCity\]\]/$in{'orderFromCity'}/g;
        $line =~ s/\[\[orderFromState\]\]/$in{'orderFromState'}/g;
        $line =~ s/\[\[orderFromPostal\]\]/$in{'orderFromPostal'}/g;
        $line =~ s/\[\[orderFromCountry\]\]/$in{'orderFromCountry'}/g;
        $line =~ s/\[\[shipToName\]\]/$in{'shipToName'}/g;
        $line =~ s/\[\[shipToAddress\]\]/$in{'shipToAddress'}/g;
        $line =~ s/\[\[shipToAddress2\]\]/$in{'shipToAddress2'}/g;
        $line =~ s/\[\[shipToAddress3\]\]/$in{'shipToAddress3'}/g;
        $line =~ s/\[\[shipToCity\]\]/$in{'shipToCity'}/g;
        $line =~ s/\[\[shipToState\]\]/$in{'shipToState'}/g;
        $line =~ s/\[\[shipToPostal\]\]/$in{'shipToPostal'}/g;
        $line =~ s/\[\[shipToCountry\]\]/$in{'shipToCountry'}/g;
        $line =~ s/\[\[shipToResidential\]\]/$in{'shiptoResidential'}/g;
        $line =~ s/\[\[shipToInsured\]\]/$in{'insureShipment'}/g;
        $line =~ s/\[\[shipMethod\]\]/$in{'shipMethod'}/g;
        $line =~ s/\[\[user1\]\]/$in{'user1'}/g;
        $line =~ s/\[\[user2\]\]/$in{'user2'}/g;
        $line =~ s/\[\[user3\]\]/$in{'user3'}/g;
        $line =~ s/\[\[user4\]\]/$in{'user4'}/g;
        $line =~ s/\[\[user5\]\]/$in{'user5'}/g;

      #          my ($buysafetext,$buysafeamount) = split(/>/,$in{'buySafe'},2);
      #          $line =~ s/\[\[buysafecost\]\]/$buysafeamount/g;
        $line =~ s/\[\[buysafecost\]\]/$in{'buySafe'}/g;
        $line =~ s/\[\[adminMessages\]\]/$in{'adminMessages'}/g;
        $line =~ s/\[\[cartContents\]\]/$cartContentsStringViewer/g;
        $line =~ s/\[\[shippingMessages\]\]/$in{'shippingMessages'}/g;
        $line =~ s/\[\[xcomments\]\]/$in{'xcomments'}/g;
        $line =~ s/\[\[termsOfService\]\]/$in{'termsOfService'}/g;
        $line =~ s/\[\[discountCode\]\]/$in{'discountCode'}/g;
        $line =~ s/\[\[user6\]\]/$in{'user6'}/g;
        $line =~ s/\[\[user7\]\]/$in{'user7'}/g;
        $line =~ s/\[\[user8\]\]/$in{'user8'}/g;
        $line =~ s/\[\[user9\]\]/$in{'user9'}/g;
        $line =~ s/\[\[user10\]\]/$in{'user10'}/g;
        $line =~ s/\[\[affiliateTotal\]\]/$in{'affiliateTotal'}/g;
        $line =~ s/\[\[affiliateID\]\]/$in{'affiliateID'}/g;
        $line =~ s/\[\[affiliateMisc\]\]/$in{'affiliateMisc'}/g;
        $line =~ s/\[\[order_payment_status\]\]/$in{'order_payment_status'}/g;
        $line =~
          s/\[\[order_payment_type_user1\]\]/$in{'order_payment_type_user1'}/g;
        $line =~ s/\[\[GiftCard_number\]\]/$in{'GiftCard_number'}/g;
        $line =~ s/\[\[GiftCard_amount_used\]\]/$in{'GiftCard_amount_used'}/g;
        $line =~ s/\[\[internal_company_notes1\]\]/$in{'internal_company_notes1'}/g;
        $line =~ s/\[\[internal_company_notes2\]\]/$in{'internal_company_notes2'}/g;
        $line =~ s/\[\[internal_company_notes3\]\]/$in{'internal_company_notes3'}/g;
        $line =~ s/\[\[customer_order_notes1\]\]/$in{'customer_order_notes1'}/g;
        $line =~ s/\[\[customer_order_notes2\]\]/$in{'customer_order_notes2'}/g;
        $line =~ s/\[\[customer_order_notes3\]\]/$in{'customer_order_notes3'}/g;
        $line =~ s/\[\[customer_order_notesDLtext\]\]/$in{'customer_order_notesDLtext'}/g;
        $line =~ s/\[\[customer_order_notesDLhtml\]\]/$in{'customer_order_notesDLhtml'}/g;
        $line =~ s/\[\[mailinglist_subscribe\]\]/$in{'mailinglist_subscribe'}/g;
        $line =~ s/\[\[wishlist_subscribe\]\]/$in{'wishlist_subscribe'}/g;
        $line =~ s/\[\[insurance_cost\]\]/$in{'insurance_cost'}/g;
        $line =~ s/\[\[trade_in_allowance\]\]/$in{'trade_in_allowance'}/g;
        $line =~ s/\[\[rma_number\]\]/$in{'rma_number'}/g;
        $line =~ s/\[\[customer_contact_notes1\]\]/$in{'customer_contact_notes1'}/g;
        $line =~ s/\[\[customer_contact_notes2\]\]/$in{'customer_contact_notes2'}/g;
        $line =~ s/\[\[account_number\]\]/$in{'account_number'}/g;
        $line =~ s/\[\[sales_rep\]\]/$in{'sales_rep'}/g;
        $line =~ s/\[\[sales_rep_notes1\]\]/$in{'sales_rep_notes1'}/g;
        $line =~ s/\[\[sales_rep_notes2\]\]/$in{'sales_rep_notes2'}/g;
        $line =~ s/\[\[how_did_you_find_us\]\]/$in{'how_did_you_find_us'}/g;
        $line =~ s/\[\[suggestion_box\]\]/$in{'suggestion_box'}/g;
        $line =~
          s/\[\[preferrred_shipping_date\]\]/$in{'preferrred_shipping_date'}/g;
        $line =~
s/\[\[ship_order_items_as_available\]\]/$in{'ship_order_items_as_available'}/g;
        $new_output .= $line;
        $line =~ s/\[\[shipToCompany\]\]/$in{'shipToCompany'}/g;
        $line =~ s/\[\[member\]\]/$in{'member'}/g;
        $line =~ s/\[\[pricingLevel\]\]/$in{'pricingLevel'}/g;
        $line =~ s/\[\[orderDate\]\]/$in{'orderDate'}/g;
        $line =~ s/\[\[nl\]\]/\r\n/g;
    }
    close(TEMPLATE);
    print "$new_output";

}

#######################################################################

sub print_order_invoice {
    my (
        $year, $month, $inv_number, $filename, $filename2,
        $cust_id, $stuff, $line, $new_output
    );

    my $cartContentsStringViewer = q{};
    my ( @cart_contents_rows, @cart_temp_rows ) = q{};
    my $cartrow_counter = '0';
    %cart_contents_rowsHash;
    $month      = $in{'month'};
    $year       = $in{'year'};
    $inv_number = $in{'cart_invoiceNumber'};
    $cust_id    = $in{'cart_and_order_id'};
    $filename =
        "$sc_order_log_directory_path/$year/$month/$inv_number" . '-'
      . "$cust_id"
      . "$scm_orderdata_ext";
    $filename2 = "$sc_orderViewing_dir/mgrinvoiceTemplate.html";

    if (
        (
               ( $in{'cart_invoiceNumber'} ) && ( $in{'cart_and_order_id'} )
            && ( $in{'year'} ) && ( $in{'month'} )
        )
        || ( $in{'invoiceviewertrigger'} )
      )
    {

        if ( -e $filename ) {
            open( ORDERLOGLOOK, "$filename" );
            $stuff = <ORDERLOGLOOK>;

            # &format_pricemgr(
            (
                $in{'year'},
                $in{'month'},
                $in{'day'},
                $in{'cart_invoiceNumber'},
                $in{'cart_and_order_id'},
                $in{'orderStatus'},
                $in{'shiptrackingID'},
                $in{'firstName'},
                $in{'lastName'},
                $in{'fullName'},
                $in{'companyName'},
                $in{'customerPhone'},
                $in{'faxNumber'},
                $in{'emailAddress'},
                $in{'orderFromAddress'},
                $in{'customerAddress2'},
                $in{'customerAddress3'},
                $in{'orderFromCity'},
                $in{'orderFromState'},
                $in{'orderFromPostal'},
                $in{'orderFromCountry'},
                $in{'shipToName'},
                $in{'shipToAddress'},
                $in{'shipToAddress2'},
                $in{'shipToAddress3'},
                $in{'shipToCity'},
                $in{'shipToState'},
                $in{'shipToPostal'},
                $in{'shipToCountry'},
                $in{'shiptoResidential'},
                $in{'insureShipment'},
                $in{'shipMethod'},
                $in{'shippingTotal'},
                $in{'salesTax'},
                $in{'tax1'},
                $in{'tax2'},
                $in{'tax3'},
                $in{'discounts'},
                $in{'COGSitem'},
                $in{'subTotal'},
                $in{'orderTotal'},
                $in{'affiliateTotal'},
                $in{'affiliateID'},
                $in{'affiliateMisc'},
                $in{'user1'},
                $in{'user2'},
                $in{'user3'},
                $in{'user4'},
                $in{'user5'},
                $in{'adminMessages'},
                $in{'cartContents'},
                $in{'GatewayUsed'},
                $in{'shippingMessages'},
                $in{'xcomments'},
                $in{'termsOfService'},
                $in{'discountCode'},
                $in{'user6'},
                $in{'user7'},
                $in{'user8'},
                $in{'user9'},
                $in{'user10'},
                $in{'buySafe'},
                $in{'order_payment_status'},
                $in{'order_payment_type_user1'},
                $in{'GiftCard_number'},
                $in{'GiftCard_amount_used'},
                $in{'internal_company_notes1'},
                $in{'internal_company_notes2'},
                $in{'internal_company_notes2'},
                $in{'customer_order_notes1'},
                $in{'customer_order_notes2'},
                $in{'customer_order_notes3'},
                $in{'customer_order_notesDLtext'},
                $in{'customer_order_notesDLhtml'},
                $in{'mailinglist_subscribe'},
                $in{'wishlist_subscribe'},
                $in{'insurance_cost'},
                $in{'trade_in_allowance'},
                $in{'rma_number'},
                $in{'customer_contact_notes1'},
                $in{'customer_contact_notes2'},
                $in{'account_number'},
                $in{'sales_rep'},
                $in{'sales_rep_notes1'},
                $in{'sales_rep_notes2'},
                $in{'how_did_you_find_us'},
                $in{'suggestion_box'},
                $in{'preferrred_shipping_date'},
                $in{'ship_order_items_as_available'},
                $in{'shipToCompany'},
                $in{'member'},
                $in{'pricingLevel'},
                $in{'orderDate'}
            ) = split( /\t/, $stuff );
            close(ORDERLOGLOOK);

            # incase of v5 order log import, orderDate will be missing, so build one
            if ( $in{'orderDate'} eq '') {
                $in{'orderDate'} = qq|$in{'month'} $in{'day'}, $in{'year'}|;
            }

            @cart_contents_rows =
              split( /::/, $in{'cartContents'}, $in{'GatewayUsed'} );
            foreach $cart_contents_rows (@cart_contents_rows) {
                $cart_contents_rowsHash{$cartrow_counter} = $cart_contents_rows;
                $cartrow_counter++;
            }

            $in{'salesTax'}      = format_pricemgr( $in{'salesTax'} );
            $in{'orderTotal'}    = format_pricemgr( $in{'orderTotal'} );
            $in{'discounts'}     = format_pricemgr( $in{'discounts'} );
            $in{'shippingTotal'} = format_pricemgr( $in{'shippingTotal'} );
            $in{'salesTax'}      = format_pricemgr( $in{'salesTax'} );
            $in{'tax1'}          = format_pricemgr( $in{'tax1'} );
            $in{'tax2'}          = format_pricemgr( $in{'tax2'} );
            $in{'tax3'}          = format_pricemgr( $in{'tax3'} );

        }
        else {
            $in{'system_edit_success'} = 'notexist';
        }

    }

    my ( $optionids, $productStatus, $downladables, $altorigin, $nontaxable,
        $cartuser5, $cartuser6, $formattedoptions )
      = q{};
    (
        $qinvoice_quantity,              $qinvoice_product,
        $qinvoice_pid,                   $qinvoice_category,
        $qinvoice_price,                 $qinvoice_shipping,
        $qinvoice_product_options_sting, $qinvoice_isDownloadble
    ) = q{};

    my $Key;
    foreach $Key ( sort keys(%cart_contents_rowsHash) ) {
        my @cart_fields2 = split( /\|/, $cart_contents_rowsHash{$Key} );
        $qinvoice_quantity          = $cart_fields2[0];
        $qinvoice_pid               = $cart_fields2[1];
        $qinvoice_category          = $cart_fields2[2];
        $qinvoice_price             = format_pricemgr( $cart_fields2[3] );
        $qinvoice_product           = $cart_fields2[4];
        $qinvoice_shipping          = $cart_fields2[5];
        $optionids                  = $cart_fields2[6];
        $downladables               = $cart_fields2[7];
        $altorigin                  = $cart_fields2[8];
        $nontaxable                 = $cart_fields2[9];
        $cartuser5                  = $cart_fields2[10];
        $cartuser6                  = $cart_fields2[11];
        $formattedoptions           = $cart_fields2[12];
        $qinvoice_priceafteroptions = format_pricemgr( $cart_fields2[13] );
        $productStatus              = $cart_fields2[14];

        my @product_formatted_cartoptions = split( /\{/, $formattedoptions );

        foreach $product_formatted_cartoptions (@product_formatted_cartoptions)
        {
            $qinvoice_product_options_sting .= "$product_formatted_cartoptions &nbsp;&nbsp;&nbsp;";
        }

        if ( $downladables ) {
            $qinvoice_isDownloadable = qq{&nbsp;&nbsp;&nbsp;<font color=red>Downloadable Product - Delivered Electronically / Separately</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;};
        }
        else {
            $qinvoice_isDownloadable = qq{&nbsp;&nbsp;&nbsp;<b>Product Status:</b> $productStatus&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;};
        }
        $qinvoice_itemTotalWeight =
          format_pricemgr( $qinvoice_quantity * $qinvoice_shipping );
        $qinvoice_itemSubTotal =
          format_pricemgr( $qinvoice_quantity * $qinvoice_priceafteroptions );

        # for custom invoice layouts.  By Mister Ed March 27, 2008
        if ( $mc_use_alt_cart_contents_invoice_layout eq 'yes' ) {

# to use this, create a codehook sub-routine in the ./protected/custom/ sub-dir of the store
# that defines the $mc_alt_cart_contents_invoice_layout variable.
# any global and variables starting with "$qinvoice_"  are useable.
            codehook( 'alternate_cart_contents_viewer_builder' );
            $cartContentsStringViewer .=
              qq~$mc_alt_cart_contents_invoice_layout~;
        }
        else {
            $cartContentsStringViewer .= qq~
<tr>
<td colspan=8><font size=1><hr width=99%></font>
</td></tr>
<tr>
<td><font size=1>$qinvoice_product  &nbsp;&nbsp;&nbsp; - &nbsp;&nbsp;&nbsp; $qinvoice_pid &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $qinvoice_isDownloadable
<b>$sc_item_Total_Weight :</b> $qinvoice_itemTotalWeight
<br><b>Options:</b>&nbsp;&nbsp;$qinvoice_product_options_sting</font></td>
<td><font size=1>$qinvoice_quantity</font></td>
<td><font size=1>$sc_money_symbol $qinvoice_priceafteroptions<br><b>item Sub Total:</b> $sc_money_symbol $qinvoice_itemSubTotal</font></td>
</tr>
~;
        }
        $qinvoice_product_options_sting = q{};
    }

    if (   ( $in{'fullName'} eq '' )
        && ( ( $in{'lastName'} ) && ( $in{'firstName'} ) ) )
    {
        $in{'fullName'} = "$in{'firstName'} $in{'lastName'}";
    }

    open( TEMPLATE, "$filename2" );
    while ( $line = <TEMPLATE> ) {
        $line =~ s/\[\[year\]\]/$in{'year'}/g;
        $line =~ s/\[\[day\]\]/$in{'day'}/g;
        $line =~ s/\[\[month\]\]/$in{'month'}/g;
        $line =~ s/\[\[invoiceNumber\]\]/$in{'cart_invoiceNumber'}/g;
        $line =~ s/\[\[customerNumber\]\]/$in{'cart_and_order_id'}/g;
        $line =~ s/\[\[orderStatus\]\]/$in{'orderStatus'}/g;
        $line =~ s/\[\[shiptrackingID\]\]/$in{'shiptrackingID'}/g;
        $line =~ s/\[\[firstName\]\]/$in{'firstName'}/g;
        $line =~ s/\[\[lastName\]\]/$in{'lastName'}/g;
        $line =~ s/\[\[fullName\]\]/$in{'fullName'}/g;
        $line =~ s/\[\[companyName\]\]/$in{'companyName'}/g;
        $line =~ s/\[\[customerPhone\]\]/$in{'customerPhone'}/g;
        $line =~ s/\[\[faxNumber\]\]/$in{'faxNumber'}/g;
        $line =~ s/\[\[emailAddress\]\]/$in{'emailAddress'}/g;
        $line =~ s/\[\[orderFromAddress\]\]/$in{'orderFromAddress'}/g;
        $line =~ s/\[\[customerAddress2\]\]/$in{'customerAddress2'}/g;
        $line =~ s/\[\[customerAddress3\]\]/$in{'customerAddress3'}/g;
        $line =~ s/\[\[orderFromCity\]\]/$in{'orderFromCity'}/g;
        $line =~ s/\[\[orderFromState\]\]/$in{'orderFromState'}/g;
        $line =~ s/\[\[orderFromPostal\]\]/$in{'orderFromPostal'}/g;
        $line =~ s/\[\[orderFromCountry\]\]/$in{'orderFromCountry'}/g;
        $line =~ s/\[\[shipToName\]\]/$in{'shipToName'}/g;
        $line =~ s/\[\[shipToAddress\]\]/$in{'shipToAddress'}/g;
        $line =~ s/\[\[shipToAddress2\]\]/$in{'shipToAddress2'}/g;
        $line =~ s/\[\[shipToAddress3\]\]/$in{'shipToAddress3'}/g;
        $line =~ s/\[\[shipToCity\]\]/$in{'shipToCity'}/g;
        $line =~ s/\[\[shipToState\]\]/$in{'shipToState'}/g;
        $line =~ s/\[\[shipToPostal\]\]/$in{'shipToPostal'}/g;
        $line =~ s/\[\[shipToCountry\]\]/$in{'shipToCountry'}/g;
        $line =~ s/\[\[shipToResidential\]\]/$in{'shiptoResidential'}/g;
        $line =~ s/\[\[shipToInsured\]\]/$in{'insureShipment'}/g;
        $line =~ s/\[\[shipMethod\]\]/$in{'shipMethod'}/g;
        $line =~ s/\[\[shippingTotal\]\]/$in{'shippingTotal'}/g;
        $line =~ s/\[\[salesTax\]\]/$in{'salesTax'}/g;
        $line =~ s/\[\[tax1\]\]/$in{'tax1'}/g;
        $line =~ s/\[\[tax2\]\]/$in{'tax2'}/g;
        $line =~ s/\[\[tax3\]\]/$in{'tax3'}/g;
        $line =~ s/\[\[discounts\]\]/$in{'discounts'}/g;
        $line =~ s/\[\[subTotal\]\]/$in{'subTotal'}/g;
        $line =~ s/\[\[orderTotal\]\]/$in{'orderTotal'}/g;
        $line =~ s/\[\[user1\]\]/$in{'user1'}/g;
        $line =~ s/\[\[user2\]\]/$in{'user2'}/g;
        $line =~ s/\[\[user3\]\]/$in{'user3'}/g;
        $line =~ s/\[\[user4\]\]/$in{'user4'}/g;
        $line =~ s/\[\[user5\]\]/$in{'user5'}/g;

      #          my ($buysafetext,$buysafeamount) = split(/>/,$in{'buySafe'},2);
      #          $line =~ s/\[\[buysafecost\]\]/$buysafeamount/g;
        $line =~ s/\[\[buysafecost\]\]/$in{'buySafe'}/g;
        $line =~ s/\[\[adminMessages\]\]/$in{'adminMessages'}/g;
        $line =~ s/\[\[GatewayUsed\]\]/$in{'GatewayUsed'}/g;
        $line =~ s/\[\[shippingMessages\]\]/$in{'shippingMessages'}/g;
        $line =~ s/\[\[cartContents\]\]/$cartContentsStringViewer/g;
        $line =~ s/\[\[money_symbol\]\]/$sc_money_symbol/g;
        $line =~ s/\[\[xcomments\]\]/$in{'xcomments'}/g;
        $line =~ s/\[\[termsOfService\]\]/$in{'termsOfService'}/g;
        $line =~ s/\[\[discountCode\]\]/$in{'discountCode'}/g;
        $line =~ s/\[\[user6\]\]/$in{'user6'}/g;
        $line =~ s/\[\[user7\]\]/$in{'user7'}/g;
        $line =~ s/\[\[user8\]\]/$in{'user8'}/g;
        $line =~ s/\[\[user9\]\]/$in{'user9'}/g;
        $line =~ s/\[\[user10\]\]/$in{'user10'}/g;
        $line =~ s/\[\[affiliateTotal\]\]/$in{'affiliateTotal'}/g;
        $line =~ s/\[\[affiliateID\]\]/$in{'affiliateID'}/g;
        $line =~ s/\[\[affiliateMisc\]\]/$in{'affiliateMisc'}/g;
        $line =~ s/\[\[order_payment_status\]\]/$in{'order_payment_status'}/g;
        $line =~
          s/\[\[order_payment_type_user1\]\]/$in{'order_payment_type_user1'}/g;
        $line =~ s/\[\[GiftCard_number\]\]/$in{'GiftCard_number'}/g;
        $line =~ s/\[\[GiftCard_amount_used\]\]/$in{'GiftCard_amount_used'}/g;
        $line =~ s/\[\[internal_company_notes1\]\]/$in{'internal_company_notes1'}/g;
        $line =~ s/\[\[internal_company_notes2\]\]/$in{'internal_company_notes2'}/g;
        $line =~ s/\[\[internal_company_notes3\]\]/$in{'internal_company_notes3'}/g;
        $line =~ s/\[\[customer_order_notes1\]\]/$in{'customer_order_notes1'}/g;
        $line =~ s/\[\[customer_order_notes2\]\]/$in{'customer_order_notes2'}/g;
        $line =~ s/\[\[customer_order_notes3\]\]/$in{'customer_order_notes3'}/g;
        $line =~ s/\[\[customer_order_notesDLtext\]\]/$in{'customer_order_notesDLtext'}/g;
        $line =~ s/\[\[customer_order_notesDLhtml\]\]/$in{'customer_order_notesDLhtml'}/g;
        $line =~ s/\[\[mailinglist_subscribe\]\]/$in{'mailinglist_subscribe'}/g;
        $line =~ s/\[\[wishlist_subscribe\]\]/$in{'wishlist_subscribe'}/g;
        $line =~ s/\[\[insurance_cost\]\]/$in{'insurance_cost'}/g;
        $line =~ s/\[\[trade_in_allowance\]\]/$in{'trade_in_allowance'}/g;
        $line =~ s/\[\[rma_number\]\]/$in{'rma_number'}/g;
        $line =~ s/\[\[customer_contact_notes1\]\]/$in{'customer_contact_notes1'}/g;
        $line =~ s/\[\[customer_contact_notes2\]\]/$in{'customer_contact_notes2'}/g;
        $line =~ s/\[\[account_number\]\]/$in{'account_number'}/g;
        $line =~ s/\[\[sales_rep\]\]/$in{'sales_rep'}/g;
        $line =~ s/\[\[sales_rep_notes1\]\]/$in{'sales_rep_notes1'}/g;
        $line =~ s/\[\[sales_rep_notes2\]\]/$in{'sales_rep_notes2'}/g;
        $line =~ s/\[\[how_did_you_find_us\]\]/$in{'how_did_you_find_us'}/g;
        $line =~ s/\[\[suggestion_box\]\]/$in{'suggestion_box'}/g;
        $line =~
          s/\[\[preferrred_shipping_date\]\]/$in{'preferrred_shipping_date'}/g;
        $line =~
s/\[\[ship_order_items_as_available\]\]/$in{'ship_order_items_as_available'}/g;
        $line =~ s/\[\[shipToCompany\]\]/$in{'shipToCompany'}/g;
        $line =~ s/\[\[member\]\]/$in{'member'}/g;
        $line =~ s/\[\[pricingLevel\]\]/$in{'pricingLevel'}/g;
        $line =~ s/\[\[orderDate\]\]/$in{'orderDate'}/g;
        $line =~ s/\[\[nl\]\]/\r\n/g;

        $new_output .= $line;
    }
    close(TEMPLATE);
    print "$new_output";

}

#######################################################################

sub write_individual_Order_information {

    my (
        $quantity,  $product,          $pid,
        $category,  $price,            $shipping,
        $optionids, $productStatus,    $downladables,
        $altorigin, $nontaxable,       $cartuser5,
        $cartuser6, $formattedoptions, $priceafteroptions,
        $cartrow_counter
    );

    #untaint a few thingies
    $in{'cart_invoiceNumber'} =~ /([\w\=\+]+)/;
    my $invoiceNum = "$1";
    $in{'cart_and_order_id'} =~ /([\w\-\=\+\/]+)\.(\w+)/;
    my $cust_id = "$1.$2";
    $in{'month'} =~ /([\w\=\+]+)/;
    my $month = "$1";
    $in{'year'} =~ /([\w\=\+]+)/;
    my $year = "$1";

    # incase of v5 order log import, orderDate will be missing, so build one
    if ( $in{'orderDate'} eq '') {
        $in{'orderDate'} = qq|$month $in{'day'}, $year|;
    }

    my (
        $cart_string,     $cart_string_short, $orderLogString,
        $orderLogString2, $orderLogString3
    ) = '';
    my ($logfile)   = "$sc_logs_dir/$sc_order_log_name";
    my ($filename3) = "$sc_order_log_directory_path/$year/$month/$month$year";
    my ($filename8) =
        "$sc_order_log_directory_path/$year/$month/$invoiceNum" . "-"
      . "$cust_id"
      . "$scm_orderdata_ext";
    my ($filename11) = "$sc_order_log_directory_path/$year/$month$year";

##########################################################
    # recompile cart lines into a single string for order databases / logs

    $cartrow_counter = $in{'cartrow_counter'};
    my $cartrow_counter_temp  = "0";
    my $cartlog_string_thingy = q{};
    while ( $cartrow_counter_temp <= $cartrow_counter ) {
        if (   ( $in{"quantity$cartrow_counter_temp"} )
            || ( $in{"quantity$cartrow_counter_temp"} > '0' ) )
        {
            $cartlog_string_thingy .=
qq!$in{"quantity$cartrow_counter_temp"}|$in{"pid$cartrow_counter_temp"}|$in{"category$cartrow_counter_temp"}|$in{"price$cartrow_counter_temp"}|$in{"product$cartrow_counter_temp"}|$in{"shipping$cartrow_counter_temp"}|$in{"optionids$cartrow_counter_temp"}|$in{"downladables$cartrow_counter_temp"}|$in{"altorigin$cartrow_counter_temp"}|$in{"nontaxable$cartrow_counter_temp"}|$in{"cartuser5$cartrow_counter_temp"}|$in{"cartuser6$cartrow_counter_temp"}|$in{"formattedoptions$cartrow_counter_temp"}|$in{"priceafteroptions$cartrow_counter_temp"}|$in{"productStatus$cartrow_counter_temp"}!;

            # debug
            # print "$cartlog_string_thingy<br><br>";
        }
        if ( $cartrow_counter_temp < $cartrow_counter ) {
            $cartlog_string_thingy .= '::';
        }
        $cartrow_counter_temp++;
    }

    $in{'customer_order_notesDLtext'} =~ s/\r\n/\[\[nl\]\]/g;
#################################
    $cart_string =
"$in{'year'}\t$in{'month'}\t$in{'day'}\t$in{'cart_invoiceNumber'}\t$in{'cart_and_order_id'}\t$in{'orderStatus'}\t$in{'shiptrackingID'}\t$in{'firstName'}\t$in{'lastName'}\t$in{'fullName'}\t$in{'companyName'}\t$in{'customerPhone'}\t$in{'faxNumber'}\t$in{'emailAddress'}\t$in{'orderFromAddress'}\t$in{'customerAddress2'}\t$in{'customerAddress3'}\t$in{'orderFromCity'}\t$in{'orderFromState'}\t$in{'orderFromPostal'}\t$in{'orderFromCountry'}\t$in{'shipToName'}\t$in{'shipToAddress'}\t$in{'shipToAddress2'}\t$in{'shipToAddress3'}\t$in{'shipToCity'}\t$in{'shipToState'}\t$in{'shipToPostal'}\t$in{'shipToCountry'}\t$in{'shiptoResidential'}\t$in{'insureShipment'}\t$in{'shipMethod'}\t$in{'shippingTotal'}\t$in{'salesTax'}\t$in{'tax1'}\t$in{'tax2'}\t$in{'tax3'}\t$in{'discounts'}\t$in{'COGSitem'}\t$in{'subTotal'}\t$in{'orderTotal'}\t$in{'affiliateTotal'}\t$in{'affiliateID'}\t$in{'affiliateMisc'}\t$in{'user1'}\t$in{'user2'}\t$in{'user3'}\t$in{'user4'}\t$in{'user5'}\t$in{'adminMessages'}\t$cartlog_string_thingy\t$in{'GatewayUsed'}\t$in{'shippingMessages'}\t$in{'xcomments'}\t$in{'termsOfService'}\t$in{'discountCode'}\t$in{'user6'}\t$in{'user7'}\t$in{'user8'}\t$in{'user9'}\t$in{'user10'}\t$in{'buySafe'}\t$in{'order_payment_status'}\t$in{'order_payment_type_user1'}\t$in{'GiftCard_number'}\t$in{'GiftCard_amount_used'}\t$in{'internal_company_notes1'}\t$in{'internal_company_notes2'}\t$in{'internal_company_notes2'}\t$in{'customer_order_notes1'}\t$in{'customer_order_notes2'}\t$in{'customer_order_notes3'}\t$in{'customer_order_notesDLtext'}\t$in{'customer_order_notesDLhtml'}\t$in{'mailinglist_subscribe'}\t$in{'wishlist_subscribe'}\t$in{'insurance_cost'}\t$in{'trade_in_allowance'}\t$in{'rma_number'}\t$in{'customer_contact_notes1'}\t$in{'customer_contact_notes2'}\t$in{'account_number'}\t$in{'sales_rep'}\t$in{'sales_rep_notes1'}\t$in{'sales_rep_notes2'}\t$in{'how_did_you_find_us'}\t$in{'suggestion_box'}\t$in{'preferrred_shipping_date'}\t$in{'ship_order_items_as_available'}\t$in{'shipToCompany'}\t$in{'member'}\t$in{'pricingLevel'}\t$in{'orderDate'}";
    $cart_string_short =
"$in{'year'}\t$in{'month'}\t$in{'day'}\t$in{'cart_invoiceNumber'}\t$in{'cart_and_order_id'}\t$in{'orderStatus'}\t$in{'firstName'}\t$in{'lastName'}\t$in{'fullName'}\t$in{'companyName'}\t$in{'emailAddress'}\t$in{'orderFromState'}\t$in{'orderFromPostal'}\t$in{'orderFromCountry'}\t$in{'shipMethod'}\t$in{'shippingTotal'}\t$in{'salesTax'}\t$in{'tax1'}\t$in{'tax2'}\t$in{'tax3'}\t$in{'discounts'}\t$in{'COGSitem'}\t$in{'subTotal'}\t$in{'orderTotal'}\t$in{'affiliateTotal'}\t$in{'affiliateID'}\t$in{'affiliateMisc'}\t$in{'GatewayUsed'}\t$in{'buySafe'}\n";

    open( ORDERLOG, ">$filename8" );
    print ORDERLOG $cart_string;
    close(ORDERLOG);

    if ( $sc_write_monthly_short_order_logs =~ /yes/i ) {
        $filename4 = "$filename3$scm_monthyearindexlog_name";
        open( ORDERLOG4, "$filename4" );
        while (<ORDERLOG4>) {
            if ( $_ =~ /$invoiceNum/ ) {
                $orderLogString .= $cart_string_short;
            }
            else {
                $orderLogString .= $_;
            }
        }
        close(ORDERLOG4);
        get_file_lock("$logfile.lockfile");
        open( ORDERLOG4, ">$filename4" );

        # debug
        # print "$filename4<br>$orderLogString<br><br>";
        print ORDERLOG4 $orderLogString;
        close(ORDERLOG4);
        release_file_lock("$logfile.lockfile");
    }

    # master log - all details for all orders each month of each year
    if ( $sc_write_monthly_master_order_logs =~ /yes/i ) {
        $filename5 = "$filename11$scm_monthyearmasterlog_name";
        open( ORDERLOG5, "$filename5" );
        while (<ORDERLOG5>) {
            if ( $_ =~ /$invoiceNum/ ) {
                $orderLogString2 .= $cart_string;
            }
            else {
                $orderLogString2 .= $_;
            }
        }
        close(ORDERLOG5);
        get_file_lock("$logfile.lockfile");
        open( ORDERLOG5, ">$filename5" );

        # debug
        # print "$filename5<br>$orderLogString2<br><br>";
        print ORDERLOG5 $orderLogString2;
        close(ORDERLOG5);
        release_file_lock("$logfile.lockfile");
    }

    # overview log - new orders
    if ( $sc_send_order_to_log =~ /yes/i ) {
        open( ORDERLOG, "$logfile" );
        while (<ORDERLOG>) {
            if ( $_ =~ /$invoiceNum/ ) {
                $orderLogString3 .= $cart_string_short;
            }
            else {
                $orderLogString3 .= $_;
            }
        }
        close(ORDERLOG);
        get_file_lock("$logfile.lockfile");
        open( ORDERLOG, ">$logfile" );

        # debug
        # print "$logfile<br>$orderLogString3<br><br>";
        print ORDERLOG $orderLogString3;
        close(ORDERLOG);
        release_file_lock("$logfile.lockfile");
    }

    select_individual_order_screen();
}

#######################################################################

sub select_individual_order_screen {
    my ( $year, $month, $inv_number, $filename, $filename2, $cust_id, $stuff );

    my $cartContentsStringViewer = q{};
    $month      = $in{'month'};
    $year       = $in{'year'};
    $inv_number = $in{'cart_invoiceNumber'};
    $cust_id    = $in{'cart_and_order_id'};
    $filename =
        "$sc_order_log_directory_path/$year/$month/$inv_number" . '-'
      . "$cust_id"
      . "$scm_orderdata_ext";
    my ( @cart_contents_rows, @cart_temp_rows ) = q{};
    my $cartrow_counter = '0';
    %cart_contents_rowsHash;

    if (
        ( ( $in{'cart_invoiceNumber'} ) && ( $in{'cart_and_order_id'} ) && ( $in{'year'} ) && ( $in{'month'} ) )
        || ( $in{'viewertrigger'} )
      )
    {

        if ( -e $filename ) {
            open( ORDERLOGLOOK, "$filename" );
            $stuff = <ORDERLOGLOOK>;
            close(ORDERLOGLOOK);
            (
                $in{'year'},
                $in{'month'},
                $in{'day'},
                $in{'cart_invoiceNumber'},
                $in{'cart_and_order_id'},
                $in{'orderStatus'},
                $in{'shiptrackingID'},
                $in{'firstName'},
                $in{'lastName'},
                $in{'fullName'},
                $in{'companyName'},
                $in{'customerPhone'},
                $in{'faxNumber'},
                $in{'emailAddress'},
                $in{'orderFromAddress'},
                $in{'customerAddress2'},
                $in{'customerAddress3'},
                $in{'orderFromCity'},
                $in{'orderFromState'},
                $in{'orderFromPostal'},
                $in{'orderFromCountry'},
                $in{'shipToName'},
                $in{'shipToAddress'},
                $in{'shipToAddress2'},
                $in{'shipToAddress3'},
                $in{'shipToCity'},
                $in{'shipToState'},
                $in{'shipToPostal'},
                $in{'shipToCountry'},
                $in{'shiptoResidential'},
                $in{'insureShipment'},
                $in{'shipMethod'},
                $in{'shippingTotal'},
                $in{'salesTax'},
                $in{'tax1'},
                $in{'tax2'},
                $in{'tax3'},
                $in{'discounts'},
                $in{'COGSitem'},
                $in{'subTotal'},
                $in{'orderTotal'},
                $in{'affiliateTotal'},
                $in{'affiliateID'},
                $in{'affiliateMisc'},
                $in{'user1'},
                $in{'user2'},
                $in{'user3'},
                $in{'user4'},
                $in{'user5'},
                $in{'adminMessages'},
                $in{'cartContents'},
                $in{'GatewayUsed'},
                $in{'shippingMessages'},
                $in{'xcomments'},
                $in{'termsOfService'},
                $in{'discountCode'},
                $in{'user6'},
                $in{'user7'},
                $in{'user8'},
                $in{'user9'},
                $in{'user10'},
                $in{'buySafe'},
                $in{'order_payment_status'},
                $in{'order_payment_type_user1'},
                $in{'GiftCard_number'},
                $in{'GiftCard_amount_used'},
                $in{'internal_company_notes1'},
                $in{'internal_company_notes2'},
                $in{'internal_company_notes2'},
                $in{'customer_order_notes1'},
                $in{'customer_order_notes2'},
                $in{'customer_order_notes3'},
                $in{'customer_order_notesDLtext'},
                $in{'customer_order_notesDLhtml'},
                $in{'mailinglist_subscribe'},
                $in{'wishlist_subscribe'},
                $in{'insurance_cost'},
                $in{'trade_in_allowance'},
                $in{'rma_number'},
                $in{'customer_contact_notes1'},
                $in{'customer_contact_notes2'},
                $in{'account_number'},
                $in{'sales_rep'},
                $in{'sales_rep_notes1'},
                $in{'sales_rep_notes2'},
                $in{'how_did_you_find_us'},
                $in{'suggestion_box'},
                $in{'preferrred_shipping_date'},
                $in{'ship_order_items_as_available'},
                $in{'shipToCompany'},
                $in{'member'},
                $in{'pricingLevel'},
                $in{'orderDate'}
            ) = split( /\t/, $stuff );

            # incase of v5 order log import, orderDate will be missing, so build one
            if ( $in{'orderDate'} eq '') {
                $in{'orderDate'} = qq|$in{'month'} $in{'day'}, $in{'year'}|;
            }

            #$in{'customer_order_notesDLtext'} =~ s/([^\x20-\x7e])/sprintf( "\\x%02x", ord( $1 ))/eg;
            $in{'customer_order_notesDLtext'} =~ s/\[\[nl\]\]/\r\n/g;
            @cart_contents_rows =
              split( /::/, $in{'cartContents'}, $in{'GatewayUsed'} );
            foreach $cart_contents_rows (@cart_contents_rows) {
                $cart_contents_rowsHash{$cartrow_counter} = $cart_contents_rows;
                $cartrow_counter++;
            }
        }
        else {
            $in{'system_edit_success'} = 'notexist';
        }

    }
    else {
        $in{'system_edit_success'} = 'notexist';
    }

    print &$manager_page_header( 'Individual Order Management', '', '', '', '' );

    print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Individual Order Viewer</b></h1>
<br><br>


ENDOFTEXT

    if ( $versions{'Order_Management_custom'} ) {
        print qq~
<p class="well">If you need to locate the necessary order information, <a href="manager.cgi?mgr_seshun=$mgr_seshun&display_custom_order_reports_screen=yes">Click Here</a> for the required information
</p>
<p><br></p>
~;
    }

    if ( ( ( $in{'system_edit_success'} ) && ( $in{'system_edit_success'} ne 'notexist' ) ) || ( $in{'viewertrigger'} ) ) {
        my $mgr_avalara_string = '';
        if ( ( $sc_avalara_enabled eq 'yes' ) && ( $sc_avalara_tax_enable eq 'yes' ) ) {
            $mgr_avalara_string = ' | ' . qq|<a href="manager.cgi?mgr_seshun=$mgr_seshun&avataxcanceltrigger=avataxcanceltrigger&cart_invoiceNumber=$in{'cart_invoiceNumber'}">Cancel/Void AvaTax</a>|;
        }

        my $success_string = 'updated';
        if ( $in{'viewertrigger'} ) {
            $success_string = 'located (scroll down to view)';
        }
    print <<ENDOFTEXT;
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
        <h4 class="text-primary mgr-center">Order $inv_number from $month $year has been successfully $success_string.</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12">
<p><br></p>
<p class="mgr-center"><a href="manager.cgi?mgr_seshun=$mgr_seshun&invoiceviewertrigger=invoiceviewertrigger&cart_invoiceNumber=$in{'cart_invoiceNumber'}&cart_and_order_id=$in{'cart_and_order_id'}&year=$year&month=$month" target="_new">View Invoice</a>  |  <a href="manager.cgi?mgr_seshun=$mgr_seshun&packingviewertrigger=packingviewertrigger&cart_invoiceNumber=$in{'cart_invoiceNumber'}&cart_and_order_id=$in{'cart_and_order_id'}&year=$year&month=$month" target="_new">Packing Slip</a>  |  <a href="manager.cgi?mgr_seshun=$mgr_seshun&deleteviewertrigger=yes&cart_invoiceNumber=$in{'cart_invoiceNumber'}&cart_and_order_id=$in{'cart_and_order_id'}&year=$year&month=$month">Delete/Remove</a>$mgr_avalara_string</p>
<p><br></p></div>
ENDOFTEXT
    }
    elsif ( $in{'system_edit_success'} eq 'notexist' ) {
        print <<ENDOFTEXT;
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
        <h4 class="text-primary mgr-center">This Order cannot be found. Please input the correct order information.</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
ENDOFTEXT
    }

    # show order info below
    if (
        ( ( $in{'system_edit_success'} ) && ( $in{'system_edit_success'} ne 'notexist' ) )
        || ( $in{'viewertrigger'} )
      )
    {
        print qq~
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<input type="hidden" name="system_edit_success" value="yes">
<input type="hidden" name="cartrow_counter" value="$cartrow_counter">
<input name="UpdateIndividualOrder" type="hidden" value="Submit">
<input type="hidden" name="cart_invoiceNumber" value="$in{'cart_invoiceNumber'}">
<input type="hidden" name="cart_and_order_id" value="$in{'cart_and_order_id'}">
<input type="hidden" name="month" value="$in{'month'}">
<input type="hidden" name="day" value="$in{'day'}">
<input type="hidden" name="year" value="$in{'year'}">
<input type="hidden" name="orderDate" value="$in{'orderDate'}">

<button class="btn btn-primary mgr-center" style="display: block;">Update Data for this Order</button>
<p><br></p>

<b>Order Date:</b> $in{'orderDate'}<br>
<b>Invoice Number:</b> $in{'cart_invoiceNumber'}<br>
<b>Cart/Order ID Number:</b> $in{'cart_and_order_id'}<br><br>
<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered">
<tr><td align=right>Order Status: </td><td><select name="orderStatus"><option>$in{'orderStatus'}</option>$scm_orderStatusDropList</select></td></tr>
<tr><td align=right>Shipping/Tracking ID: </td><td><input name="shiptrackingID" type="text" class="form-control" value="$in{'shiptrackingID'}"></td></tr>
<tr><td align=right>Agree to Sales/Terms of Service: </td><td><input name="termsOfService" type="text" class="form-control" value="$in{'termsOfService'}"></td></tr>
<tr><td align=right>First Name: </td><td><input name="firstName" type="text" class="form-control" value="$in{'firstName'}"></td></tr>
<tr><td align=right>Last Name: </td><td><input name="lastName" type="text" class="form-control" value="$in{'lastName'}"></td></tr>
<tr><td align=right>Full Name: </td><td><input name="fullName" type="text" class="form-control" value="$in{'fullName'}"></td></tr>
<tr><td align=right>Company Name: </td><td><input name="companyName" type="text" class="form-control" value="$in{'companyName'}"></td></tr>
<tr><td align=right>Membership: </td><td><input name="member" type="text" class="form-control" value="$in{'member'}"></td></tr>
<tr><td align=right>Pricing Level: </td><td><input name="pricingLevel" type="text" class="form-control" value="$in{'pricingLevel'}"></td></tr>
<tr><td align=right>Phone Number: </td><td><input name="customerPhone" type="text" class="form-control" value="$in{'customerPhone'}"></td></tr>
<tr><td align=right>Fax Number: </td><td><input name="faxNumber" type="text" class="form-control" value="$in{'faxNumber'}"></td></tr>
<tr><td align=right>Email Address: </td><td><input name="emailAddress" type="text" class="form-control" value="$in{'emailAddress'}"></td></tr>
<tr><td align=right>Billing Address: </td><td><input name="orderFromAddress" type="text" class="form-control" value="$in{'orderFromAddress'}"></td></tr>
<tr><td align=right>Address line 2: </td><td><input name="customerAddress2" type="text" class="form-control" value="$in{'customerAddress2'}"></td></tr>
<tr><td align=right>Address line 3: </td><td><input name="customerAddress3" type="text" class="form-control" value="$in{'customerAddress3'}"></td></tr>
<tr><td align=right>Billing City: </td><td><input name="orderFromCity" type="text" class="form-control" value="$in{'orderFromCity'}"></td></tr>
<tr><td align=right>Billing State/Province: </td><td><input name="orderFromState" type="text" class="form-control" value="$in{'orderFromState'}"></td></tr>
<tr><td align=right>Billing Postal Code: </td><td><input name="orderFromPostal" type="text" class="form-control" value="$in{'orderFromPostal'}"></td></tr>
<tr><td align=right>Billing Country: </td><td><input name="orderFromCountry" type="text" class="form-control" value="$in{'orderFromCountry'}"></td></tr>
<tr><td align=right>Ship to Name: </td><td><input name="shipToName" type="text" class="form-control" value="$in{'shipToName'}"></td></tr>
<tr><td align=right>Ship to Company Name: </td><td><input name="shipToCompany" type="text" class="form-control" value="$in{'shipToCompany'}"></td></tr>
<tr><td align=right>Ship to Address: </td><td><input name="shipToAddress" type="text" class="form-control" value="$in{'shipToAddress'}"></td></tr>
<tr><td align=right>Ship to Address line 2: </td><td><input name="shipToAddress2" type="text" class="form-control" value="$in{'shipToAddress2'}"></td></tr>
<tr><td align=right>Ship to Address line 3: </td><td><input name="shipToAddress3" type="text" class="form-control" value="$in{'shipToAddress3'}"></td></tr>
<tr><td align=right>Ship to City: </td><td><input name="shipToCity" type="text" class="form-control" value="$in{'shipToCity'}"></td></tr>
<tr><td align=right>Ship to State: </td><td><input name="shipToState" type="text" class="form-control" value="$in{'shipToState'}"></td></tr>
<tr><td align=right>Ship to Postal Code: </td><td><input name="shipToPostal" type="text" class="form-control" value="$in{'shipToPostal'}"></td></tr>
<tr><td align=right>Ship to Country: </td><td><input name="shipToCountry" type="text" class="form-control" value="$in{'shipToCountry'}"></td></tr>
<tr><td align=right>Ship to Residential Address: </td><td><input name="shiptoResidential" type="text" class="form-control" value="$in{'shiptoResidential'}"></td></tr>
<tr><td align=right>Insure Shipment? </td><td><input name="insureShipment" type="text" class="form-control" value="$in{'insureShipment'}"></td></tr>
<tr><td align=right>Shipping Method / Shipped by: </td><td><input name="shipMethod" type="text" class="form-control" value="$in{'shipMethod'}"></td></tr>
<tr><td align=right>Shipping Total: </td><td><input name="shippingTotal" type="text" class="form-control" value="$in{'shippingTotal'}"></td></tr>
<tr><td align=right>Sales Tax Collected: </td><td><input name="salesTax" type="text" class="form-control" value="$in{'salesTax'}"></td></tr>
<tr><td align=right>Special Tax 1 Collected: </td><td><input name="tax1" type="text" class="form-control" value="$in{'tax1'}"></td></tr>
<tr><td align=right>Special Tax 2 Collected: </td><td><input name="tax2" type="text" class="form-control" value="$in{'tax2'}"></td></tr>
<tr><td align=right>Special Tax 3 Collected: </td><td><input name="tax3" type="text" class="form-control" value="$in{'tax3'}"></td></tr>
<tr><td align=right>Discounts Given: </td><td><input name="discounts" type="text" class="form-control" value="$in{'discounts'}"></td></tr>
<tr><td align=right>Discount Code: </td><td><input name="discountCode" type="text" class="form-control" value="$in{'discountCode'}"></td></tr>
<tr><td align=right>buySAFE Fee: </td><td><input name="buySafe" type="text" class="form-control" value="$in{'buySafe'}"></td></tr>
<tr><td align=right>COGS Generated: </td><td><input name="COGSitem" type="text" class="form-control" value="$in{'COGSitem'}"></td></tr>
<tr><td align=right>Order Sub Total: </td><td><input name="subTotal" type="text" class="form-control" value="$in{'subTotal'}"></td></tr>
<tr><td align=right>Order Grand Total: </td><td><input name="orderTotal" type="text" class="form-control" value="$in{'orderTotal'}"></td></tr>
<tr><td align=right>Affiliate Commision: </td><td><input name="affiliateTotal" type="text" class="form-control" value="$in{'affiliateTotal'}"></td></tr>
<tr><td align=right>Affiliate ID: </td><td><input name="affiliateID" type="text" class="form-control" value="$in{'affiliateID'}"></td></tr>
<tr><td align=right>Affiliate Misc: </td><td><input name="affiliateMisc" type="text" class="form-control" value="$in{'affiliateMisc'}"></td></tr>
<tr><td align=right>User 1: </td><td><input name="user1" type="text" class="form-control" value="$in{'user1'}"></td></tr>
<tr><td align=right>User 2: </td><td><input name="user2" type="text" class="form-control" value="$in{'user2'}"></td></tr>
<tr><td align=right>User 3: </td><td><input name="user3" type="text" class="form-control" value="$in{'user3'}"></td></tr>
<tr><td align=right>User 4: </td><td><input name="user4" type="text" class="form-control" value="$in{'user4'}"></td></tr>
<tr><td align=right>User 5: </td><td><input name="user5" type="text" class="form-control" value="$in{'user5'}"></td></tr>
<tr><td align=right>Admin Notes / Messages: </td><td><textarea name="adminMessages" class="form-control" rows="10">$in{'adminMessages'}</textarea></td></tr>
<tr><td align=right>Gateway Used: </td><td><input name="GatewayUsed" type="text" class="form-control" value="$in{'GatewayUsed'}"></td></tr>
<tr><td align=right>Order Payment Status: </td><td><select name="order_payment_status"><option>$in{'order_payment_status'}</option>$scm_paymentStatusDropList</select></td></tr>
<tr><td align=right>Order Payment Type User 1: </td><td><input name="order_payment_type_user1" type="text" class="form-control" value="$in{'order_payment_type_user1'}"></td></tr>
<tr><td align=right>GiftCard_number: </td><td><input name="GiftCard_number" type="text" class="form-control" value="$in{'GiftCard_number'}"></td></tr>
<tr><td align=right>GiftCard Amount Used: </td><td><input name="GiftCard_amount_used" type="text" class="form-control" value="$in{'GiftCard_amount_used'}"></td></tr>
<tr><td align=right>Shipping Messages: </td><td><textarea name="shippingMessages" class="form-control" rows="10">$in{'shippingMessages'}</textarea></td></tr>
<tr><td align=right>XCOMMENTS: </td><td><textarea name="xcomments" class="form-control" rows="5">$in{'xcomments'}</textarea></td></tr>
<tr><td align=center colspan="2"><br><b>NOTE:</b>The fields below are logged as of version 6. In version 5 they were only available for use on a customized level (order logging and invoice display)<br><br></td></tr>
<tr><td align=right>user 6: </td><td><textarea name="user6" class="form-control" rows="10">$in{'user6'}</textarea></td></tr>
<tr><td align=right>user 7: </td><td><textarea name="user7" class="form-control" rows="10">$in{'user7'}</textarea></td></tr>
<tr><td align=right>user 8: </td><td><textarea name="user8" class="form-control" rows="10">$in{'user8'}</textarea></td></tr>
<tr><td align=right>user 9: </td><td><textarea name="user9" class="form-control" rows="10">$in{'user9'}</textarea></td></tr>
<tr><td align=right>user 10: </td><td><textarea name="user10" class="form-control" rows="10">$in{'user10'}</textarea></td></tr>
<tr><td align=right>internal company notes 1: </td><td><textarea name="internal_company_notes1" class="form-control" rows="10">$in{'internal_company_notes1'}</textarea></td></tr>
<tr><td align=right>internal company notes 2: </td><td><textarea name="internal_company_notes2" class="form-control" rows="10">$in{'internal_company_notes2'}</textarea></td></tr>
<tr><td align=right>internal company notes 3: </td><td><textarea name="internal_company_notes3" class="form-control" rows="10">$in{'internal_company_notes3'}</textarea></td></tr>
<tr><td align=right>customer order notes 1: </td><td><textarea name="customer_order_notes1" class="form-control" rows="10">$in{'customer_order_notes1'}</textarea></td></tr>
<tr><td align=right>customer order notes 2: </td><td><textarea name="customer_order_notes2" class="form-control" rows="10">$in{'customer_order_notes2'}</textarea></td></tr>
<tr><td align=right>customer order notes 3: </td><td><textarea name="customer_order_notes3" class="form-control" rows="10">$in{'customer_order_notes3'}</textarea></td></tr>
<tr><td align=right>downloadable product notes - text: </td><td><textarea name="customer_order_notesDLtext" class="form-control" rows="10">$in{'customer_order_notesDLtext'}</textarea></td></tr>
<tr><td align=right>downloadable product notes - HTML: </td><td><textarea name="customer_order_notesDLhtml" class="form-control" rows="10">$in{'customer_order_notesDLhtml'}</textarea></td></tr>
<tr><td align=right>mailinglist subscribe: </td><td><input name="mailinglist_subscribe" type="text" class="form-control" value="$in{'mailinglist_subscribe'}"></td></tr>
<tr><td align=right>wishlist subscribe: </td><td><input name="wishlist_subscribe" type="text" class="form-control" value="$in{'wishlist_subscribe'}"></td></tr>
<tr><td align=right>insurance cost: </td><td><input name="insurance_cost" type="text" class="form-control" value="$in{'insurance_cost'}"></td></tr>
<tr><td align=right>trade-in allowance: </td><td><input name="trade_in_allowance" type="text" class="form-control" value="$in{'trade_in_allowance'}"></td></tr>
<tr><td align=right>RMA number: </td><td><input name="rma_number" type="text" class="form-control" value="$in{'rma_number'}"></td></tr>
<tr><td align=right>customer contact notes 1: </td><td><textarea name="customer_contact_notes1" class="form-control" rows="10">$in{'customer_contact_notes1'}</textarea></td></tr>
<tr><td align=right>customer contact notes 2: </td><td><textarea name="customer_contact_notes2" class="form-control" rows="10">$in{'customer_contact_notes2'}</textarea></td></tr>
<tr><td align=right>Account Number: </td><td><input name="account_number'" type="text" class="form-control" value="$in{'account_number'}"></td></tr>
<tr><td align=right>sales rep: </td><td><input name="sales_rep" type="text" class="form-control" value="$in{'sales_rep'}"></td></tr>
<tr><td align=right>sales rep notes 1: </td><td><textarea name="sales_rep_notes1" class="form-control" rows="10">$in{'sales_rep_notes1'}</textarea></td></tr>
<tr><td align=right>sales rep notes 2: </td><td><textarea name="sales_rep_notes2" class="form-control" rows="10">$in{'sales_rep_notes2'}</textarea></td></tr>
<tr><td align=right>how did you find us: </td><td><input name="how_did_you_find_us" type="text" class="form-control" value="$in{'how_did_you_find_us'}"></td></tr>
<tr><td align=right>suggestion box: </td><td><textarea name="suggestion_box" class="form-control" rows="10">$in{'suggestion_box'}</textarea></td></tr>
<tr><td align=right>preferrred shipping date: </td><td><input name="preferrred_shipping_date" type="text" class="form-control" value="$in{'preferrred_shipping_date'}"></td></tr>
<tr><td align=right>ship order items separately as available: </td><td><input name="ship_order_items_as_available" type="text" class="form-control" value="$in{'ship_order_items_as_available'}"></td></tr>
~;

        my (
            $quantity,  $product,          $pid,
            $category,  $price,            $shipping,
            $optionids, $productStatus,    $downladables,
            $altorigin, $nontaxable,       $cartuser5,
            $cartuser6, $formattedoptions, $priceafteroptions
        );
        my $Key;
        foreach $Key ( sort keys(%cart_contents_rowsHash) ) {
            my @cart_fields2 = split( /\|/, $cart_contents_rowsHash{$Key} );
            $quantity          = $cart_fields2[0];
            $pid               = $cart_fields2[1];
            $category          = $cart_fields2[2];
            $price             = format_pricemgr( $cart_fields2[3] );
            $product           = $cart_fields2[4];
            $shipping          = $cart_fields2[5];
            $optionids         = $cart_fields2[6];
            $downladables      = $cart_fields2[7];
            $altorigin         = $cart_fields2[8];
            $nontaxable        = $cart_fields2[9];
            $cartuser5         = $cart_fields2[10];
            $cartuser6         = $cart_fields2[11];
            $formattedoptions  = $cart_fields2[12];
            $priceafteroptions = format_pricemgr( $cart_fields2[13] );
            $productStatus     = $cart_fields2[14];
            $cartContentsStringViewer .= qq~
<input type="hidden" name="downladables$Key" value="$downladables">
<input type="hidden" name="altorigin$Key" value="$altorigin">
<input type="hidden" name="nontaxable$Key" value="$nontaxable">
<input type="hidden" name="cartuser5$Key" value="$cartuser5">
<input type="hidden" name="cartuser6$Key" value="$cartuser6">
<tr bgcolor=#c0c0c0>
<td>Product Status</td>
<td>Product ID</td>
<td>QTY</td>
<td>Product</td>
<td>Category</td>
<td>Base Price</td>
<td>Shipping</td>
<td>Price after Options</td>
</tr>
<tr>
<td><input name="productStatus$Key" type="text" size=13 value="$productStatus"></td>
<td><input name="pid$Key" type="text" size=7 value="$pid"></td>
<td><input name="quantity$Key" type="text" size=3 value="$quantity"></td>
<td><input name="product$Key" type="text" size=18 value="$product"></td>
<td><input name="category$Key" type="text" size=9 value="$category"></td>
<td><input name="price$Key" type="text" size=7 value="$price"></td>
<td><input name="shipping$Key" type="text" size=7 value="$shipping"></td>
<td><input name="priceafteroptions$Key" type="text" size=7 value="$priceafteroptions"></td>
</tr>
<tr>
<td colspan=8><font size=2><br>
These are the product Options in raw cart contents form.  Each option separated by a: { character. Be careful when editing this information:<br>
Option IDs: <input name="optionids$Key" type="text" class="form-control" value="$optionids"><br>
Formatted Options:  <input name="formattedoptions$Key" type="text" class="form-control" value="$formattedoptions"><br><br></font>
</td></tr>
~;
        }

        print qq~
<tr><td colspan="2"><input type="hidden" name="cartContents" type="text" size=40 value="$in{'cartContents'}">
<table>
<tr>
<td colspan=8 bgcolor="#FFCC00" align=center width=100%><font size="+2"><b>Individual items in this Order</b></font></td>
</tr>
<tr>
<td colspan=8><br><font size=2>If you edit any pricing, quantity, or options, make sure to reflect your adjustment in any affected field as these things will not be automagically updated without your manual intervention. Each field may contain more data than shown, if unsure, move the cursor to the left in order to scroll through each character in the box.<br><br>
<b>Items (rows) in this Order:  $cartrow_counter</b><br><br>
</font></td>
</tr>

$cartContentsStringViewer</table></td></tr>
</table></div>
<br><br>
<button class="btn btn-primary btn-lg mgr-center" style="display: block;">Update Data for this Order</button>
<p><br><br><br></p>
~;
    }

    print &$manager_page_footer;
}

#######################################################################

sub select_delete_order_screen {
    my ( $year, $month, $inv_number, $filename, $filename2, $cust_id, $stuff );

    $scm_logdirs_loaded = q{};
    set_log_years_months();
    my $cartContentsStringViewer = q{};
    $month      = $in{'month'};
    $year       = $in{'year'};
    $inv_number = $in{'cart_invoiceNumber'};
    $cust_id    = $in{'cart_and_order_id'};

    print &$manager_page_header( 'Order and Sales Log Deletion', '', '', '', '' );

    print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Individual Order and Order Log Deletion</b></h1>
<br><br>

<p class="well">This section will allow you to remove the individual order logs for an order and/or it's entry within any of the monthly, annual or overview order logs of your choice. This is also an additional place where you can remove an order from the new orders log, however it is easier to do so using the archive icon at the beginning of each order line. Once an order is removd from an order log, there is no way to recover the order. Any duplicates will be removed as well.
ENDOFTEXT

    if ( $versions{'Order_Management_custom'} ) {
        print qq~
<br><br>If you need to locate the necessary order ID information, <a href="manager.cgi?mgr_seshun=$mgr_seshun&display_custom_order_reports_screen=yes">Click Here</a> for the required information
~;
    }

    print <<ENDOFTEXT;
</p>
<p><br></p>
ENDOFTEXT

    if ( $in{system_edit_success} eq "yes" ) {
        print <<ENDOFTEXT;
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-success">
        <h4 class="text-primary mgr-center">Your Deletion Request was Successful!</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
ENDOFTEXT
    }

    print qq~
<div class="table-responsive">
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<table class="table table-condensed table-bordered">
<tr>
<td colspan="2" bgcolor="#FFCC00" align=center><font size="+2"><b>Enter an Order to Delete</b></font></td>
</tr>
<tr>
<td class="col-sm-6" align="left">
<p><b>Enter the order's Invoice number, customer ID, month and year</b>.</p>
~;

    if ( $versions{'Order_Management_custom'} ) {
        print qq~
<p><small>* If you do not know this,<br>you cannot look up the order.<br><a href="manager.cgi?mgr_seshun=$mgr_seshun&display_custom_order_reports_screen=yes">Click Here</a> for the required information</small></p>
~;
    }

    print qq~
<p><br></p>
<p>Invoice Number: <input name="cart_invoiceNumber" type="number" maxlength="25" value="$inv_number"></p>

<p>Customer Number: <input name="cart_and_order_id" type="text" maxlength="25" value="$cust_id"></p>

<div class="checkbox">
    <label>
      <input type="checkbox" name="deleteIndividualNewOrderLog" value='yes'> Remove this Order from the New Orders Log
    </label>
</div>
<div class="checkbox">
    <label>
      <input type="checkbox" name="deleteIndividualData" value='yes'> Remove this Order's Data File
    </label>
</div>
<div class="checkbox">
    <label>
      <input type="checkbox" name="deleteIndividualMasterSalesLog" value='yes'> Remove this Order from the Master Sales log
    </label>
</div>
<div class="checkbox">
    <label>
      <input type="checkbox" name="deleteIndividualOverviewSalesLog" value='yes'> Remove this Order from the Overview Sales Log
    </label>
</div>
<p><br></p>
</td>
<td class="col-sm-6" valign=top>
<p><b>Select Date of Order:</b></p>
<p><select name="month">
<option>$in{'month'}</option>
$scm_monthlinks
</select>
<select name="year">
<option>$in{'year'}</option>
$scm_yearlinks
</select></p>
<p><br><br></p>

<p><font color=red>NOTE: Once you delete this order and/or it's log entry, that information is gone forever!</font></p>
<p><br></p>
<input type="hidden" name="deletionType" value="individual">
<input type="hidden" name="system_edit_success" value="yes">
<input name="DeleteIndividualOrder" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center" style="display: block;">Delete this Order</button>
<p><br><br><br></p>

</td>
</tr></table>
</form>
</div>

<div class="table-responsive">
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<table class="table table-condensed table-bordered">
<tr>
<td colspan="2" bgcolor="#FFCC00" align=center><font size="+2"><b>Bulk Delete Functions</b></font></td>
</tr>
<tr>
<td class="col-sm-6" valign=top align="left">
<p>This will delete a single month (the entire month) within the specified year. This only deletes the directory, not any entries in the master and/or overview sales logs</p>
<p><br></p>
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<p><b>Select Month to Delete. Indicate year as well</b></p>
<p><select name="month">
<option>$in{'month'}</option>
$scm_monthlinks
</select>
<select name="year">
<option>$in{'year'}</option>
$scm_yearlinks
</select></p>
<p><br></p>

<p><font color=red>NOTE: Once you delete this Month, it is gone forever!</font></p>
<p><br></p>
<input type="hidden" name="deletionType" value="month">
<input type="hidden" name="system_edit_success" value="yes">
<input name="DeleteIndividualOrder" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center" style="display: block;">Delete this Month's Order Logs</button>
</form>
</td>
<td class="col-sm-6" valign=top>
<p>This will delete an Entire Year, the directory and all months and individual order files within it</p>
<p><br></p>
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<p><b>Select Year to Delete</b></p>
<p><select name="year">
$scm_yearlinks
</select></p>
<p><br></p>

<font color=red>NOTE: Once you delete this Year, it and all months and orders within are gone forever!</font><br><br>
<input type="hidden" name="deletionType" value="year">
<input type="hidden" name="system_edit_success" value="yes">
<input name="DeleteIndividualOrder" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center" style="display: block;">Delete this Year's Order Logs</button>
</form>
</td>
</tr></table>
</div>

<p><br><br><br></p>>
~;

    print &$manager_page_footer;
}

#######################################################################

sub select_orders_by_date_range_screen {

    print &$manager_page_header( 'Select Orders to View by Date Range', '', '', '', '' );

    print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Order Viewing - Select By Date Range</b></h1>
<br><br>
<p class="well">Note: You must have <i>Yearly</i> and or <i>Monthly</i> order logging enabled for this to work properly.</p>
<p><br></p>

<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<p><b>Select Date Range to View Orders from:</b></p>
<p class="mgr-center" style="display: block;">&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;
 From:
<select name="logreportfrommonth">
$scm_monthlinks
</select>
<select name="logreportfromday">
$scm_daylinks
</select>
<select name="logreportfromyear">
$scm_yearlinks
</select> &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;
To: &nbsp;&nbsp;
<select name="logreporttomonth">
<option>$scm_month</option>
$scm_monthlinks
</select>
<select name="logreporttoday">
<option>$scm_day</option>
$scm_daylinks
</select>
<select name="logreporttoyear">
<option>$scm_year</option>
$scm_yearlinks
</select></p>
<p><br><br></p>

<input type="hidden" name="system_edit_success" value="yes">
<input name="CompileOrdersByDateRange" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center" style="display: block;">View Orders from the Selected Date Range</button>

<p><br><br><br></p>
ENDOFTEXT

    print &$manager_page_footer;
}

#######################################################################
#
# added from old v5 & v6 custom order manager
# by Mister Ed - Sept 17, 2011
#
#######################################################################

sub compile_Orders_by_date_range_output {
    my ( $year, $month, $day );
    local (%orderLoggingHash);

    $custom_report_error = q{};

    my $day_is_okay  = q{};
    my $start_and_to_years_same  = 'no';
    my $start_and_to_months_same = q{};
    my $tempStartMonthCounter  = 0;
    my $tempEndMonthCounter  = 0;
    my $counter = 0;
    my $tempYearCounter  = $in{'logreportfromyear'};

    #figure Start month location in array: @monthsLong
    while ( $months_long[$tempStartMonthCounter] ne $in{'logreportfrommonth'} ) {
        $tempStartMonthCounter++;
    }

    #figure End month location in array: @monthsLong
    while ( $months_long[$tempEndMonthCounter] ne $in{'logreporttomonth'} ) {
        $tempEndMonthCounter++;
    }

    if ( $in{'logreportfromyear'} eq $in{'logreporttoyear'} ) {
        $start_and_to_years_same = 'yes';
    }
    elsif ( $in{'logreportfromyear'} > $in{'logreporttoyear'} ) {
        $start_and_to_years_same = 'yes';
        $custom_report_error .=
'Cannot complete report: Ending Year and Starting Year is not in proper order<br>';
    }

    if ( ( $tempStartMonthCounter > $tempEndMonthCounter ) && ( $start_and_to_years_same =~ /yes/i ) ) {
        $custom_report_error .=
'Cannot complete report: Ending Month and Starting Month is not in proper order<br>';
    }
###########
    while ( ( $tempYearCounter <= $in{'logreporttoyear'} ) && ( $custom_report_error eq '' ) ) {
        if ( $tempYearCounter eq $in{'logreporttoyear'} ) {
            $start_and_to_years_same = 'yes';
        }

        while ( ( $tempStartMonthCounter <= 11 ) && ( $start_and_to_months_same eq '' ) && ( $custom_report_error eq '' ) ) {
            my $monthThingy = $months_long[$tempStartMonthCounter];
            $filename4 =
"$sc_order_log_directory_path/$tempYearCounter/$monthThingy/$monthThingy$tempYearCounter$scm_monthyearindexlog_name";
            if ( ( $tempStartMonthCounter eq $tempEndMonthCounter ) && ( $start_and_to_years_same =~ /yes/i ) ) {
                $start_and_to_months_same = 'yes';
            }

# Debugging
# $scm_order_report_string .= "startmonth = $startMonthLongName or $in{'logreporttomonth'}, we looked at: $months_long[$tempStartMonthCounter] $monthThingy $tempYearCounter<br>$filename4<br><br>";

            if ( -e $filename4 ) {
                open( ORDERLOGLOOK, "$filename4" );
                while (<ORDERLOGLOOK>) {
                    (
                        $year,
                        $month,
                        $day,
                        $orderLoggingHash{'cart_invoiceNumber'},
                        $orderLoggingHash{'cart_and_order_id'},
                        $orderLoggingHash{'orderStatus'},
                        $orderLoggingHash{'firstName'},
                        $orderLoggingHash{'lastName'},
                        $orderLoggingHash{'fullName'},
                        $orderLoggingHash{'companyName'},
                        $orderLoggingHash{'emailAddress'},
                        $orderLoggingHash{'orderFromState'},
                        $orderLoggingHash{'orderFromPostal'},
                        $orderLoggingHash{'orderFromCountry'},
                        $orderLoggingHash{'shipMethod'},
                        $orderLoggingHash{'shippingTotal'},
                        $orderLoggingHash{'salesTax'},
                        $orderLoggingHash{'tax1'},
                        $orderLoggingHash{'tax2'},
                        $orderLoggingHash{'tax3'},
                        $orderLoggingHash{'discounts'},
                        $orderLoggingHash{'COGSitem'},
                        $orderLoggingHash{'subTotal'},
                        $orderLoggingHash{'orderTotal'},
                        $orderLoggingHash{'affiliateTotal'},
                        $orderLoggingHash{'affiliateID'},
                        $orderLoggingHash{'affiliateMisc'},
                        $orderLoggingHash{'GatewayUsed'}
                    ) = split( /\t/, $_ );

                    if (   ( $in{'logreportfrommonth'} =~ /$month/i ) && ( $in{'logreportfromyear'} eq $year ) )  {
                        if ( ( $day >= $in{'logreportfromday'} ) && ( ( $day <= $in{'logreporttoday'} )  || ( $month !~ $in{'logreporttomonth'} ) ) )  {
                            $day_is_okay = 'yes';
                        }
                        else {
                            $day_is_okay = 'no';
                        }
                    }
                    elsif ( ( $in{'logreporttomonth'} =~ /$month/i ) && ( $in{'logreporttoyear'} eq $year ) ) {
                        if ( $day <= $in{'logreporttoday'} ) {
                            $day_is_okay = 'yes';
                        }
                        else {
                            $day_is_okay = 'no';
                        }
                    }
                    else {
                        $day_is_okay = q{};
                    }

                    if ( $day_is_okay ne 'no' ) {
                        $counter++;
                        $scm_order_report_string .= qq~<tr>
<td align=center>$orderLoggingHash{'orderStatus'}</td>
<td align=center>$month $day, $year</td>
<td align=center>$orderLoggingHash{'cart_invoiceNumber'}<br>$orderLoggingHash{'cart_and_order_id'}</td>
~;

                        if ( $orderLoggingHash{'lastName'} ) {
                            $scm_order_report_string .= qq~
<td align=center>$orderLoggingHash{'firstName'} $orderLoggingHash{'lastName'}</td>
~;
                        }
                        else {
                            $scm_order_report_string .= qq~<td align=center>$orderLoggingHash{'fullName'}</td>~;
                        }

                        $order_filename = "$scm_order_logpath/$orderLoggingHash{'cart_invoiceNumber'}" . '-' . "$orderLoggingHash{'cart_and_order_id'}";
                        my $mgr_avalara_string = '';
                        if ( ( $sc_avalara_enabled eq 'yes' ) && ( $sc_avalara_tax_enable eq 'yes' ) ) {
                            $mgr_avalara_string = qq|<a href="manager.cgi?mgr_seshun=$mgr_seshun&avataxcanceltrigger=avataxcanceltrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}">Cancel AvaTax</a><br>|;
                        }
                        $scm_order_report_string .= qq~
<td align=center>$sc_money_symbol $orderLoggingHash{'orderTotal'}</td>
<td valign='middle' align=center>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&viewertrigger=viewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month"><i class="fa fa-pencil-square-o fa-lg" data-toggle="tooltip" data-placement="top" title="View / Edit this order. All customer and order info and cart items presented in form format for viewing and/or editing." aria-hidden="true"></i></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&invoiceviewertrigger=invoiceviewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month" target="_new"><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADnSURBVEhL7dQxDgFRFIXhsQVRqARRYwFKW1CqJHYgdAqFNViAml6pnw2IQqVUKEQU/IcpZOZO5j1CInGTL3nJ3HMyJnmCn58cmmh7UkZZc/RgieuLFjDLG9BCF1VPyihbR2Ja0MMSKhg6KkMZZdWRmOdiBS7YGo44RWftTOBcPMIO1syxfhzvO1N4FeutVoY9DtFZO97F+skzwwYq11k73sUf+RSD6OxiDOfiAnroZ9COdp2L08a6zjW8Xazncc7fWDcpbazrnIcyqcVFnKE/ovi1zaKMsuowp4MQ8WucRRll//O1CYIbFUSKVjC73wAAAAAASUVORK5CYII=" class="fa fa-2x" data-toggle="tooltip" data-placement="top" title="View Invoice - view this order in invoice format. This individual order is presented using the your store's invoice template."></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&packingviewertrigger=packingviewertrigger&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month" target="_new"><i class="fa fa-truck fa-lg" data-toggle="tooltip" data-placement="top" title="View Packing Slip - view this order in invoice format. This individual order is presented using the your store's invoice template."></i></a>
<a href="manager.cgi?mgr_seshun=$mgr_seshun&deleteviewertrigger=yes&cart_invoiceNumber=$orderLoggingHash{'cart_invoiceNumber'}&cart_and_order_id=$orderLoggingHash{'cart_and_order_id'}&year=$year&month=$month"><i class="fa fa-trash-o fa-lg" data-toggle="tooltip" data-placement="top" title="Delete this order. You will be taken to a screen where you can chose to delete the order from various log files as well as option to delete all orders from a specific month or year." aria-hidden="true"></i></a>
<br>$mgr_avalara_string</td>
</tr>
~;
                    }

                }

                close(ORDERLOGLOOK);
            }
            $tempStartMonthCounter++;
        }
        $tempStartMonthCounter = 0;
        $tempYearCounter++;
    }    # END # while ($tempYearCounter <= $in{'logreporttoyear'})
###########
    print &$manager_page_header( "Displaying Your Orders from $in{'logreportfrommonth'} $in{'logreportfromday'}, $in{'logreportfromyear'} to $in{'logreporttomonth'} $in{'logreporttoday'}, $in{'logreporttoyear'}", '', '', '' );

    print qq~
<h1 class='mgr-page-title'><b>Orders from:<br>$in{'logreportfrommonth'} $in{'logreportfromday'}, $in{'logreportfromyear'} to $in{'logreporttomonth'} $in{'logreporttoday'}, $in{'logreporttoyear'}</b></h1>
<p><br></p>

<p class="mgr-center"><a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&select_orders_by_date_range_screen=yes" class="btn btn-primary" role="button">Get Orders From Another Date Range</a></p>
<p><br></p>

<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered"><tr>
<td valign=middle align=center bgcolor="#FFCC00"><b>Order Status</b></td>
<td valign=middle align=center bgcolor="#FFCC00" width=85><b>Order Date</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Invoice #</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Customer Name</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Order Total</b></td>
<td bgcolor="#FFCC00">&nbsp;</td>
</tr>
$scm_order_report_string
~;

    if ( $counter > 20 ) {
        print qq~
<tr>
<td valign=middle align=center bgcolor="#FFCC00"><b>Order Status</b></td>
<td valign=middle align=center bgcolor="#FFCC00" width=85><b>Order Date</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Invoice #</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Customer Name</b></td>
<td valign=middle align=center bgcolor="#FFCC00"><b>Order Total</b></td>
<td bgcolor="#FFCC00">&nbsp;</td>
</tr>
~;
    }

    print qq~
</table>
</div>
<p><br><br><br></p>
<p class="mgr-center"><a href="manager.cgi?mgr_seshun=$in{'mgr_seshun'}&select_orders_by_date_range_screen=yes" class="btn btn-primary" role="button">Get Orders From Another Date Range</a></p>
<p><br><br><br></p>
~;
    print &$manager_page_footer;

}

#######################################################################
#
# added from old v5 & v6 custom order manager
# by Mister Ed - Sept 17, 2011
#
#######################################################################

sub compile_sales_snapshot_information {
    local ($filename) = "$mgrdir/";
    my ( $year, $month, $day );
    my (
        $mysalesTax, $mytax1, $mytax2,
        $mytax3,     $mydiscounts,  $myCOGSitem,
        $mysubTotal, $myorderTotal, $myaffiliateTotal,
        $myaffiliateSubTotal, $mynumberoforders, $myaverageordersize,
        $myhighestorder, $myshipTotal
    ) = '0';
    my $mylowestorder = 10000001;
    local (%orderLoggingHash);

    $custom_report_error = q{};

    my $day_is_okay              = q{};
    my $start_and_to_years_same  = 'no';
    my $start_and_to_months_same = q{};
    my $tempStartMonthCounter    = 0;
    my $tempEndMonthCounter      = 0;
    my $tempYearCounter          = $in{'logreportfromyear'};

    #figure Start month location in array: @monthsLong
    while ( $months_long[$tempStartMonthCounter] ne $in{'logreportfrommonth'} ) {
        $tempStartMonthCounter++;
    }

    #figure End month location in array: @monthsLong
    while ( $months_long[$tempEndMonthCounter] ne $in{'logreporttomonth'} ) {
        $tempEndMonthCounter++;
    }

    if ( $in{'logreportfromyear'} eq $in{'logreporttoyear'} ) {
        $start_and_to_years_same = 'yes';
    }
    elsif ( $in{'logreportfromyear'} > $in{'logreporttoyear'} ) {
        $start_and_to_years_same = 'yes';
        $custom_report_error .=
'Cannot complete report: Ending Year and Starting Year are not in the proper order<br>';
    }

    if (   ( $tempStartMonthCounter > $tempEndMonthCounter )
        && ( $start_and_to_years_same =~ /yes/i ) )
    {
        $custom_report_error .=
'Cannot complete report: Ending Month and Starting Month is not in proper order<br>';
    }
###########
    while (( $tempYearCounter <= $in{'logreporttoyear'} )
        && ( $custom_report_error eq "" ) )
    {
        if ( $tempYearCounter eq $in{'logreporttoyear'} ) {
            $start_and_to_years_same = "yes";
        }
        while (( $tempStartMonthCounter <= 11 )
            && ( $start_and_to_months_same eq $MGR_EMPTY )
            && ( $custom_report_error eq $MGR_EMPTY ) )
        {
            my $monthThingy = $months_long[$tempStartMonthCounter];
            $filename4 =
"$sc_order_log_directory_path/$tempYearCounter/$monthThingy/$monthThingy$tempYearCounter$scm_monthyearindexlog_name";
            if (   ( $tempStartMonthCounter eq $tempEndMonthCounter )
                && ( $start_and_to_years_same =~ /yes/i ) )
            {
                $start_and_to_months_same = 'yes';
            }

# Debugging
# $scm_order_report_string .= "startmonth = $startMonthLongName or $in{'logreporttomonth'}, we looked at: $months_long[$tempStartMonthCounter] $monthThingy $tempYearCounter<br>$filename4<br><br>";

 my (
        $mymonthlysalesTax, $mymonthlytax1, $mymonthlytax2,
        $mymonthlytax3,     $mymonthlydiscounts,  $mymonthlyCOGSitem,
        $mymonthlysubTotal, $mymonthlyorderTotal, $mymonthlyaffiliateTotal,
        $mymonthlyaffiliateSubTotal, $mymonthlynumberoforders, $mymonthlyaverageordersize,
        $mymonthlyhighestorder, $mymonthlyshipTotal
    ) = '0';
    my $mymonthlylowestorder = 10000001;

            if ( -e $filename4 ) {
                open( ORDERLOGLOOK, "$filename4" );
                while (<ORDERLOGLOOK>) {
                    (
                        $year,
                        $month,
                        $day,
                        $orderLoggingHash{'cart_invoiceNumber'},
                        $orderLoggingHash{'cart_and_order_id'},
                        $orderLoggingHash{'orderStatus'},
                        $orderLoggingHash{'firstName'},
                        $orderLoggingHash{'lastName'},
                        $orderLoggingHash{'fullName'},
                        $orderLoggingHash{'companyName'},
                        $orderLoggingHash{'emailAddress'},
                        $orderLoggingHash{'orderFromState'},
                        $orderLoggingHash{'orderFromPostal'},
                        $orderLoggingHash{'orderFromCountry'},
                        $orderLoggingHash{'shipMethod'},
                        $orderLoggingHash{'shippingTotal'},
                        $orderLoggingHash{'salesTax'},
                        $orderLoggingHash{'tax1'},
                        $orderLoggingHash{'tax2'},
                        $orderLoggingHash{'tax3'},
                        $orderLoggingHash{'discounts'},
                        $orderLoggingHash{'COGSitem'},
                        $orderLoggingHash{'subTotal'},
                        $orderLoggingHash{'orderTotal'},
                        $orderLoggingHash{'affiliateTotal'},
                        $orderLoggingHash{'affiliateID'},
                        $orderLoggingHash{'affiliateMisc'},
                        $orderLoggingHash{'GatewayUsed'}
                    ) = split( /\t/, $_ );

                    if ( ( $in{'logreportfrommonth'} =~ /$month/i ) && ( $in{'logreportfromyear'} eq $year ) )  {
                        if ( ( $day >= $in{'logreportfromday'} ) && ( ( $day <= $in{'logreporttoday'} )  || ( $month !~ $in{'logreporttomonth'} ) ) )  {
                            $day_is_okay = 'yes';
                        }
                        else {
                            $day_is_okay = 'no';
                        }
                    }
                    elsif ( ( $in{'logreporttomonth'} =~ /$month/i ) && ( $in{'logreporttoyear'} eq $year ) ) {
                        if ( $day <= $in{'logreporttoday'} ) {
                            $day_is_okay = 'yes';
                        }
                        else {
                            $day_is_okay = 'no';
                        }
                    }
                    else {
                        $day_is_okay = q{};
                    }

                    if ( $day_is_okay ne 'no' ) {

                        # Generate monthly totals for snapshot
                        if ( $orderLoggingHash{'orderTotal'} > $mymonthlyhighestorder ) {
                          $mymonthlyhighestorder = $orderLoggingHash{'orderTotal'};
                        }
                        if ( $orderLoggingHash{'orderTotal'} < $mymonthlylowestorder ) {
                          $mymonthlylowestorder = $orderLoggingHash{'orderTotal'};
                        }
                        $mymonthlysalesTax   += $orderLoggingHash{'salesTax'};
                        $mymonthlytax1       += $orderLoggingHash{'tax1'};
                        $mymonthlytax2       += $orderLoggingHash{'tax2'};
                        $mymonthlytax3       += $orderLoggingHash{'tax3'};
                        $mymonthlydiscounts  += $orderLoggingHash{'discounts'};
                        $mymonthlyCOGSitem  += $orderLoggingHash{'COGSitem'};
                        $mymonthlyshipTotal += $orderLoggingHash{'shippingTotal'};
                        $mymonthlysubTotal   += $orderLoggingHash{'subTotal'};
                        $mymonthlyorderTotal += $orderLoggingHash{'orderTotal'};
                        $mymonthlynumberoforders += 1;
                        $mymonthlyaverageordersize = $mymonthlyorderTotal / $mymonthlynumberoforders;
                        $mymonthlyaffiliateTotal +=  $orderLoggingHash{'affiliateTotal'};
                        if ( $orderLoggingHash{'affiliateTotal'} ) {
                            $mymonthlyaffiliateSubTotal += $orderLoggingHash{'subTotal'};
                        }
                    }

                }

                close(ORDERLOGLOOK);
            }
            $tempStartMonthCounter++;

            # Add Monthly to Running Totals
            if ( $mymonthlyhighestorder > $myhighestorder ) {
                $myhighestorder = $mymonthlyhighestorder;
            }
            if ( $mymonthlylowestorder < $mylowestorder ) {
                $mylowestorder = $mymonthlylowestorder;
            }
            $mysalesTax   += $mymonthlysalesTax;
            $mytax1       += $mymonthlytax1;
            $mytax2       += $mymonthlytax2;
            $mytax3       += $mymonthlytax3;
            $mydiscounts  += $mymonthlydiscounts;
            $myshipTotal += $mymonthlyshipTotal;
            $myCOGSitem  += $mymonthlyCOGSitem;
            $mysubTotal   += $mymonthlysubTotal;
            $myorderTotal += $mymonthlyorderTotal;
            $mynumberoforders += $mymonthlynumberoforders;
            $myaffiliateTotal +=  $mymonthlyaffiliateTotal;
            $myaffiliateSubTotal += $mymonthlyaffiliateSubTotal;

            if ( $mymonthlynumberoforders > 0 ) {

            $scm_order_report_string .=
      qq~<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered"><tr>
<td align="left" bgcolor="#FFCC00" colspan="2"><font size=+1><b>Order Snapshot Data for: $monthThingy $tempYearCounter</b></font></td></tr>
~;

    if ( $in{'numberoforders'} ) {
         $scm_order_report_string .= qq~
<tr><td><b>Number of Orders:</b></td><td>$mymonthlynumberoforders</td></tr>
~;
    }
    if ( $in{'averageordersize'} ) {
        $mymonthlyaverageordersize = format_pricemgr($mymonthlyaverageordersize);
         $scm_order_report_string .= qq~
<tr><td><b>Average Order Size (by order total):</b></td><td>$sc_money_symbol $mymonthlyaverageordersize</td></tr>
~;
    }
    if ( $in{'highestorder'} ) {
        $mymonthlyhighestorder = format_pricemgr($mymonthlyhighestorder);
         $scm_order_report_string .= qq~
<tr><td><b>Largest Order (by order total):</b></td><td>$sc_money_symbol $mymonthlyhighestorder</td></tr>
~;
    }
    if ( $in{'lowestorder'} ) {
        $mymonthlylowestorder = format_pricemgr($mymonthlylowestorder);
         $scm_order_report_string .= qq~
<tr><td><b>Smallest Order (by order total):</b></td><td>$sc_money_symbol $mymonthlylowestorder</td></tr>
~;
    }
    if ( $in{'grosssales'} ) {
        $mymonthlyorderTotal = format_pricemgr($mymonthlyorderTotal);
         $scm_order_report_string .= qq~
<tr><td><b>Total Gross Sales:</b></td><td>$sc_money_symbol $mymonthlyorderTotal</td></tr>
~;
    }
    if ( $in{'discountsgiven'} ) {
        $mymonthlydiscounts = format_pricemgr($mymonthlydiscounts);
         $scm_order_report_string .= qq~
<tr><td><b>Total Discounts Given (if setup):</b></td><td>$sc_money_symbol $mymonthlydiscounts</td></tr>
~;
    }
    if ( $in{'shipTotal'} ) {
        $mymonthlyshipTotal = format_pricemgr($mymonthlyshipTotal);
         $scm_order_report_string .= qq~
<tr><td><b>Total Shipping Charges:</b></td><td>$sc_money_symbol $mymonthlyshipTotal</td></tr>
~;
    }
    if ( $in{'salestaxes'} ) {
        $mymonthlysalesTax = format_pricemgr($mymonthlysalesTax);
         $scm_order_report_string .= qq~
<tr><td><b>Total Sales Taxes Collected:</b></td><td>$sc_money_symbol $mymonthlysalesTax</td></tr>
~;
    }
    if ( $in{'sales1taxes'} ) {
        $mymonthlytax1 = format_pricemgr($mymonthlytax1);
         $scm_order_report_string .= qq~
<tr><td><b>Total Special Tax 1 (if setup):</b></td><td>$sc_money_symbol $mymonthlytax1</td></tr>
~;
    }
    if ( $in{'sales2taxes'} ) {
        $mymonthlytax2 = format_pricemgr($mymonthlytax2);
         $scm_order_report_string .= qq~
<tr><td><b>Total Special Tax 2 (if setup):</b></td><td>$sc_money_symbol $mymonthlytax2</td></tr>
~;
    }
    if ( $in{'sales3taxes'} ) {
        $mymonthlytax3 = format_pricemgr($mymonthlytax3);
         $scm_order_report_string .= qq~
<tr><td><b>Total Special Tax 3 (if setup):</b></td><td>$sc_money_symbol $mymonthlytax3</td></tr>
~;
    }
    if ( $in{'netsales'} ) {
        $mymonthlysubTotal = format_pricemgr($mymonthlysubTotal);
         $scm_order_report_string .= qq~
<tr><td><b>Total Net Sales (Gross minus shipping, taxes, and discounts):</b></td><td>$sc_money_symbol $mymonthlysubTotal</td></tr>
~;
    }
    if ( $in{'COGSitem'} ) {
        $mymonthlyCOGSitem = &format_pricemgr($mymonthlyCOGSitem);
         $scm_order_report_string .= qq~
<tr><td><b>Total COGS (if setup):</b></td><td>$sc_money_symbol $mymonthlyCOGSitem</td></tr>
~;
    }

    if ( $in{'affiliatetotals'} ) {
        $mymonthlyaffiliateTotal = format_pricemgr($mymonthlyaffiliateTotal);
        $scm_order_report_string .= qq~
<tr><td><b>Total Affiliate Commissions Paid/Payable (if setup):</b></td><td>$sc_money_symbol $mymonthlyaffiliateTotal</td></tr>
~;
    }
    if ( $in{'affiliatenetgentotals'} ) {
        $mymonthlyaffiliateSubTotal = format_pricemgr($mymonthlyaffiliateSubTotal);
         $scm_order_report_string .= qq~
<tr><td><b>Total Affiliate Generated Net Sales (if setup):</b></td><td>$sc_money_symbol $mymonthlyaffiliateSubTotal</td></tr>
~;
    }

     $scm_order_report_string .= qq~
</table></div><p><br></p>
~;
            }

        }
        $tempStartMonthCounter = 0;
        $tempYearCounter++;
    }    # while ($tempYearCounter <= $in{'logreporttoyear'})
###########

    $myaverageordersize = $myorderTotal / $mynumberoforders;

    $scm_order_totals_string = qq~
<div class="table-responsive">
<table class="table table-condensed table-striped table-bordered"><tr>
<td align=center bgcolor="#FFCC00" colspan="2"><font size=+1><b>Order Totals Data for: $in{'logreportfrommonth'} $in{'logreportfromday'}, $in{'logreportfromyear'} to $in{'logreporttomonth'} $in{'logreporttoday'}, $in{'logreporttoyear'}</b></font></td></tr>
~;
    if ( $in{'numberoforders'} ) {
        $scm_order_totals_string .= qq~<tr><td><b>Number of Orders:</b></td><td>$mynumberoforders</td></tr>~;
    }
    if ( $in{'averageordersize'} ) {
        $myaverageordersize = format_pricemgr($myaverageordersize);
        $scm_order_totals_string .= qq~
<tr><td><b>Average Order Size  (by order total):</b></td><td>$sc_money_symbol $myaverageordersize</td></tr>
~;
    }
    if ( $in{'highestorder'} ) {
        $myhighestorder = format_pricemgr($myhighestorder);
        $scm_order_totals_string .= qq~
<tr><td><b>Largest Order (by order total):</b></td><td>$sc_money_symbol $myhighestorder</td></tr>
~;
    }
    if ( $in{'lowestorder'} ) {
        $mylowestorder = format_pricemgr($mylowestorder);
        $scm_order_totals_string .= qq~
<tr><td><b>Smallest Order (by order total):</b></td><td>$sc_money_symbol $mylowestorder</td></tr>
~;
    }
    if ( $in{'grosssales'} ) {
        $myorderTotal = format_pricemgr($myorderTotal);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Gross Sales:</b></td><td>$sc_money_symbol $myorderTotal</td></tr>
~;
    }
    if ( $in{'shipTotal'} ) {
        $myshipTotal = format_pricemgr($myshipTotal);
         $scm_order_totals_string .= qq~
<tr><td><b>Total Shipping Charges:</b></td><td>$sc_money_symbol $myshipTotal</td></tr>
~;
    }
    if ( $in{'discountsgiven'} ) {
        $mydiscounts = format_pricemgr($mydiscounts);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Discounts Given (if setup):</b></td><td>$sc_money_symbol $mydiscounts</td></tr>
~;
    }
    if ( $in{'salestaxes'} ) {
        $mysalesTax = format_pricemgr($mysalesTax);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Sales Taxes Collected:</b></td><td>$sc_money_symbol $mysalesTax</td></tr>
~;
    }
    if ( $in{'sales1taxes'} ) {
        $mytax1 = format_pricemgr($mytax1);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Special Tax 1 (if setup):</b></td><td>$sc_money_symbol $mytax1</td></tr>
~;
    }
    if ( $in{'sales2taxes'} ) {
        $mytax2 = format_pricemgr($mytax2);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Special Tax 2 (if setup):</b></td><td>$sc_money_symbol $mytax2</td></tr>
~;
    }
    if ( $in{'sales3taxes'} ) {
        $mytax3 = format_pricemgr($mytax3);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Special Tax 3 (if setup):</b></td><td>$sc_money_symbol $mytax3</td></tr>
~;
    }
    if ( $in{'netsales'} ) {
        $mysubTotal = format_pricemgr($mysubTotal);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Net Sales (prior to all shipping, taxes, and discounts):</b></td><td>$sc_money_symbol $mysubTotal</td></tr>
~;
    }
    if ( $in{'COGSitem'} ) {
        $myCOGSitem = &format_pricemgr($myCOGSitem);
        $scm_order_totals_string .= qq~
<tr><td><b>Total COGS (if setup):</b></td><td>$sc_money_symbol $myCOGSitem</td></tr>
~;
    }
    if ( $in{'affiliatetotals'} ) {
        $myaffiliateTotal = format_pricemgr($myaffiliateTotal);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Affiliate Commissions Paid/Payable (if setup):</b></td><td>$sc_money_symbol $myaffiliateTotal</td></tr>
~;
    }
    if ( $in{'affiliatenetgentotals'} ) {
        $myaffiliateSubTotal = format_pricemgr($myaffiliateSubTotal);
        $scm_order_totals_string .= qq~
<tr><td><b>Total Affiliate Generated Net Sales (if setup):</b></td><td>$sc_money_symbol $myaffiliateSubTotal</td></tr>
~;
    }

    $scm_order_totals_string .= qq~
</table></div><p><br></p>
~;

######################
    print &$manager_page_header( " Sales Performance Snapshots for: $in{'logreportfrommonth'} $in{'logreportfromday'}, $in{'logreportfromyear'} to $in{'logreporttomonth'} $in{'logreporttoday'}, $in{'logreporttoyear'}", '', '', '', '' );

    print qq~
$scm_order_totals_string
<p><br></p>
$custom_report_error
<h1 class='mgr-page-title'><b>Your Monthly Sales Performance Snapshots</b></h1>
<p><br></p>

<p class="well">If any months are not listed below, then that means they had no orders within the selected date range and were skipped.</p>
<p><br></p>
$scm_order_report_string
<p><br><br></p>
~;

    print &$manager_page_footer;

}

#######################################################################
#
# added from old v5 & v6 custom order manager
# by Mister Ed - Sept 17, 2011
#######################################################################

sub display_sales_snapshot_selection_screen {

    print &$manager_page_header( "Sales Snapshot - Date Range Selection", '', '', '', '' );

    print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Annual &amp; Monthly Sales Snapshots - Date Range Selection</b></h1>
<p><br></p>

<p class="well">Note: You must have <i>Yearly</i> and/or <i>Monthly</i> order logging enabled for this add-on to work.</p>
<p><br></p>

<div class="table-responsive">
<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$in{'mgr_seshun'}">
<table class="table table-condensed table-striped table-bordered">
<tr>
<td colspan="2" BGCOLOR="#FFCC00" align=center><font size=+2><b>Create Your Sales Performance Snapshot Below</b></font></td>
</tr>
<tr>
<td class="col-sm-6" align="left">
<p><b>Select items to track in your Sales Snapshot</b></p>
<p><small>* not all items below are available by default. Some require other add-ons and customizations in order to initially save the data, such as affiliate sales and COGS totals</small></p>
<p><br></p>

<input type="checkbox" name="numberoforders" value="numberoforders" checked>Total Number of Orders<br>
<input type="checkbox" name="averageordersize" value="averageordersize" checked>Average Order Size<br>
<input type="checkbox" name="highestorder" value="highestorder" checked>Largest Order (by order total)<br>
<input type="checkbox" name="lowestorder" value="lowestorder" checked>Smallest Order (by order total)<br>
<input type="checkbox" name="grosssales" value="grosssales" checked>Total Gross Sales<br>
<input type="checkbox" name="discountsgiven" value="discountsgiven">* Total Discounts Given<br>
<input type="checkbox" name="shipTotal" value="shipTotal" checked>Total Shipping Charges<br>
<input type="checkbox" name="salestaxes" value="salestaxes" checked>Total Sales Taxes<br>
<!--<input type="checkbox" name="salestaxes" value="salestaxes">Sales Taxes by <br>-->
<input type="checkbox" name="sales1taxes" value="sales1taxes">Total Special Tax 1 (if setup)<br>
<input type="checkbox" name="sales2taxes" value="sales2taxes">Total Special Tax 2 (if setup)<br>
<input type="checkbox" name="sales3taxes" value="sales3taxes">Total Special Tax 3 (if setup)<br>
<input type="checkbox" name="netsales" value="netsales" checked>Total Net Sales<br>
<!--<input type="checkbox" name="grosssalesyearly" value="grosssalesyearly" checked>Gross Sales by Year<br>-->
<input type="checkbox" name="COGSitem" value="COGSitem">* Total COGS<br>
<input type="checkbox" name="affiliatetotals" value="affiliatetotals">* Total Affiliate Commissions<br>
<input type="checkbox" name="affiliatenetgentotals" value="affiliatenetgentotals">* Total Affiliate Generated Net Sales<br>

</td>
<td class="col-sm-6" align="left">
<p><b>Select Date Range to Report / View</b></p>
<p class="mgr-center" style="display: block;">
From:
<select name="logreportfrommonth">
$scm_monthlinks
</select>
<select name="logreportfromday">
$scm_daylinks
</select>
<select name="logreportfromyear">
$scm_yearlinks
</select><br>
To: &nbsp;&nbsp;
<select name="logreporttomonth">
<option>$scm_month</option>
$scm_monthlinks
</select>
<select name="logreporttoday">
<option>$scm_day</option>
$scm_daylinks
</select>
<select name="logreporttoyear">
<option>$scm_year</option>
$scm_yearlinks
</select>
</p>

<p><br><br><br></p>

<input type="hidden" name="system_edit_success" value="yes">
<input name="CompileOrderPerformanceSnapshot" type="hidden" value="Submit">
<button class="btn btn-primary mgr-center" style="display: block;">Generate Snapshots</button>

</td>
</tr></table>
<p><br><br><br></p>
ENDOFTEXT

    print &$manager_page_footer;
}

#######################################################################

sub select_cancel_avatax_screen {

    $in{'cart_invoiceNumber'} =~ /([\w\=\+\.]+)/;
    my $inv_number = "$1";

    print &$manager_page_header( "Cancel AvaTax Reporting on Invoice: $inv_number",
        '', '', '', '' );

    if ( ( $sc_avalara_enabled ne 'yes' ) || ( $sc_avalara_tax_enable ne 'yes' ) ) {
        print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Avalara AvaTax Order Cancellation Manager</b></h1>
<p><br></p>

<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
        <h4 class="text-primary mgr-center"><b>Error:</b><br>Sorry, but Avalara and/or AvaTax Calculations are not enabled.</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
<p><br></p>
ENDOFTEXT
    }
    elsif ( $inv_number ) {
    print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Avalara AvaTax Cancellation Manager - For Invoice: $inv_number</b></h1>
<p><br></p>

<p class="well">This section will allow you to cancel the reporting of sales tax in your Avalara account for Invoice# $inv_number.  <b>Canceling</b> your AvaTax reporting for this order does not remove the order from the store's order logs nor removes any actual sales tax liability you might have.</p>
<p><br></p>

<form action="manager.cgi" method="post"><input type="hidden" name="mgr_seshun" value="$mgr_seshun"><br>
<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-warning">
        <h4 class="text-primary mgr-center">Once you cancel the AvaTax amount on this invoice, the cancelled invoice cannot be resubmitted.</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
<INPUT TYPE="hidden" NAME="cart_invoiceNumber" VALUE="$inv_number">
<button name="CancelAvaTaxOrder" class="btn btn-primary btn-lg btn-block mgr-center" value="Submit">Cancel AvaTax Reporting on Invoice# $inv_number</button>

</form>
<p><br><br><br></p>
ENDOFTEXT
    }
    else {
        print <<ENDOFTEXT;
<h1 class='mgr-page-title'><b>Avalara AvaTax Order Cancellation Manager</b></h1>
<p><br></p>

<div class="row col-xs-12 col-sm-12 col-md-12 col-lg-12 hidden-xs">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 bg-danger">
        <h4 class="text-primary mgr-center"><b>Error:</b><br>Sorry, but no invoice number was submitted for this action.</h4>
    </div>
</div>
<div class="row col-xs-12 col-sm-12"><p><br></p></div>
<p><br><br><br></p>
ENDOFTEXT
    }

    print &$manager_page_footer;
}

#######################################################################

sub avalara_cancelRequest($) {

    use AgoraCart::JSON;
    if ( ( $sc_avalara_enabled ne 'yes' ) || ( $sc_avalara_tax_enable ne 'yes' ) ) { return; }
    my $JSON_Body   = shift || die "Missing required parameter 1, JSON body data";
    my $transkey = encode_agc64("$sc_avalara_acct_number:$sc_avalara_license_key");
    my $array_ref = '';

    my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => "0", }, );
    # my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0, SSL_cipher_list => "ALL:!3DES:!DES:!ADH:!SRP:!AESGCM:!SHA256:!SHA384" }, );
    #!SSLv2:!SSLv3:!TLSv1:!TLSv1_1 -- for TLS 1.2
    my $req = HTTP::Request->new(POST => $mgr_avalara_cancel_url);
    $req->content_type('text/json');
    $req->header(Authorization => "Basic $transkey ");
    $req->content($JSON_Body);

  # debug
  if ($sc_avalara_debug_req_and_response =~ /yes/i) {
     print "<br><br>Request:<br>" . $req->as_string;
     print "<br><br>Sending POST to [$sc_avalara_URL]<br>";
  }

  # Avalara Logging
  if ( ( time < $sc_avalara_txn_logging_expire ) && ( $sc_avalara_txn_logging eq 'yes' ) ) {
      $sc_avalara_logging_string .= "\n\nAvaTax Cancel Request String:\n" . $req->as_string;
      $sc_avalara_logging_string .= "\n\nAvaTax Cancel Request Sent To:  $mgr_avalara_cancel_url";
  }

  my $res = $ua->request($req);
  $avatemp_response = decode_json($res->content);
  %avalara_response = %$avatemp_response;

  $array_ref = $avalara_response{'CancelTaxResult'};
  $avalara_cancel_response = $$array_ref{'ResultCode'};

  if ( $response =~ /Error|Warning|Exception/i ) {
      my $array_ref2 = $$array_ref{'Messages'}->[0];
      $avalara_cancel_error_message = $avalara_cancel_response . ' ' . $$array_ref2{'Summary'};
  }


  # debug
  if ($sc_avalara_debug_req_and_response =~ /yes/i) {
     print "<br><br>\$transkey = $transkey<br><br>";
     print "<br><br>Response:<br>" . $res->as_string;
     for my $keys45 (sort keys(%avalara_response)) {
         print "<br><br>\$avalara_response{$keys45} = $avalara_response{$keys45}";
     }
     print '<br><br>';
  }

  # Avalara Logging
  if ( ( time < $sc_avalara_txn_logging_expire ) && ( $sc_avalara_txn_logging eq 'yes' ) ) {
      $sc_avalara_logging_string .= "\n\nCancellation Errors (if any): $avalara_cancel_error_message";
      $sc_avalara_logging_string .= "\n\nAvalara Cancellation Response:\n" . $res->as_string;
      &avalara_logging;
  }


}

#######################################################################

sub cancel_individual_avatax_order {

    $in{'cart_invoiceNumber'} =~ /([\w\=\+\.]+)/;
    my $inv_number = "$1";
    my $font_color = 'green';
    my $JSON_Body = qq|
    {
        "CompanyCode": "$avalara_company_code",
        "DocType": "SalesInvoice",
        "DocCode": "$inv_number",
        "CancelCode": "DocVoided"
    }
|;
    print &$manager_page_header( "Cancelled AvaTax Reporting on Invoice: $inv_number",
        '', '', '', '' );

    &avalara_cancelRequest($JSON_Body);

    if ( $avalara_cancel_error_message ) {
        $avalara_cancel_response = '<br>' . $avalara_cancel_error_message;
        $font_color = 'red';
    }

    print '<h2>Status Cancellation Request (Invoice #' . $inv_number . '):<br><br><font color="' . $font_color . '">' . $avalara_cancel_response . '</font><h2><br><br>';

    print &$manager_page_footer;
}

#######################################################################

sub avalara_logging {

    if ( ( time > $sc_avalara_txn_logging_expire ) || ( $sc_avalara_txn_logging ne 'yes' ) ) { return; }

    my $date = get_date();
    my $log_entry = 'Date: ' . $date . "\n";
    $log_entry .= 'Log Timestamp: ' . time;
    $log_entry .= $sc_avalara_logging_string;
    $log_entry .= "\n\n ################################################################################################################ \n\n";

    get_file_lock("$sc_avalara_log_path.lockfile");
    open( AVALARA_LOG, ">>$sc_avalara_log_path" )
      || CgiDie("Can't open the Avalara Logging File.");
    print AVALARA_LOG "$log_entry\n";
    close(AVALARA_LOG);

    release_file_lock("$sc_avalara_log_path.lockfile");
}

#######################################################################

1;
