<?php
/**********************************************************************
***********************************************************************/
$path_to_root = "../..";

include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.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 . "/sales/includes/db/sales_inquiry_db.inc");


$page_security = 'SA_OUTSTANDING_SALES_ORDERS_INQ';


//
//if (isset($_GET['ApproveOrdersMode']) && ($_GET['ApproveOrdersMode'] == true)){
//    if (isset($_GET['type']) && ($_GET['type'] == ST_SALESQUOTE)){
//        $trans_type = ST_SALESQUOTE;
//        set_page_security( $trans_type, array(	ST_SALESQUOTE => 'SA_APPROVE_SALES_QUOTES'), array(	'ApproveOrdersMode' => 'SA_APPROVE_SALES_QUOTES'));
//    }
//    else{
//        $trans_type = ST_SALESORDER;
//        set_page_security( $trans_type, array(	ST_SALESORDER => 'SA_APPROVE_SALES_ORDERS'), array(	'ApproveOrdersMode' => 'SA_APPROVE_SALES_ORDERS'));
//    }
//}
//elseif (isset($_GET['OutstandingOnly']) && ($_GET['OutstandingOnly'] == true)){
//    if (isset($_GET['type']) && ($_GET['type'] == ST_SALESINVOICE)){
//        $trans_type = ST_SALESINVOICE;
//        set_page_security( $trans_type, array(ST_SALESINVOICE => 'SA_SALESINVOICE'), array(	'OutstandingOnly' => 'SA_SALESINVOICE'));
//    }
//}
//else{
//     set_page_security( @$_POST['order_view_mode'],
//        array(	'OutstandingOnly' => 'SA_SALESDELIVERY',
//                'InvoiceTemplates' => 'SA_SALESINVOICE'),
//        array(	'OutstandingOnly' => 'SA_SALESDELIVERY',
//                'InvoiceTemplates' => 'SA_SALESINVOICE')
//    );
//}
//
//
//if (get_post('type')){
//	$trans_type = $_POST['type'];
//}
//elseif (isset($_GET['type']) && $_GET['type'] == ST_SALESQUOTE){
//	$trans_type = ST_SALESQUOTE;
//}
//else{
//	$trans_type = ST_SALESORDER;
//}
//
//if ($trans_type == ST_SALESORDER)
//{
//	if (isset($_GET['OutstandingOnly']) && ($_GET['OutstandingOnly'] == true))
//	{
//		$_POST['order_view_mode'] = 'OutstandingOnly';
//		$_SESSION['page_title'] = _($help_context = "Search Outstanding Sales Orders");
//	}
//	elseif (isset($_GET['InvoiceTemplates']) && ($_GET['InvoiceTemplates'] == true))
//	{
//		$_POST['order_view_mode'] = 'InvoiceTemplates';
//		$_SESSION['page_title'] = _($help_context = "Search Template for Invoicing");
//	}
//	elseif (isset($_GET['DeliveryTemplates']) && ($_GET['DeliveryTemplates'] == true))
//	{
//		$_POST['order_view_mode'] = 'DeliveryTemplates';
//		$_SESSION['page_title'] = _($help_context = "Select Template for Delivery");
//	}
//    elseif (isset($_GET['ApproveOrdersMode']) && ($_GET['ApproveOrdersMode'] == true))
//	{
//		$_POST['order_view_mode'] = 'ApproveOrdersMode';
//		$_SESSION['page_title'] = _($help_context = "Approve Sales Orders");
//	}
//	elseif (!isset($_POST['order_view_mode']))
//	{
//		$_POST['order_view_mode'] = false;
//		$_SESSION['page_title'] = _($help_context = "Search All Sales Orders");
//	}
//}
//else
//{
//    if (isset($_GET['ApproveOrdersMode']) && ($_GET['ApproveOrdersMode'] == true))
//	{
//		$_POST['order_view_mode'] = 'ApproveOrdersMode';
//		$_SESSION['page_title'] = _($help_context = "Approve Sales Quotations");
//	}
//    else{
//        $_POST['order_view_mode'] = "Quotations";
//        $_SESSION['page_title'] = _($help_context = "Search All Sales Quotations");
//    }
//}


$_SESSION['page_title'] = _($help_context = "Search All Sales Orders");


$js = "";
if ($SysPrefs->use_popup_windows)
        $js .= get_js_open_window(900, 600);
if (user_use_date_picker())
        $js .= get_js_date_picker();
page($help_context = "Outstanding Sales Orders", false, false, "", $js);


if (isset($_GET['selected_customer']))
{
	$selected_customer = $_GET['selected_customer'];
}
elseif (isset($_POST['selected_customer']))
{
	$selected_customer = $_POST['selected_customer'];
}
else
	$selected_customer = -1;

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

if (isset($_POST['SelectStockFromList']) && ($_POST['SelectStockFromList'] != "") &&
	($_POST['SelectStockFromList'] != ALL_TEXT))
{
 	$selected_stock_item = $_POST['SelectStockFromList'];
}
else
{
	unset($selected_stock_item);
}
//---------------------------------------------------------------------------------------------
//	Query format functions
//
function check_overdue($row)
{
	global $trans_type;
	if ($trans_type == ST_SALESQUOTE)
		return (date1_greater_date2(Today(), sql2date($row['delivery_date'])));
	else
		return ($row['type'] == 0
			&& date1_greater_date2(Today(), sql2date($row['delivery_date']))
			&& ($row['TotDelivered'] < $row['TotQuantity']));
}

function view_link($dummy, $order_no)
{
	global $trans_type;
	return  get_customer_trans_view_str($trans_type, $order_no);
}


//function edit_link($row) 
//{
//	if (@$_GET['popup'])
//		return '';
//	global $trans_type;
//	$modify = ($trans_type == ST_SALESORDER ? "ModifyOrderNumber" : "ModifyQuotationNumber");
//        if($row['approval_status'] == AS_NEW || $row['approval_status'] == AS_AWAITING_APPROVAL || $row['approval_status'] == AS_WITH_THE_APPROVER || 
//                $row['approval_status'] == AS_REOPENED)
//        {
//            return pager_link( _("Edit"),"/sales/sales_order_entry.php?$modify=" . $row['order_no'], ICON_EDIT);
//        }
//        else 
//        {
//            return null;
//        }
//}


function invoice_link($row)
{
	global $trans_type;
	if ($trans_type == ST_SALESORDER){
        if($row['approval_status'] == AS_APPROVED)
        {
            //return pager_link( _("Dispatch"),"/sales/customer_delivery.php?OrderNumber=" .$row['order_no'], ICON_DOC);
            return pager_link( _("Invoice"),"/sales/customer_invoice.php?OrderNumber=" .$row['order_no'], ICON_DOC);
        }
        else 
        {
            return null;
        }
    }
  	else{		
  		return pager_link( _("Sales Order"),"/sales/sales_order_entry.php?OrderNumber=" .$row['order_no'], ICON_DOC);
    }
}


function _reference($row)
{
    return $row['reference'];
}


function _order_date($row)
{
    return sql2date($row['ord_date']);
}

function _delivery_date($row)
{
    return sql2date($row['delivery_date']);
}

function _deliver_to($row)
{
    return $row['deliver_to'];
}

function _OrderValue($row)
{
    return number_format($row['OrderValue'],2);
}

function _curr_code($row)
{
    return $row['curr_code'];
}


//function dispatch_link($row)
//{
//	global $trans_type;
//	if ($trans_type == ST_SALESORDER){
//  		return pager_link( _("Dispatch"),"/sales/sales_order_entry.php?NewInvoice=" .$row["order_no"], ICON_DOC);
//    }
//	else{
//        return '';
//    }
//}

//function delivery_link($row)
//{
//  return pager_link( _("Delivery"),"/sales/sales_order_entry.php?NewDelivery=" .$row['order_no'], ICON_DOC);
//}

//function order_link($row)
//{
//    if($row['approval_status'] == AS_APPROVED || $row['approval_status'] == AS_ORDERED){
//        return pager_link( _("Sales Order"),"/sales/sales_order_entry.php?NewQuoteToSalesOrder=" .$row['order_no'], ICON_DOC);
//    }
//    else{
//        return null;
//    }
//}



//function status_link($row)
//{
//    global $document_approval_statuses;
//
//    return $document_approval_statuses[$row['approval_status']];
//    
//}


//function purchase_link($row)
//{
//    if($row['closed_for_prs'] == 1){
//        return pager_link(_("---"), "/sales/sales_order_pr.php?OrderNumber=" . $row["order_no"], null);
//    }
//    else{
//        return pager_link(_("Purchase"), "/sales/sales_order_pr.php?OrderNumber=" . $row["order_no"], null);
//    }
//}

//function tmpl_checkbox($row)
//{
//	global $trans_type;
//	if ($trans_type == ST_SALESQUOTE)
//		return '';
//	if (@$_GET['popup'])
//		return '';
//	$name = "chgtpl" .$row['order_no'];
//	$value = $row['type'] ? 1:0;
//
//// save also in hidden field for testing during 'Update'
//
// return checkbox(null, $name, $value, true,
// 	_('Set this order as a template for direct deliveries/invoices'))
//	. hidden('last['.$row['order_no'].']', $value, false);
//}
//---------------------------------------------------------------------------------------------
// Update db record if respective checkbox value has changed.
//
//function change_tpl_flag($id)
//{
//	global	$Ajax;
//	
//  	$sql = "UPDATE ".TB_PREF."sales_orders SET type = !type WHERE order_no=$id";
//
//  	db_query($sql, "Can't change sales order type");
//	$Ajax->activate('orders_tbl');
//}

$id = find_submit('_chgtpl');
if ($id != -1)
	change_tpl_flag($id);

if (isset($_POST['Update']) && isset($_POST['last'])) {
	foreach($_POST['last'] as $id => $value)
		if ($value != check_value('chgtpl'.$id))
			change_tpl_flag($id);
}

//$show_dates = !in_array($_POST['order_view_mode'], array('OutstandingOnly', 'InvoiceTemplates', 'DeliveryTemplates'));
//---------------------------------------------------------------------------------------------
//	Order range form
//
//if (get_post('_OrderNumber_changed') || get_post('_OrderReference_changed')) // enable/disable selection controls
//{
//	$disable = get_post('OrderNumber') !== '' || get_post('OrderReference') !== '';
//
//  	if ($show_dates) {
//			$Ajax->addDisable(true, 'OrdersAfterDate', $disable);
//			$Ajax->addDisable(true, 'OrdersToDate', $disable);
//	}
//
//	$Ajax->activate('orders_tbl');
//}

$Ajax->activate('orders_tbl');

	start_form();

//if(isset($page_security) && $page_security != ''){
//    $_POST['PAGE_SECURITY'] = $page_security;
//}

hidden('PAGE_SECURITY',$page_security);

start_table(TABLESTYLE_NOBORDER);
start_row();
        ref_cells(text_bold("Order #:"), 'OrderNumber', '',null, '', true);
        ref_cells(text_bold("Reference"), 'OrderReference', '',null, '', true);

  	date_cells(_("from:"), 'OrdersAfterDate', '', null, -500);
  	date_cells(_("to:"), 'OrdersToDate', '', null, 1);

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


	end_row();
	end_table();

	start_table(TABLESTYLE_NOBORDER);
	start_row();

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

customer_list_cells(_("Select a customer: "), 'customer_id', null, true, true);
//if ($trans_type == ST_SALESQUOTE)
//	check_cells(_("Show All:"), 'show_all');

submit_cells('SearchOrders', _("Search"),'',_('Select documents'), 'default');
//hidden('order_view_mode', $_POST['order_view_mode']);
//hidden('type', $trans_type);

end_row();

end_table(1);
//---------------------------------------------------------------------------------------------
//	Orders inquiry table
//

$trans_type = ST_SALESORDER;
$sql = get_sql_for_outstanding_sales_orders_inquiry($selected_customer, $trans_type, $_POST['OrderNumber'], 
	@$selected_stock_item, @$_POST['OrdersAfterDate'], @$_POST['OrdersToDate'], 
        @$_POST['OrderReference'], $_POST['StockLocation'], $_POST['customer_id']);

	$cols = array(
                        _("Order #") => array('fun'=>'view_link'),
                        _("Ref") => array('fun' => '_reference') ,
                        _("Cat. Ref."),            
                        _("Customer") => array('type' => 'debtor.name') ,
                        _("Branch"), 
                        _("Cust Order Ref"),
                        _("Order Date") => array('fun' =>  '_order_date', 'align'=>'center'),
                        _("Required By") =>array('fun' =>  '_delivery_date', 'align'=>'center'),
                        _("Delivery To") => array('fun' => '_deliver_to'), 
                        _("Order Total") => array('fun'=>'_OrderValue', 'align'=>'right'),
                        _("Currency") => array('fun'=>'_curr_code', 'align'=>'center'),

		array('insert'=>true, 'fun'=>'invoice_link'));


$table =& new_db_pager('orders_tbl', $sql, $cols);
$table->set_marker('check_overdue', _("Marked items are overdue."));

$table->width = "90%";

display_db_pager($table);
submit_center('Update', _("Update"), true, '', null);

if (!@$_GET['popup'])
{
	end_form();
	end_page();
}
?>
