<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
/* Function : Estimate and Proposal Inquiry
*****************************************/
$page_security = 'CRM_CUSTOMERS';
$path_to_root = "../../..";
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/db/sales_db.inc");

set_page_security( @$_POST['order_view_mode'],
	array(	'OutstandingOnly' => 'SA_SALESDELIVERY',
			'InvoiceTemplates' => 'SA_SALESINVOICE',
			'DeliveryTemplates' => 'SA_SALESDELIVERY',
			'PrepaidOrders' => 'SA_SALESINVOICE'),
	array(	'OutstandingOnly' => 'SA_SALESDELIVERY',
			'InvoiceTemplates' => 'SA_SALESINVOICE',
			'DeliveryTemplates' => 'SA_SALESDELIVERY',
			'PrepaidOrders' => 'SA_SALESINVOICE')
);

if (get_post('trans_type'))
	$trans_type = $_POST['trans_type'];
if (isset($_GET['type']) && $_GET['type'] == ST_SALESESTIMATE)
	$trans_type = $_POST['trans_type'] = ST_SALESESTIMATE;
elseif (isset($_GET['type']) && $_GET['type'] == ST_SALESPROPOSAL)
	$trans_type = $_POST['trans_type'] = ST_SALESPROPOSAL;
if(isset($_SESSION['wa_current_user']->type)) {
	$_POST['customer_id'] = $_SESSION['wa_current_user']->person;
	//echo '<style> #delete { display : none; } </style>';	
} elseif(isset($_GET['customer_id']))
	$_POST['customer_id'] = $_GET['customer_id'];
//display_error($_GET['customer_id']);
if ($trans_type == ST_SALESESTIMATE){
	$_POST['order_view_mode'] = _("Estimate");
	$_SESSION['page_title'] = _($help_context = "Search All Estimates");	
}else{
	$_POST['order_view_mode'] = _("Proposals");
	$_SESSION['page_title'] = _($help_context = "Search All Proposals");
}

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 600);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page($_SESSION['page_title'], false, false, "", $js);
//---------------------------------------------------------------------------------------------
//	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['trans_type'] == 0
			&& date1_greater_date2(Today(), sql2date($row['delivery_date']))
			&& ($row['TotDelivered'] < $row['TotQuantity']));
}

function view_link($dummy, $order_no){

	global $trans_type;

	return  crm_get_customer_trans_view_str($trans_type, $order_no);
}

function prt_link($row)
{
	global $trans_type;
	return crm_print_document_link($row['order_no'], _("Print"), true, $trans_type, ICON_PRINT);
}

function edit_link($row) {
	
	if (crm_is_prepaid_order_open($row['order_no']))
		return '';

	return  crm_trans_editor_link($row['trans_type'], $row['order_no']);
}

function order_link($row){
	global $trans_type;
 	if($trans_type == ST_SALESESTIMATE) 
 		return pager_link( _("Sales Order"),"/modules/KvcodesCRM/estimates.php?NewEstimateToSalesOrder=" .$row['order_no'], ICON_DOC);
 	elseif($trans_type == ST_SALESPROPOSAL)
 		return pager_link( _("Sales Order"),"/modules/KvcodesCRM/estimates.php?NewProposalToSalesOrder=" .$row['order_no'], ICON_DOC);
}


$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');
}

start_form();

start_table(TABLESTYLE_NOBORDER);
start_row();
ref_cells(_("#:"), 'OrderNumber', '',null, '', true);
//display_error($_POST['type']);
//if (!$page_nested)
	//types_list_cells(_("Select a Type"), 'type', null, true, true);

if ($show_dates)
{
  	date_cells(_("from:"), 'OrdersAfterDate', '', null, -user_transaction_days());
  	date_cells(_("to:"), 'OrdersToDate', '', null, 1);
}
locations_list_cells(_("Location:"), 'StockLocation', null, true, true);

if($show_dates) {
	end_row();
	end_table();

	start_table(TABLESTYLE_NOBORDER);
	start_row();
}
stock_items_list_cells(_("Item:"), 'SelectStockFromList', null, true, true);

if (!$page_nested && !isset($_SESSION['wa_current_user']->type))
	customer_list_cells(_("Select a customer: "), 'customer_id', null, true, true);
//else
	//hidden('customer_id', $_POST['customer_id']);
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('trans_type', $_POST['trans_type']);

end_row();

end_table(1);

//------------------------------------------------------------------------------------------------
$filters = array('`sorder`.`trans_type`' => $_POST['trans_type']); //array('`lead`.`is_converted`' => 0 );
/*if(get_post('lead_id')){
	$filters['`lead`.`lead_id`'] = get_post('lead_id');
}*/
/*if(get_post('show_inactive')){
	unset($filters['`lead`.`is_converted`']);
}*/
if(get_post('lead_source_id')){
	$filters['`lead`.`lead_source_id`'] 	= get_post('lead_source_id');
}
if(get_post('industry_id')){
	$filters['`lead`.`industry_id`'] 	= get_post('industry_id');
}
if(get_post('lead_status_id')){
	$filters['`lead`.`lead_status_id`'] 	= get_post('lead_status_id');
}

if(get_post('customer_id')){
	$filters['`sorder`.`debtor_no`'] 		= get_post('customer_id');
}

//---------------------------------------------------------------------------------------------
//	Orders inquiry table
//

$sql = GetDataJoin('kv_crm_sales_orders AS sorder', array( 
	0 => array('join' => 'LEFT', 'table_name' => 'debtors_master AS debtor', 'conditions' => '`debtor`.`debtor_no` = `sorder`.`debtor_no`'),
	1 => array('join' => 'LEFT', 'table_name' => 'kv_crm_leads AS lead', 'conditions' => '`lead`.`lead_id` = `sorder`.`debtor_no`'), 
	//2 => array('join' => 'LEFT', 'table_name' => 'kv_crm_picklist_values AS industry', 'conditions' => '`lead`.`industry_id` = `industry`.`id`'), 
	//3 => array('join' => 'LEFT', 'table_name' => 'kv_crm_picklist_values AS status', 'conditions' => '`lead`.`lead_status_id` = `status`.`id`'), 
	
	), array('`sorder`.`order_no`, IF(`sorder`.`formType` = 1, CONCAT(`lead`.`first_name`, `lead`.`last_name`), debtor.name ) AS name, `sorder`.`customer_ref`, `sorder`.`ord_date`, `sorder`. `delivery_date`, `sorder`. `deliver_to`, IF(`sorder`.`formType` = 1, `lead`.`curr_code`, `debtor`.`curr_code` ) AS `curr_code`, `sorder`.`total`, `sorder`.`trans_type`'), $filters, null, false, false, true);

/* $sql = crm_get_sql_for_sales_orders_view($trans_type, get_post('OrderNumber'), get_post('order_view_mode'),
	get_post('SelectStockFromList'), get_post('OrdersAfterDate'), get_post('OrdersToDate'), get_post('StockLocation'), get_post('customer_id'));*/
//display_error($sql);
if ($trans_type == ST_SALESESTIMATE)
	$cols = array(
		_("Estimate #") => array('fun'=>'view_link', 'align'=>'right'),		
		_("Customer") => array('type' => 'debtor.name' , 'ord' => ''),		
		_("Cust Estimate Ref"),
		_("Estimate Date") => array('type' =>  'date', 'ord' => ''),
		_("Required By") =>array('type'=>'date', 'ord'=>''),
		_("Delivery To"), 
		_("Currency") => array('align'=>'center'),
		_("Estimate Total") => array('type'=>'amount', 'ord'=>''),
		'Type' => 'skip'		
	);
else
	$cols = array(
		_("Proposal #") => array('fun'=>'view_link', 'align'=>'right'),		
		_("Customer/Lead"),
		_("Cust Proposal Ref"),
		_("Proposal Date") =>array('type'=>'date', 'ord'=>''),
		_("Valid until") =>array('type'=>'date', 'ord'=>''),
		_("Delivery To"), 
		_("Currency") => array('align'=>'center'),
		_("Proposal Total") => array('type'=>'amount', 'ord'=>''),
		'Type' => 'skip'		
	);
if ($trans_type == ST_SALESESTIMATE || $trans_type == ST_SALESPROPOSAL) {
	
	if(!isset($_SESSION['wa_current_user']->type)) {
		$options_array = array(
					array('insert'=>true, 'fun'=>'edit_link'),
					array('insert'=>true, 'fun'=>'order_link'),
					array('insert'=>true, 'fun'=>'prt_link'));
	} else {
		$options_array = array(array('insert'=>true, 'fun'=>'prt_link'));	
	}
	 array_append($cols,$options_array);
} 


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

$table->width = "80%";

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

end_form();
end_page();
