<?php

$path_to_root="../..";
include_once($path_to_root . "/sales/includes/cart_class.inc");
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/taxes/tax_calc.inc");
include_once($path_to_root . "/admin/db/shipping_db.inc");

$page_security = 'SA_SALESTRANSVIEW';


$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 600);
if (user_use_date_picker())
	$js .= get_js_date_picker();

if (isset($_GET['OutstandingOnly']) && ($_GET['OutstandingOnly'] == true))
{
	$_POST['OutstandingOnly'] = true;
	page(_($help_context = "Search Not Invoiced Deliveries"), false, false, "", $js);
}
else
{
	$_POST['OutstandingOnly'] = false;
	page(_($help_context = "Search All Deliveries"), false, false, "", $js);
}

//-----------------------------------------------------------------------------------
if (get_post('SearchOrders')) 
{
	
	$Ajax->activate('Items');
}
//-----------------------------------------------------------------------------

function copy_from_cart()
{
	$cart = &$_SESSION['Items'];
 	$_POST['Comments']= $cart->Comments;
	$_POST['InvoiceDate']= $cart->document_date;
 	$_POST['ref'] = $cart->reference;
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['due_date'] = $cart->due_date;
 	$_POST['payment'] = $cart->payment;
	if (!$_SESSION['Items']->is_prepaid())
	{
		$_POST['ship_via'] = $cart->ship_via;
		$_POST['ChargeFreightCost'] = price_format($cart->freight_cost);
	}
	$_POST['dimension_id'] = $cart->dimension_id;
	$_POST['dimension2_id'] = $cart->dimension2_id;
}

//-----------------------------------------------------------------------------
function display_customer_summary($customer_record)
{
	$past1 = get_company_pref('past_due_days');
	$past2 = 2 * $past1;
    if ($customer_record["dissallow_invoices"] != 0)
    {
    	echo "<center><font color=red size=4><b>" . _("CUSTOMER ACCOUNT IS ON HOLD") . "</font></b></center>";
    }

	$nowdue = "1-" . $past1 . " " . _('Days');
	$pastdue1 = $past1 + 1 . "-" . $past2 . " " . _('Days');
	$pastdue2 = _('Over') . " " . $past2 . " " . _('Days');

    start_table(TABLESTYLE, "width='80%'");
    $th = array(_("Currency"), _("Terms"), _("Current"), $nowdue,
    	$pastdue1, $pastdue2, _("Total Balance"));
    table_header($th);

	start_row();
    label_cell($customer_record["curr_code"]);
    label_cell($customer_record["terms"]);
	amount_cell($customer_record["Balance"] - $customer_record["Due"]);
	amount_cell($customer_record["Due"] - $customer_record["Overdue1"]);
	amount_cell($customer_record["Overdue1"] - $customer_record["Overdue2"]);
	amount_cell($customer_record["Overdue2"]);
	amount_cell($customer_record["Balance"]);
	end_row();

	end_table();
}
//-----------------------------------------------------------------------------------


start_form(false, false, $_SERVER['PHP_SELF'] ."?OutstandingOnly=".$_POST['OutstandingOnly']);

start_table(TABLESTYLE_NOBORDER);
start_row();
ref_cells(_("#:"), 'DeliveryNumber', '',null, '', true);
date_cells(_("Date:"), 'DeliveryAfterDate', '', null, 0);
//date_cells(_("to:"), 'DeliveryToDate', '', null, 1);

locations_list_cells(_("Location:"), 'StockLocation', null, true);

end_row();

end_table();
start_table(TABLESTYLE_NOBORDER);
start_row();

stock_items_list_cells(_("Item:"), 'SelectStockFromList', null, true);

//customer_list_cells(_("Select a customer: "), 'customer_id', null, true, true);

submit_cells('SearchOrders', _("Reload"),'',_('Select documents'), 'default');

hidden('OutstandingOnly', $_POST['OutstandingOnly']);

end_row();

end_table(1);

//------------------------------------------------------------------------------------------------
div_start('totals_tbl');
if ($_POST['customer_id'] != "" && $_POST['customer_id'] != ALL_TEXT)
{
	$customer_record = get_customer_details(get_post('customer_id'), get_post('TransToDate'));
    display_customer_summary($customer_record);
    echo "<br>";
}
div_end();

//------------------------------------------------------------------------------------------------



function trans_view($trans, $trans_no)
{
	return get_customer_trans_view_str(ST_CUSTDELIVERY, $trans['trans_no']);
}

function batch_checkbox($row)
{
	$name = "Sel_" .$row['trans_no'];
	return $row['Done'] ? '' :
		"<input type='checkbox' name='$name' value='1' >"
// add also trans_no => branch code for checking after 'Batch' submit
	 ."<input name='Sel_[".$row['trans_no']."]' type='hidden' value='"
	 .$row['branch_code']."'>\n";
}

function edit_link($row)
{
	return $row["Outstanding"]==0 ? '' :
		trans_editor_link(ST_CUSTDELIVERY, $row['trans_no']);
}

function prt_link($row)
{
	return print_document_link($row['trans_no'], _("Print"), true, ST_CUSTDELIVERY, ICON_PRINT);
}

function invoice_link($row)
{
	return $row["Outstanding"]==0 ? '' :
		pager_link(_('Invoice'), "/sales/customer_invoice.php?DeliveryNumber=" 
			.$row['trans_no'], ICON_DOC);
}

function check_overdue($row)
{
   	return date1_greater_date2(Today(), sql2date($row["due_date"])) && 
			$row["Outstanding"]!=0;
}
//------------------------------------------------------------------------------------------------
$sql = get_sql_for_day_sales_deliveries_view(get_post('DeliveryAfterDate'), get_post('customer_id'),	
	get_post('SelectStockFromList'), get_post('StockLocation'), get_post('DeliveryNumber'), false);
$result = db_query($sql,"could not get customer deliveries");

$is_batch_invoice = FALSE;



//-----------------------------------------------------------------------------------
div_start('Items');
start_table(TABLESTYLE, "width='80%'");
$th = array(_("Delivery #"),_("Item Code"), _("Item Description"), _("Issued"),  _("Sold"),
		_("Not sold"), _("Price"),  _("Total Sale"));
$del_no = get_day_delivery(get_post('customer_id'),get_post('DeliveryAfterDate'));
echo '<tr>';
if($del_no == 0){
    label_cell(popup_pager_link(_('Issue to DSR'), "/sales/sales_order_entry.php?NewDelivery=0&customer_id=".get_post('customer_id')."&OrderDate".get_post('DeliveryAfterDate')));
} else {
    label_cell(popup_pager_link(_('Issue to DSR'), "/sales/edit_day_deliveries.php?ModifyDelivery=".$del_no));
}

label_cell(popup_pager_link(_('Today Sale'), "/sales/delivery_invoice.php?DeliveryNumber=".$del_no));
echo '</tr>';
table_header($th);

$cust_total = 0;
$dn_line_cnt = 0;
while ($myrow = db_fetch($result)) {
            
        alt_table_row_color($k);
        label_cell(trans_view($myrow, $myrow['trans_no']));
        view_stock_status_cell($myrow['stock_id']);

        label_cell($myrow['description']);

        //$dec = get_qty_dec($myrow['stock_id']);
        qty_cell($myrow['qty_dispatched'], false);
        qty_cell($myrow['qty_done'], false);
        qty_cell(($myrow['qty_dispatched'] - $myrow['qty_done']), false);
        $line_total = ($myrow['qty_done']  * $myrow['price'] );

        amount_cell($myrow['price']);
        amount_cell($line_total);
//        label_cell(popup_pager_link(_('Invoice'), "/sales/customer_invoice.php?DeliveryNumber=" 
//                        .$myrow['trans_no'], ICON_DOC));
        $cust_total += $line_total;
        end_row();
}
/*Don't re-calculate freight if some of the order has already been delivered -
depending on the business logic required this condition may not be required.
It seems unfair to charge the customer twice for freight if the order
was not fully delivered the first time ?? */


$colspan = 7;

$display_sub_total = price_format($cust_total);

label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right", $is_batch_invoice ? 2 : 0);

//$taxes = $_SESSION['Items']->get_taxes(input_num('ChargeFreightCost'));
//$tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['Items']->tax_included, $is_batch_invoice ? 2 : 0);

$display_total = price_format($cust_total);

label_row(_("Customer Days Total"), $display_total, "colspan=$colspan align=right","align=right", $is_batch_invoice ? 2 : 0);

end_table(1);
div_end();

end_form();
end_page();