<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/sales/includes/display_sales_quotation_class.inc");
include_once($path_to_root . "/includes/inventory.inc");

//--------------------------------------------------------------------------------
function add_to_save_sales_quotation(&$order, $new_item, $new_item_qty, 
                    $price, $discount, $description='', 
                    $tran_unit = '', $tran_qty = 0, $convertion_factor = 1, 
                    $order_unit_price =0, $kit_parent ='')
//        $cart, get_post('stock_id'), input_num('tran_qty') / $convesion_factor,
//            input_num('tran_unit_price_'.$line_no) / $convesion_factor, input_num('Disc') / 100, get_post('stock_id_text'), 
//            $tran_unit, input_num('tran_qty'), $convesion_factor,
//            input_num('tran_unit_price_'.$id));
{
	// calculate item price to sum of kit element prices factor for 
	// value distribution over all exploded kit items
	$std_price = get_kit_price($new_item, $order->customer_currency, 
                                    $order->sales_type,	$order->price_factor, get_post('OrderDate'), true, $tran_unit);

	if ($std_price == 0){
                $price_factor = 0;
        }
	else{
                    $price_factor = $price/$std_price;
        }

	$kit = get_item_kit($new_item);
	$item_num = db_num_rows($kit);

	while($item = db_fetch($kit)) {
		$std_price = get_kit_price($item['stock_id'], $order->customer_currency, 
                            $order->sales_type,	$order->price_factor, get_post('OrderDate'), true, $tran_unit);

		// rounding differences are included in last price item in kit
		$item_num--;
		if ($item_num) {
			$price -= $item['quantity']*$std_price*$price_factor;
			$item_price = $std_price*$price_factor;
		} 
                else {
                        if ($item['quantity']){ 
				$price = $price/$item['quantity'];
                        }
			$item_price = $price;
		}
		$item_price = round($item_price, user_price_dec());

                if (!$item['is_foreign'] && $item['item_code'] != $item['stock_id']){	// this is sales kit - recurse 
                        $kit_comp_stock_id =  $item['stock_id'];
                        $kit_comp_convertion_factor = 1;
                        $kit_comp_qty =  $new_item_qty * $item['quantity'] * $kit_comp_convertion_factor;
                        $kit_comp_unit_price = $item_price;
                        $kit_comp_description =  $item['comp_name'];
                        $kit_comp_info = get_item_edit_info($kit_comp_stock_id);
                        $kit_comp_tran_qty =  $new_item_qty * $item['quantity'];
                        $kit_comp_tran_unit_price = $item_price * $kit_comp_convertion_factor;
                        $kit_parent =  $item['item_code'];

                        add_to_order($order, $kit_comp_stock_id, $kit_comp_qty,
                            $kit_comp_unit_price, $discount, $kit_comp_description, 
                            $kit_comp_info['units'], $kit_comp_tran_qty, $kit_comp_convertion_factor,
                            $kit_comp_tran_unit_price, $kit_parent);
                }
                else{	// stock item record eventually with foreign code
                        // check duplicate stock item
                        foreach ($order->line_items as $order_item)
                        {
                                if (strcasecmp($order_item->stock_id, $item['stock_id']) == 0)
                                {
        //				display_warning(_("For Part :").$item['stock_id']. " ". _("This item is already on this document. You have been warned."));
                                        break;
                                }
                        }
                        $line_no = count($order->line_items);
                        $order->add_to_save_sales_quotation_cart ($line_no,	$item['stock_id'], 
                                        $new_item_qty*$item['quantity'], $item_price, $discount, 0,0, $description, 0, 0, 0,
                                        $tran_unit, $tran_qty, $convertion_factor);

                        $order->line_items[$line_no]->tran_unit_price = $order_unit_price;
                        $order->line_items[$line_no]->kit_parent = $kit_parent;
                }
	}

}

function update_to_save_sales_quotation(&$order, $row_id, $stock_id, $base_unit_qty, 
                    $base_unit_price, $discount, $description='', 
                    $tran_unit = '', $tran_qty = 0, $convertion_factor = 1, 
                    $order_unit_price =0, $kit_parent ='')
{
        $line_no = 0;
        $order->add_to_save_sales_quotation_cart ($line_no,	$stock_id, 
                        $base_unit_qty, $base_unit_price, $discount, 0,0, $description, 0, 0, 0,
                        $tran_unit, $tran_qty, $convertion_factor);

        $order->line_items[$line_no]->tran_unit_price = $order_unit_price;
        $order->line_items[$line_no]->kit_parent = $kit_parent;
        $order->line_items[$line_no]->id = $row_id;
}
//---------------------------------------------------------------------------------

function get_customer_details_to_order(&$order, $customer_id, $branch_id)
{
	global $SysPrefs;
	
	$ret_error = "";

	$myrow = get_customer_to_order($customer_id);

	$name = $myrow['name'];

	if ($myrow['dissallow_invoices'] == 1)
		$ret_error = _("The selected customer account is currently on hold. Please contact the credit control personnel to discuss.");

	$deliver = $myrow['address']; // in case no branch address use company address

	$order->set_customer($customer_id, $name, $myrow['curr_code'], 
		$myrow['discount'], $myrow['payment_terms'], $myrow['pymt_discount']);

	// the sales type determines the price list to be used by default
	$order->set_sales_type($myrow['salestype'], $myrow['sales_type'], $myrow['tax_included'],
	    $myrow['factor']);

	$order->credit = $myrow['cur_credit'];

	if ($order->trans_type != ST_SALESQUOTE && $order->trans_type != ST_SALESQUOTE)
	{
		$order->dimension_id = $myrow['dimension_id'];
		$order->dimension2_id = $myrow['dimension2_id'];
	}
	$result = get_branch_to_order($customer_id, $branch_id);

	if (db_num_rows($result) == 0)
	{
		return _("The selected customer and branch are not valid, or the customer does not have any branches.");
	}

	$myrow = db_fetch($result);

	// FIX - implement editable contact selector in sales order 
	$contact = get_branch_contacts($branch_id, 'order', $customer_id);
	$order->set_branch($branch_id, $myrow["tax_group_id"],
	$myrow["tax_group_name"], @$contact["phone"], @$contact["email"]);

	$address = trim($myrow["br_post_address"]) != '' ? $myrow["br_post_address"]
		: (trim($myrow["br_address"]) != '' ? $myrow["br_address"]:$deliver);

	$order->set_delivery($myrow["default_ship_via"], $myrow["br_name"],
		$address);
	if ($order->trans_type == ST_SALESINVOICE) {
		$order->due_date = get_invoice_duedate($order->payment, $order->document_date);
	}
	elseif ($order->trans_type == ST_SALESQUOTE)
		$order->due_date = add_days($order->document_date, $SysPrefs->default_delivery_required_by());
	if($order->payment_terms['cash_sale']) {
		$order->set_location($order->pos["pos_location"], $order->pos["location_name"]);
	} else
		$order->set_location($myrow["default_location"], $myrow["location_name"]);
		
	return $ret_error;
}

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

function display_sales_quotation_item_details($title, &$order, $editable_items=false)
{
	global $SysPrefs;

        
        
        start_table(TABLESTYLE, "width=95%", 10);
        
	display_heading($title);

        
	start_table(TABLESTYLE, "colspan=7 width=100%");
	$th = array(_("Id"),_("Item Code"), _("Item Description"), _("Tran Quantity"), _("Delivered"),
                _("Tran Unit"), _("List Price"), $order->tax_included ? _("Price after Tax") : _("Price before Tax"), 
                _("Discount %"), _("Min. Price"), _("Total"), "");

	if ($order->order_no == 0) {
            unset( $th[4] );
	}

	if (count($order->line_items))
	     $th[]= '';

	table_header($th);

	$total = 0;
	$k = 0;  //row colour counter

	$id = find_submit('Edit');
	$has_marked = false;

	foreach ($order->get_items() as $line_no=>$stock_item)
//	foreach ($order->get_items() as $stock_item)
	{
                $line_no = $stock_item->id;
                if(list_updated('tran_unit_'.$line_no)){
                    $id = $line_no;
                    $_POST['Edit'.$line_no] = $line_no;
                }
		$line_total = round(($stock_item->tran_qty *  $stock_item->tran_unit_price) * (1 - $stock_item->discount_percent), user_price_dec());

		$qoh_msg = '';
		if (!$editable_items || $id != $line_no)
		{
			if (!$SysPrefs->allow_negative_stock() && is_inventory_item($stock_item->stock_id) && 
				$order->trans_type != ST_SALESQUOTE && $order->trans_type!=ST_SALESQUOTE) {
				$qoh = get_qoh_on_date($stock_item->stock_id, 
					$_POST['Location'], $_POST['delivery_date']);
				if (($stock_item->qty_dispatched -$stock_item->qty_done) > $qoh)
				{
					// oops, we don't have enough of one of the component items
					start_row("class='stockmankobg'");
					$qoh_msg .= $stock_item->stock_id . " - " . $stock_item->item_description . ": " .
					_("Quantity On Hand") . " = " 
					. number_format2($qoh, get_qty_dec($stock_item->stock_id)) . '<br>';
					$has_marked = true;
				 } else 
					alt_table_row_color($k);
			} else {
				alt_table_row_color($k);
			}

                        label_cell($stock_item->id);
                        
			view_stock_status_cell($stock_item->stock_id);

			//label_cell($stock_item->item_description, "nowrap" );
			label_cell($stock_item->item_description );
			$dec = get_qty_dec($stock_item->stock_id);
			qty_cell($stock_item->tran_qty, false, $dec);

			if ($order->order_no!=0)
				qty_cell($stock_item->qty_done, false, $dec);

			label_cell($stock_item->tran_unit);
                        amount_cell($stock_item->list_price);
			amount_cell($stock_item->tran_unit_price);

//			percent_cell($stock_item->discount_percent * 100);
                        label_cell(number_format2($stock_item->discount_percent * 100, 5), "align=right");
            
            //          amount_cell($stock_item->tran_unit_price * (1 - $stock_item->discount_percent));
                        amount_cell($stock_item->minimum_price * $stock_item->convertion_factor);
            
			amount_cell($line_total);

			if ($editable_items)
			{
				edit_button_cell("Edit$line_no", _("Edit"),
				_('Edit document line'));
				delete_button_cell("Delete$line_no", _("Delete"),
				_('Remove line from document'));
			}
			end_row();
		}
		else
		{
			sales_quotation_item_controls($order, $k,  $line_no);
		}

		$total += $line_total;
	}

	if ($id==-1 && $editable_items){
		sales_quotation_item_controls($order, $k);
    }

	$colspan = 8;
	if ($order->order_no!=0)
		++$colspan;
	start_row();
	label_cell(_("Shipping Charge"), "colspan=$colspan align=right");
	small_amount_cells(null, 'freight_cost', price_format(get_post('freight_cost',0)));
	label_cell('', 'colspan=2');
	end_row();
	$display_sub_total = price_format($total + input_num('freight_cost'));
	label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right", 2);
	$taxes = $order->get_taxes(input_num('freight_cost'));
	$tax_total = display_edit_tax_items($taxes, $colspan, $order->tax_included, 2);

	$display_total = price_format(($total + input_num('freight_cost') + $tax_total));
        $_SESSION['sales_quotation_total'] = $display_total;
	start_row();
	label_cells(_("Amount Total"), $display_total, "colspan=$colspan align=right","align=right");
	submit_cells('update', _("Update"), "colspan=2 align='center'", _("Refresh"), true);
	end_row();

	end_table();
	if ($has_marked) {
		display_note(_("Marked items have insufficient quantities in stock as on day of delivery."), 0, 1, "class='stockmankofg'");
		if ($order->trans_type!=30 && !$SysPrefs->allow_negative_stock())
			display_error(_("The delivery cannot be processed because there is an insufficient quantity for item:")
				. '<br>'. $qoh_msg);
	}
    

	end_table(1);
        
        
}

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

function display_sales_quotation_header(&$order, $editable, $date_text)
{
	global $Ajax, $SysPrefs;         
    
        if(isset($order) && $order->order_no){
                $order_no =  ($order->order_no);
                if($order_no>0){
                        if(isset($_POST['_project_id_edit']) && $_POST['_project_id_edit'] > 0){
                            $project_id = $_POST['_project_id_edit'];
                        }
                        elseif(isset($_POST['project_id']) && $_POST['project_id'] > 0){
                            $project_id = $_POST['project_id'];
                        }
                        elseif($order->project_id > 0){
                            $project_id = $order->project_id;
                        }
                        else{
                            $project_id = -1;
                        }

                        $_POST['project_id'] = $project_id;

                        $user_id = $_SESSION['wa_current_user']->user;
                        $cap = can_access_project($project_id, $user_id);
                        if($cap['success'] !== true) 
                        {
                            display_error($cap["message"]);
                            set_focus('project_id');
                            display_footer_exit();
                            exit;
                        }
                }
        }

	start_outer_table(TABLESTYLE2, "width=70%");

	table_section(1, '35%');
	
	$customer_error = "";
	$change_prices = 0;

	if (isset($order) && !$editable)
	{    
		// can't change the customer/branch if items already received on this order
		//echo $order->customer_name . " - " . $order->deliver_to;
                if(isset($_POST['project_id'])){
                    $order->project_id  = $_POST["project_id"];
                }   

                if(isset($order->project_id))
                {
                    project_list_row(_("Project:"), 'project_id', null, _('Select a Project'), true);
                }
                else
                {
                    project_list_row(_("Project:"), 'project_id', null, _('Select a Project'), true);
                }
                        
                label_row(_("Customer:"), $order->customer_name . " - " . $order->deliver_to);
                hidden('customer_id', $order->customer_id);
                hidden('branch_id', $order->Branch);
                hidden('sales_type', $order->sales_type);
                if ($order->trans_type != ST_SALESQUOTE  && $order->trans_type != ST_SALESQUOTE) {
                        hidden('dimension_id', $order->dimension_id); // 2008-11-12 Joe Hunt
                        hidden('dimension2_id', $order->dimension2_id);
                }	
        }
	else{
                if(isset($_POST['_project_id_edit']) && $_POST['_project_id_edit'] > 0){
                    $project_id = $_POST['_project_id_edit'];
                }
                elseif(isset($_POST['project_id']) && $_POST['project_id'] > 0){
                    $project_id = $_POST['project_id'];
                }
                else{
                    $project_id = -1;
                } 

                $order->project_id = $project_id;
                
                if(isset($order->project_id)){
                    $_POST['_project_id_edit'] = $order->project_id;
                    $_POST['project_id'] = $order->project_id;
                    project_list_row(_("Project:"), 'project_id', null, _('Select a Project'), true);
                }
                else{
                    project_list_row(_("Project:"), 'project_id', null, _('Select a Project'), true);
                }
        
//		customer_list_row(_("Customer:"), 'customer_id', null, 'Select a Customer', true, false, true);
		customer_list_row(_("Customer:"), 'customer_id', null, 'Select a Customer', true);

                $cis = get_post('customer_id', -11);
		if ($order->customer_id != $cis)
		{
			// customer has changed
			$Ajax->activate('branch_id');
  		}
		customer_branches_list_row(_("Branch:"), $_POST['customer_id'], 'branch_id', null, false, true, true, true);

		if(($order->customer_id != get_post('customer_id', -1)) ||
			($order->Branch != get_post('branch_id', -1)) ||
				list_updated('customer_id')) 
		{

			if (!isset($_POST['branch_id']) || $_POST['branch_id'] == "")
			{
				// ignore errors on customer search box call
//				if ($_POST['customer_id'] == '')
//					$customer_error = _("No customer found for entered text.");
//				else
//					$customer_error = _("The selected customer does not have any branches. Please create at least one branch.");
				unset($_POST['branch_id']);
				$order->Branch = 0;
			} 
			else
			{

				$old_order = (PHP_VERSION<5) ? $order : clone( $order );

				$customer_error = get_customer_details_to_order($order, $_POST['customer_id'], $_POST['branch_id']);
				$_POST['Location'] = $order->Location;
				$_POST['deliver_to'] = $order->deliver_to;
				$_POST['delivery_address'] = $order->delivery_address;
				$_POST['phone'] = $order->phone;
				$_POST['delivery_date'] = $order->due_date;

				if (!in_array($order->trans_type, array(ST_SALESQUOTE, ST_SALESQUOTE))
					&& ($order->pos['cash_sale'] != $order->pos['credit_sale'])
					&& (($order->payment_terms['cash_sale'] && !$order->pos['cash_sale']) ||
						(!$order->payment_terms['cash_sale'] && !$order->pos['credit_sale']))) {
							// force payment terms refresh if terms are editable
							// and pos have no permitions for terms selected in customer record.
							// Terms are set to first terms in allowed category below.
							display_warning(
								sprintf(_("Customer's payment terms '%s' cannot be selected on this POS"),
									$order->payment_terms['terms']));
							$order->payment = '';
				} elseif (get_post('payment') !== $order->payment) {
					$_POST['payment'] = $order->payment;
					$Ajax->activate('delivery');
					$Ajax->activate('payment');
				} else {
					if ($order->trans_type == ST_SALESINVOICE)
					{
						$_POST['delivery_date'] = $order->due_date;
						$Ajax->activate('delivery_date');
					}
					$Ajax->activate('Location');
					$Ajax->activate('deliver_to');
					$Ajax->activate('phone');
					$Ajax->activate('delivery_address');
				}
				// change prices if necessary
				// what about discount in template case?
				if ($old_order->customer_currency != $order->customer_currency) {
					$change_prices = 1;
				}
				if ($old_order->sales_type != $order->sales_type) {
				//  || $old_order->default_discount!=$order->default_discount
					$_POST['sales_type'] = $order->sales_type;
					$Ajax->activate('sales_type');
					$change_prices = 1;
				}
				if ($old_order->dimension_id != $order->dimension_id) {
					$_POST['dimension_id'] = $order->dimension_id;
				    $Ajax->activate('dimension_id');
				}
				if ($old_order->dimension2_id != $order->dimension2_id) {
					$_POST['dimension2_id'] = $order->dimension2_id;
				    $Ajax->activate('dimension2_id');
				}
				unset($old_order);
			}
//			set_global_customer($_POST['customer_id']);
		} // changed branch
		else
		{
			$row = get_customer_to_order($_POST['customer_id']);
			if ($row['dissallow_invoices'] == 1)
				$customer_error = _("The selected customer account is currently on hold. Please contact the credit control personnel to discuss.");
		}
	}

//	ref_row(_("Reference").':', 'ref', _('Reference number unique for this document type'), null, '');
        text_row("Reference:", 'ref', null, 20, 100);

	table_section(2, '35%');

	if (!is_company_currency($order->customer_currency) && in_array($order->trans_type, array(ST_SALESINVOICE, ST_CUSTDELIVERY)))
	{
		label_row(_("Customer Currency:"), $order->customer_currency);
		exchange_rate_display(get_company_currency(), $order->customer_currency,
			($editable ? $_POST['OrderDate'] : $order->document_date));
	}

	customer_credit_row($_POST['customer_id'], $order->credit);

	label_row(_("Customer Discount:"), ($order->default_discount * 100) . "%");

	//table_section(3);
	if ($order->pos['cash_sale'] || $order->pos['credit_sale']) {
		 // editable payment type 
		if (get_post('payment') !== $order->payment) {
			$order->payment = get_post('payment');
			$order->payment_terms = get_payment_terms($order->payment);
			$order->due_date = get_invoice_duedate($order->payment, $order->document_date);
			if ($order->payment_terms['cash_sale']) {
				$_POST['Location'] = $order->Location = $order->pos['pos_location'];
				$order->location_name = $order->pos['location_name'];
			}
			$Ajax->activate('items_table');
			$Ajax->activate('delivery');
		}
		$paymcat = !$order->pos['cash_sale'] ? PM_CREDIT : 
			(!$order->pos['credit_sale'] ? PM_CASH : PM_ANY);
		// all terms are available for SO
		sale_payment_list_cells(_('Payment:'), 'payment', 
			(in_array($order->trans_type, array(ST_SALESQUOTE, ST_SALESQUOTE)) 
			? PM_ANY : $paymcat), null);
	} else {
		label_cells(_('Payment:'), $order->payment_terms['terms']);
	}

	if($editable) {
		$str = sales_types_list_row(_("Price List:"), 'sales_type', null, true);
	} else {
		label_row(_("Price List:"), $order->sales_type_name);
	}
	if ($order->sales_type != $_POST['sales_type']) {
		$myrow = get_sales_type($_POST['sales_type']);
		$order->set_sales_type($myrow['id'], $myrow['sales_type'],
			$myrow['tax_included'], $myrow['factor']);
		$Ajax->activate('sales_type');
		$change_prices = 1;
	}

//	table_section(4);

	if ($editable)
	{
		if (!isset($_POST['OrderDate']) || $_POST['OrderDate'] == "")
			$_POST['OrderDate'] = $order->document_date;

		date_row($date_text, 'OrderDate', _('Date of order receive'),
			$order->order_no==0, 0, 0, 0, null, true);
		if (isset($_POST['_OrderDate_changed']) || list_updated('payment')) {
			if (!is_company_currency($order->customer_currency) 
				&& (get_base_sales_type()>0)) {
					$change_prices = 1;
			}
			$Ajax->activate('_ex_rate');
			if ($order->trans_type == ST_SALESINVOICE) {
				$_POST['delivery_date'] = get_invoice_duedate(get_post('payment'), get_post('OrderDate'));
			} else 
				$_POST['delivery_date'] = add_days(get_post('OrderDate'), $SysPrefs->default_delivery_required_by());
			$Ajax->activate('items_table');
			$Ajax->activate('delivery_date');
		}
		if ($order->trans_type != ST_SALESQUOTE && $order->trans_type != ST_SALESQUOTE)
		{	// 2008-11-12 Joe Hunt added dimensions
			$dim = get_company_pref('use_dimension');
			if ($dim > 0)
				dimensions_list_row(_("Dimension").":", 'dimension_id', 
					null, true, ' ', false, 1, false);
			else
				hidden('dimension_id', 0);
			if ($dim > 1)
				dimensions_list_row(_("Dimension")." 2:", 'dimension2_id', 
					null, true, ' ', false, 2, false);
			else
				hidden('dimension2_id', 0);
		}	
	}
	else
	{
		label_row($date_text, $order->document_date);
		hidden('OrderDate', $order->document_date);
	}

    table_section(3, '30%');
    global $approval_statuses;
    
    if(list_updated("branch_id") || list_updated("customer_id")){
        $cust_branch = get_cust_branch($_POST['customer_id'], $_POST['branch_id']);
        $_POST['salesman_id'] = $cust_branch['salesman'];
        $_POST['tax_group_id'] = $cust_branch['tax_group_id'];
    }
    
    if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id']>0)){
        $_POST['tax_group_id'] = $order->tax_group_id;
    }
    tax_groups_list_row("Tax Group:", 'tax_group_id', null);
    sales_persons_list_row("Sales Person:", "salesman_id", $_POST['salesman_id']);
    
    if($order->order_no > 0 && !isset($_GET['NewQuoteToSalesOrder'])){
        label_row("Order Category:", $order->order_category_name);
        label_row("Order Category Ref:", $order->order_category_reference);
        hidden('order_category_id', $order->order_category_id);
    }
    else{
        order_categories_list_row("Order Category:", "order_category_id", OCT_SALES);
    }
    
    $s = get_project_trans_view_str(98, $order->order_no."&source_type_id=".$order->trans_type, "Approval Status");
            //label_cell($s);
    label_row($s,$approval_statuses[$order->approval_status]);
    
	end_outer_table(1); // outer table

	if ($change_prices != 0) {
		foreach ($order->line_items as $line_no=>$item) {
			$line = &$order->line_items[$line_no];
			$line->price = get_kit_price($line->stock_id, $order->customer_currency,
				$order->sales_type, $order->price_factor, get_post('OrderDate'));
		//		$line->discount_percent = $order->default_discount;
		}
	    $Ajax->activate('items_table');
	}

	return $customer_error;
}

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

function sales_quotation_item_controls(&$order, &$rowcounter, $line_no=-1)
{
    global $Ajax;

	alt_table_row_color($rowcounter);

	$id = find_submit('Edit');
    
	if ($line_no!=-1 && $line_no == $id) // edit old line
	{
		$_POST['stock_id_'.$line_no] = $order->line_items[$id]->stock_id;
		$dec = get_qty_dec($_POST['stock_id_'.$line_no]);
		$_POST['dispatched_qty_'.$line_no] = number_format2($order->line_items[$id]->qty_dispatched, $dec);
    
                label_cell($line_no);
                if(list_updated('tran_unit_'.$line_no)){
                    $price = get_kit_price($_POST['stock_id_'.$line_no],$order->customer_currency, $order->sales_type,
                                            $order->price_factor, get_post('OrderDate'), false, get_post('tran_unit_'.$line_no));
                    $alternate_unit = get_convertion_factor(get_post('tran_unit_'.$line_no), $order->line_items[$line_no]->stock_id);
                    if($alternate_unit){
                        $convertion_factor = $alternate_unit['convertion_factor'];
                    }
                    else{
                        $convertion_factor = 1;
                    }   
                    $tran_unit_price = $price;
                    $_POST['tran_unit_price_'.$id] = price_format($tran_unit_price);
                    $_POST['tran_unit_min_price_'.$line_no] = price_format($order->line_items[$line_no]->minimum_price * $convertion_factor);
                    $_POST['tran_unit_list_price_'.$line_no] = $price;
                }
                else{
                    $_POST['tran_unit_price_'.$id] = price_format($order->line_items[$line_no]->tran_unit_price);
                    $_POST['tran_unit_min_price_'.$line_no] = price_format($order->line_items[$line_no]->minimum_price  * $order->line_items[$line_no]->convertion_factor);
                }
//		$_POST['Disc'] = percent_format($order->line_items[$id]->discount_percent*100);
                $_POST['Disc_'.$line_no] = number_format2($order->line_items[$id]->discount_percent*100, 5);
		$units = $order->line_items[$id]->units;
		$_POST['item_description_'.$line_no] = $order->line_items[$id]->item_description;
		hidden('stock_id_'.$line_no, $order->line_items[$line_no]->stock_id);
		hidden('stock_id_'.$line_no, $_POST['stock_id_'.$line_no]);
		label_cell($_POST['stock_id_'.$line_no]); 
		if ($order->line_items[$id]->descr_editable){
			text_cells(null,'item_description_'.$line_no, null, 45, 150);
                }
		else{
			hidden('item_description_'.$line_no, $_POST['item_description_'.$line_no]);
			label_cell($_POST['item_description_'.$line_no]);
		}
        
                $minimum_price = $order->line_items[$id]->minimum_price;
        
//		} else {
//			sales_items_list_cells(null,'item_description', null, false, true);
//		}
		//label_cell($order->line_items[$line_no]->item_description, "nowrap");
                
                if(!(isset($_POST['tran_qty_'.$line_no]) && $_POST['tran_qty_'.$line_no] >= 0)){
                    $_POST['tran_qty_'.$line_no] = number_format2($order->line_items[$id]->tran_qty, $dec);
                }
                $Ajax->activate('items_table');
	}
	else	// prepare new line
	{
                label_cell("");
		sales_items_list_cells(null,'stock_id_'.$line_no, null, false, true, true);
		if (list_updated('stock_id_'.$line_no)) {
                        $Ajax->activate('tran_unit_price_'.$line_no);
                        $Ajax->activate('units_'.$line_no);
                        $Ajax->activate('dispatched_qty_'.$line_no);
                        $Ajax->activate('line_total');
                        $Ajax->activate('tran_unit_'.$line_no);
                        $Ajax->activate('tran_qty_'.$line_no);
		}

                $units = '';
                $dec = $minimum_price = 0;
		$item_info = get_item_edit_info($_POST['stock_id_'.$line_no]);
                if (isset($item_info["units"]) && strlen($item_info["units"]) > 0) {
                    $units = $item_info["units"];
                    $dec = $item_info['decimals'];
                    $minimum_price = $item_info['minimum_price'];
                }
		$_POST['dispatched_qty'] = number_format2(1, $dec);
        
		// default to the customer's discount %
		$_POST['Disc_'.$line_no] = percent_format($order->default_discount * 100);
        
	}

//	qty_cells(null, 'qty', $_POST['qty'], null, null, $dec);
        qty_cells(null, 'tran_qty_'.$line_no, null, null, null, $dec);

	if ($order->order_no!=0) {
		qty_cell($line_no==-1 ? 0 :$order->line_items[$line_no]->qty_done, false, $dec);
	}

	if ($line_no != -1 && $line_no == $id)
	{
        if(!isset($_POST['tran_unit_'.$line_no])){
             $tran_unit = $order->line_items[$id]->tran_unit;
//            $_POST['std_cost'] = input_num('std_cost');
            if($tran_unit == ""){
                $_POST['tran_unit_'.$line_no] = $order->line_items[$id]->units;
            }
            else{
                $_POST['tran_unit_'.$line_no] = $order->line_items[$id]->tran_unit;
            }
        }
    }
    
    units_list_cells(null, 'tran_unit_'.$line_no, $_POST['stock_id_'.$line_no], null, false, true);
    
    
    $price = get_kit_price($_POST['stock_id_'.$line_no],$order->customer_currency, $order->sales_type,
                            $order->price_factor, get_post('OrderDate'), false, $_POST['tran_unit_'.$line_no]);
    $_POST['tran_unit_list_price_'.$line_no] = $price;
    
    
    $alternate_unit = get_convertion_factor(get_post('tran_unit_'.$line_no), $_POST['stock_id_'.$line_no]);
    if($alternate_unit){
        $convertion_factor = $alternate_unit['convertion_factor'];
    }
    else{
        $convertion_factor = 1;
    }     
    
    
    
    hidden('conversion_factor', $convertion_factor);
    hidden('tran_unit_list_price_'.$line_no);
    
    
    $tran_unit_price = $price;
        
    if(list_updated('stock_id_'.$line_no) || list_updated('tran_unit_'.$line_no)){
        $_POST['tran_unit_price_'.$line_no] = price_format($tran_unit_price);
        $_POST['tran_unit_min_price_'.$line_no] = $minimum_price * $convertion_factor;
    }
    
    if(!isset($_POST['tran_unit_price_'.$line_no])){
        $_POST['tran_unit_price_'.$line_no] = $tran_unit_price;
    }
    
    amount_cell(input_num('tran_unit_list_price_'.$line_no));

    amount_cells(null, 'tran_unit_price_'.$line_no);

//	small_amount_cells(null, 'Disc', percent_format($_POST['Disc']), null, null, user_percent_dec());
    small_amount_cells(null, 'Disc_'.$line_no, percent_format($_POST['Disc_'.$line_no]), null, null, 5);
    
    if(isset($_POST['tran_unit_min_price_'.$line_no])){
        amount_cell(input_num('tran_unit_min_price_'.$line_no));
    }
    else{
        amount_cell(0);
    }

	$line_total = input_num('tran_qty_'.$line_no) * input_num('tran_unit_price_'.$line_no) * (1 - input_num('Disc_'.$line_no) / 100);

	amount_cell($line_total, false, '','line_total');

	if ($id!=-1)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $line_no);
		set_focus('tran_qty_'.$line_no);
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2 align='center'",
		    _('Add new item to document'), true);
	}

	end_row();
}

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

function display_sales_quotation_delivery_details(&$order)
{
	global $Ajax;

	div_start('delivery');	

        start_table(TABLESTYLE, "width=95%", 10);

//	if ($order->payment_terms['cash_sale']) {	// Direct payment sale
//		$Ajax->activate('items_table');
//		display_heading(_('Cash payment'));
//		start_table(TABLESTYLE2, "width=60%");
//
//		locations_list_row(_("Deliver from Location:"), 'Location', null, false, true);
// 		if (list_updated('Location'))
// 			$Ajax->activate('items_table');
//		label_row(_("Cash account:"), $order->pos['bank_account_name']);
//                text_row(_("Customer Reference:"), 'cust_ref', $order->cust_ref, 25, 25,_('Customer reference number for this order (if any)'));
//		textarea_row(_("Comments:"), "Comments", $order->Comments, 31, 5);
//		end_table();
//		hidden('delivery_date', $order->due_date);
//	} 
//        else {
		if ($order->trans_type==ST_SALESINVOICE)
		{
			$title = _("Delivery Details");
			$delname = _("Due Date").':';
		}
		elseif ($order->trans_type==ST_CUSTDELIVERY)
		{
			$title = _("Invoice Delivery Details");
			$delname = _("Invoice before").':';
		}
		elseif ($order->trans_type==ST_SALESQUOTE)
		{
			$title = _("Quotation Delivery Details");
			$delname = _("Valid until").':';
		}
		else
		{
			$title = _("Order Delivery Details");
			$delname = _("Required Delivery Date").':';
		}
		display_heading($title);
		start_outer_table(TABLESTYLE2, "width=90%");
		table_section(1);

		locations_list_row(_("Deliver from Location:"), 'Location', null, false, true);
		if (list_updated('Location'))
			$Ajax->activate('items_table');


		date_row($delname, 'delivery_date',
			$order->trans_type==ST_SALESQUOTE ?  _('Enter requested day of delivery') 
				: ($order->trans_type==ST_SALESQUOTE ? _('Enter Valid until Date') : ''));
		text_row(_("Deliver To:"), 'deliver_to', $order->deliver_to, 40, 40,
			_('Additional identifier for delivery e.g. name of receiving person'));

		textarea_row(_("Address:"), 'delivery_address', $order->delivery_address, 35, 5,
			_('Delivery address. Default is address of customer branch'));

		table_section(2);

		text_row(_("Contact Phone Number:"), 'phone', $order->phone, 25, 25,
		    _('Phone number of ordering person. Defaults to branch phone number'));
		text_row(_("Customer Reference:"), 'cust_ref', $order->cust_ref, 25, 25,
		  _('Customer reference number for this order (if any)'));
		textarea_row(_("Comments:"), "Comments", $order->Comments, 31, 5);

		shippers_list_row(_("Shipping Company:"), 'ship_via', $order->ship_via);

		end_outer_table(1);
//	}
	div_end();
        
        echo "</td></tr>";
	end_table(1);
}

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


function reject_sales_quotation($so_no)
{
    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);
    
    $crso_msg = can_release_sales_quotation_for_approval($cart);
    if($crso_msg['success'] !== true){
        display_error($crso_msg['message']);
        return;
    }

    copy_to_save_sales_quotation_cart($cart);

    $dad_msg = direct_reject_sales_documents($cart, $_SESSION['wa_current_user']->user);
    if($dad_msg['success'] !== true){
        display_error(_($dad_msg["message"]));
        return;
    }
    
        
    $order_no = $cart->order_no;
    $trans_type = $cart->trans_type;
    new_doc_date($cart->document_date);
    processing_end();

    if ($trans_type == ST_SALESQUOTE) {
        meta_forward($_SERVER['PHP_SELF'], "RejectedSO=$order_no");
    } 
    elseif ($trans_type == ST_SALESQUOTE) {
        meta_forward($_SERVER['PHP_SELF'], "RejectedSQ=$order_no");
    } 
            
}

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


function release_sales_quotation_for_approval($so_no)
{
    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);
    
    $crso_msg = can_release_sales_quotation_for_approval($cart);
    if($crso_msg['success'] !== true){
        display_error($crso_msg['message']);
        return;
    }

    copy_to_save_sales_quotation_cart($cart);

    $dad_msg = direct_approve_sales_documents($cart, $_SESSION['wa_current_user']->user);
    if($dad_msg['success'] !== true){
        display_error(_($dad_msg["message"]));
        return;
    }
    
        
    $order_no = $cart->order_no;
    $trans_type = $cart->trans_type;
    new_doc_date($cart->document_date);
    processing_end();

    if ($trans_type == ST_SALESQUOTE) {
        meta_forward($_SERVER['PHP_SELF'], "ApprovedSO=$order_no");
    } 
    elseif ($trans_type == ST_SALESQUOTE) {
        meta_forward($_SERVER['PHP_SELF'], "ApprovedSQ=$order_no");
    } 
            
}

//--------------------------------------------------------------------------------
function can_release_sales_quotation_for_approval($so) {

        if(!($so->approval_status == AS_NEW || $so->approval_status == AS_AWAITING_APPROVAL || 
                $so->approval_status == AS_WITH_THE_APPROVER || $so->approval_status == AS_REOPENED || 
                $so->approval_status == AS_BACK_TO_ORIGINATOR))
        {
            $message = ("This document status does not allow further updating.");
            return array("success" => false, "tran_no" => $so->order_no, "message" => $message);
        }
        
        $msg = check_sales_quotation_integrity($so->order_no);
        if($msg['success'] !== true){ 
            return array("success" => false, "tran_no" => $so->order_no, "message" => $msg['message']);
        }
        
        return array("success" => true, "tran_no" => $so->order_no, "message" => ""); 

}

//--------------------------------------------------------------------------------
function can_process_sales_quotation_header($so) {
	global $Refs;
        

     $so_no = ($so->order_no);

        if($so_no > 0){
            if(!($so->approval_status == AS_NEW || $so->approval_status == AS_AWAITING_APPROVAL || 
                    $so->approval_status == AS_WITH_THE_APPROVER || $so->approval_status == AS_REOPENED))
            {
                $message = ("This document status does not allow further updating.");
                $set_focus =  "";
                return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }
        }
    
        if (!($_POST['project_id']) > 0) 
	{
		$message = (_("There is no project selected."));
		$set_focus = ('project_id');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
    
	if (!(get_post('customer_id') > 0)) 
	{
		$message = (_("There is no customer selected."));
		$set_focus = ('customer_id');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	} 
	
	if (!(get_post('branch_id') > 0)) 
	{
		$message = (_("Please select customer branch."));
		$set_focus = ('branch_id');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	} 
	
	if (!is_date($_POST['OrderDate'])) {
		$message = (_("The entered date is invalid."));
		$set_focus = ('OrderDate');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
	if ($so->trans_type!=ST_SALESQUOTE && $so->trans_type!=ST_SALESQUOTE && !is_date_in_fiscalyear($_POST['OrderDate'])) {
		$message = (_("The entered date is not in fiscal year"));
		$set_focus = ('OrderDate');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
//	if (count($so->line_items) == 0)	{
//		display_error(_("You must enter at least one non empty item line."));
//		set_focus('AddItem');
//		return false;
//	}
	if ($so->payment_terms['cash_sale'] == -9999) {//process is same for both sash payment and credit payment. So no eed below validations
            if (strlen($_POST['deliver_to']) <= 1) {
                    $message = (_("You must enter the person or company to whom delivery should be made to."));
                    $set_focus = ('deliver_to');
                    return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }


            if ($so->trans_type != ST_SALESQUOTE && strlen($_POST['delivery_address']) <= 1) {
                $message = ( _("You should enter the street address in the box provided. Orders cannot be accepted without a valid street address."));
                $set_focus = ('delivery_address');
                return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }

            if ($_POST['freight_cost'] == ""){
                $_POST['freight_cost'] = price_format(0);
            }

            if (!check_num('freight_cost',0)) {
                $message = (_("The shipping cost entered is expected to be numeric."));
                $set_focus = ('freight_cost');
                return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }
            if (!is_date($_POST['delivery_date'])) {
                if ($so->trans_type==ST_SALESQUOTE){
                    $message = (_("The Valid date is invalid."));
                }
                else{	
                    $message = (_("The delivery date is invalid."));
                }
                $set_focus = ('delivery_date');
                return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }

            //if (date1_greater_date2($so->document_date, $_POST['delivery_date'])) {
            if (date1_greater_date2($_POST['OrderDate'], $_POST['delivery_date'])) {
                if ($so->trans_type==ST_SALESQUOTE){
                    $message = (_("The requested valid date is before the date of the quotation."));
                }
                else{	
                    $message = (_("The requested delivery date is before the date of the order."));
                }
                $set_focus = ('delivery_date');
                return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }
	}
	else
	{
		if (!db_has_cash_accounts())
		{
			$message = (_("You need to define a cash account for your Sales Point."));
                        $set_focus = "";
			return false;
		}	
	}	
    
	if (!$Refs->is_valid($_POST['ref'])) {
		$message = (_("You must enter a reference."));
		$set_focus = ('ref');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
    
//    if ($Refs->exists($so->trans_type, $_POST['ref'], ($so->order_no ? $so->order_no: 0 )) ) {
//		display_error(_("Entered reference is already in use."));
//		set_focus('ref');
//		return false;
//	}
        $ref_msg = reference_exists($_POST['ref'], $so->trans_type, ($so_no > 0 ? $so_no: 0 ));    
        if ($ref_msg){
		$message = ($ref_msg);
		$set_focus = ('ref');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
    
	return array("success" => true, "set_focus" => "", "message" => "");
}


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

function can_process_sales_quotation_line(&$cart, $id = -1)
{
	global $SysPrefs, $allow_negative_prices;

        if($id < 1){
            if(!get_post('stock_id_'.$id)) {
                    $message = ( _("Please select an item."));
                    $set_focus = ('stock_id_'.$id);
                    return array("success" => false, "set_focus" => $set_focus, "message" => $message);
            }
        }

//	if(!get_post('stock_id_text', true)) {
//		display_error( _("Item description cannot be empty."));
//		set_focus('stock_id_edit');
//		return false;
//	}
    
    
//    if (!$alternate_unit) {
//		display_error("Unit conversion not defined for the select unit ".get_post('tran_unit'));
//		set_focus('tran_unit');
//		return false;
//    }
    
    if (!check_num('tran_qty_'.$id, 0)) {
		$message = ( _("The item could not be updated because you are attempting to set the quantity ordered to less than 0."));
		$set_focus = ('tran_qty_'.$id);
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }
    
    if (!check_num('Disc_'.$id, 0, 100)) {
		$message = ( _("The item could not be updated because you are attempting to set the discount percent to an invalid value."));
		$set_focus = ('Disc_'.$id);
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    }
    
//    if (!check_num('tran_unit_price_'.$line_no, 0) && (!$allow_negative_prices || $is_inventory_item)) {
//		display_error( _("Price for inventory item must be entered and can not be less than 0"));
//		set_focus('price');
//		return false;
//	} 
    
    if (!check_num('tran_unit_price_'.$id, 0)) {
		$message = ( _("Price for inventory item must be entered and can not be less than 0"));
		$set_focus = ('price');
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
	}
    
    if (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']])
	    && (input_num('tran_qty') * $_SESSION['Items']->line_items[$_POST['LineNo']]->convertion_factor) < 
                $_SESSION['Items']->line_items[$_POST['LineNo']]->qty_done ) {

		$set_focus = ('tran_qty_'.$id);
		$message = (_("You attempting to make the quantity ordered a quantity less than has already been delivered. The quantity delivered cannot be modified retrospectively."));
		return array("success" => false, "set_focus" => $set_focus, "message" => $message);
    } // Joe Hunt added 2008-09-22 -------------------------

    return array("success" => true, "set_focus" => "", "message" => "");
    
}	
    
    
function check_sales_quotation_item_data(&$cart, $id=-1)
{
    	
        $is_inventory_item = is_inventory_item(get_post('stock_id_'.$id));

        if ($is_inventory_item && $cart->trans_type!=ST_SALESQUOTE && $cart->trans_type!=ST_SALESQUOTE 
		&& !$SysPrefs->allow_negative_stock())
	{
		$qoh = get_qoh_on_date($_POST['stock_id_'.$id], $_POST['Location'], $_POST['OrderDate']);
		if ((input_num('tran_qty_'.$id) * $cart->line_items[0]->convertion_factor) > $qoh)
		{
			$stock = get_item($_POST['stock_id_'.$id]);
			$message = (_("The delivery cannot be processed because there is an insufficient quantity for item:") .
				" " . $stock['stock_id_'.$id] . " - " . $stock['description_'.$id] . " - " .
				_("Quantity On Hand") . " = " . number_format2($qoh, get_qty_dec($_POST['stock_id_'.$id])));
                        
			return array("success" => false, "set_focus" => "", "message" => $message);
		}
                
		
	}
    
    
        $cost_home = get_standard_cost(get_post('stock_id_'.$id)); // Added 2011-03-27 Joe Hunt
	$cost = $cost_home / get_exchange_rate_from_home_currency($cart->customer_currency, $cart->document_date);
    
//        if (isset($_POST['LineNo']) && isset($_SESSION['Items']->line_items[$_POST['LineNo']]->convertion_factor)){
//            $conversion_factor = $_SESSION['Items']->line_items[$_POST['LineNo']]->convertion_factor;
//        }
//        else{
//            $conversion_factor = get_post('conversion_factor');
//        }
            
        $conversion_factor = $cart->line_items[0]->convertion_factor;
        
	if (input_num('tran_unit_price_'.$id) < $cost * $conversion_factor)
	{
		$dec = user_price_dec();
		$curr = $cart->customer_currency;
		$price = number_format2(input_num('price_'.$id), $dec);
		if ($cost_home == $cost){
			$std_cost = number_format2($cost_home, $dec);
                }
		else
		{
			$price = $curr . " " . $price;
			$std_cost = $curr . " " . number_format2($cost, $dec);
		}
//		display_warning(sprintf(_("Price %s is below Standard Cost %s"), $price, $std_cost));
	}	
    
    
	return array("success" => false, "set_focus" => "", "message" => "");
}


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

function handle_new_sales_quotation_item($so_no)
{       
    global $Refs;
    
    $id = -1;
    
    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);

    $reth = can_process_sales_quotation_header($cart);
    if($reth["success"] !== true){
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return;
    }
    
    copy_to_save_sales_quotation_cart($cart);
    
    $retl = can_process_sales_quotation_line($cart);
    if($retl["success"] !== true){
        display_error($retl["message"]);
        return;
    }
    
    $stock_id = $_POST['stock_id_'.$id];
    $tran_unit = $_POST['tran_unit_'.$id];
    get_convertion_factor2($stock_id, $tran_unit, $convesion_factor);
    $_POST['tran_unit_-1'] = $tran_unit;

    $kit = get_kit_props($_POST['stock_id_'.$id]);
//    if($kit){
//        $convertion_factor = 1;
//        $alternate_unit = true;
//    }
        
    $tran_qty = input_num('tran_qty_'.$id);
    $base_unit_qty = $tran_qty * $convesion_factor;
    $tran_unit_price = input_num('tran_unit_price_'.$id);
    $base_unit_price = $tran_unit_price / $convesion_factor;  
    $discount = input_num('Disc_'.$id);
    $item_description = get_post('item_description_'.$id);
    get_post('stock_id_text');
    
    add_to_save_sales_quotation($cart, $stock_id, $base_unit_qty,
            $base_unit_price, $discount / 100, $item_description, 
            $tran_unit, $tran_qty, $convesion_factor,
            $tran_unit_price);
    
    
//    $l = $cart->count_items() - 1;
    $cart->line_items[0]->list_price = input_num('tran_unit_list_price');
    
    if (!check_sales_quotation_item_data($cart)) {
        return;
    }
    
    begin_transaction();
    $cart_msg = $cart->write_sales_quotation($cart, $id);
    if($cart_msg["success"] === true){
        add_audit_trail($cart->trans_type, $cart->order_no, $cart->document_date);
	$Refs->save($cart->trans_type, $cart->order_no, $cart->reference);
        
        commit_transaction();
        set_session_variable("ST_SALESQUOTE_no", $cart_msg["tran_no"]);
        display_notification("New line has been added to Sales order #".$cart_msg["tran_no"].".");
    }
    else{        
        cancel_transaction();
        display_error($cart_msg["message"]);
        return;
    }
    
    unset($_POST['_stock_id_edit'], $_POST['stock_id']);
//    page_modified();
//    line_start_focus();
}

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

function handle_delete_sales_quotation_item($so_no, $id)
{

    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);
    
    $reth = can_process_sales_quotation_header($cart);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return;
    }
    
    copy_to_save_sales_quotation_cart($cart);
    
    begin_transaction();
    $cart_msg = $cart->write_delete_sales_quotation_item($cart, $id);
    if($cart_msg["success"] === true){
        commit_transaction();
        display_notification("A line has been deleted in the Sales order #".$cart_msg["tran_no"].".");
    }
    else{        
        cancel_transaction();
        display_error($cart_msg["message"]);
        return;
    }
    
    page_modified();
    line_start_focus();
}

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

function handle_update_sales_quotation_header($so_no)
{
    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);
    
    $reth = can_process_sales_quotation_header($cart);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return;
    }
    
    copy_to_save_sales_quotation_cart($cart);
    
    
    begin_transaction();
    $cart_msg = $cart->write_sales_quotation_header($cart);
    if($cart_msg["success"] === true){
        commit_transaction();
        display_notification("Sales order #".$cart_msg["tran_no"]." header has been updated.");
    }
    else{        
        cancel_transaction();
        display_error($cart_msg["message"]);
        return;
    }
    
    page_modified();
    line_start_focus();
}


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

function handle_update_sales_quotation_item($so_no)
{
    $id = $_POST['LineNo'];

    $cart = create_save_sales_quotation_cart(ST_SALESQUOTE, $so_no);
    
    $reth = can_process_sales_quotation_header($cart);
    if($reth["success"] !== true){
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return;
    }
    
    copy_to_save_sales_quotation_cart($cart);
    
    $retl = can_process_sales_quotation_line($cart, $id);
    if($retl["success"] !== true){
        display_error($retl["message"]);
        return;
    }
    
    $so_line = get_sales_order_line_record($id);
    $stock_id = $so_line['stk_code'];
    $item = get_stock_item_edit_info($stock_id);
    
    $tran_unit = $_POST['tran_unit_'.$id];
    get_convertion_factor2($so_line['stk_code'], $tran_unit, $convesion_factor);
    
    $tran_qty = input_num('tran_qty_'.$id);
    $base_unit_qty = $tran_qty * $convesion_factor;
    $tran_unit_price = input_num('tran_unit_price_'.$id);
    $base_unit_price = $tran_unit_price / $convesion_factor;  
    $discount = input_num('Disc_'.$id);
    $item_description = $_POST['item_description_'.$id];
        
//    $cart->update_save_sales_quotation_cart_item($id, $base_unit_qty, $base_unit_price, input_num('Disc') / 100, 
//                                    $_POST['item_description'], input_num('tran_qty'), get_post('tran_unit_'.$id), $convesion_factor, 
//                                    input_num('tran_unit_price_'.$line_no));
                
    update_to_save_sales_quotation($cart, $id, $stock_id, $base_unit_qty, 
                                    $base_unit_price, $discount / 100, $item_description, 
                                    $tran_unit, $tran_qty, $convesion_factor, 
                                    $tran_unit_price);    

    
    $cart->line_items[0]->minimum_price = $item['minimum_price'];
    $cart->line_items[0]->list_price = input_num('tran_unit_list_price_'.$id);
    
    if(!check_sales_quotation_item_data($cart)){
            $_POST['Edit'.get_post('LineNo')] = 1;
            return;
    }
    
    begin_transaction();
    $cart_msg = $cart->write_sales_quotation($cart, $id, $policy=0);
    if($cart_msg["success"] === true){
        commit_transaction();
        display_notification("A line has been updated in Sales order #".$cart_msg["tran_no"].".");
    }
    else{        
        cancel_transaction();
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($cart_msg["message"]);
        return;
    }
    
    page_modified();
    line_start_focus();
}



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

function  handle_cancel_sales_quotation()
{
	global $path_to_root, $Ajax;


	if ($_SESSION['Items']->trans_type == ST_CUSTDELIVERY) {
		display_notification(_("Direct delivery entry has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Delivery"),	"/sales/sales_quotation_entry.php?NewDelivery=1");
	} 
    elseif ($_SESSION['Items']->trans_type == ST_SALESINVOICE) {
		display_notification(_("Direct invoice entry has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Invoice"),	"/sales/sales_quotation_entry.php?NewInvoice=1");
	} 
    elseif ($_SESSION['Items']->trans_type == ST_SALESQUOTE)
	{
		if ($_SESSION['Items']->order_no != 0){
			delete_sales_quotation(key($_SESSION['Items']->order_no), $_SESSION['Items']->trans_type);
        }
		display_notification(_("This sales quotation has been cancelled as requested."), 1);
		submenu_option(_("Enter a New Sales Quotation"), "/sales/sales_quotation_entry.php?NewQuotation=Yes");
	} 
    else { // sales order
		if ($_SESSION['Items']->order_no != 0) {
			$order_no = key($_SESSION['Items']->order_no);
			if (sales_quotation_has_deliveries($order_no)){
				close_sales_quotation($order_no);
				display_notification(_("Undelivered part of order has been cancelled as requested."), 1);
				submenu_option(_("Select Another Sales Order for Edition"), "/sales/inquiry/sales_quotations_view.php?type=".ST_SALESQUOTE);
			} 
            else{
				delete_sales_quotation(key($_SESSION['Items']->order_no), $_SESSION['Items']->trans_type);

				display_notification(_("This sales order has been cancelled as requested."), 1);
				submenu_option(_("Enter a New Sales Order"), "/sales/sales_quotation_entry.php?NewOrder=Yes");
			}
		} 
        else {
			processing_end();
			meta_forward($path_to_root.'/index.php','application=orders');
		}
	}
	$Ajax->activate('_page_body');
	processing_end();
	display_footer_exit();
}


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

function create_display_sales_quotation_cart($type, $order_no)
{ 
	global $Refs;

	if (!$_SESSION['SysPrefs']->db_ok){ // create_cart is called before page() where the check is done
		return;
        }

	processing_start();


        $cart = new Display_Sales_Quotation_Cart($type, $order_no);
    
	copy_from_sales_quotation_cart($cart);
        
        return $cart;
}


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

function create_save_sales_quotation_cart($type, $order_no)
{ 
	global $Refs;

	if (!$_SESSION['SysPrefs']->db_ok){ // create_cart is called before page() where the check is done
		return;
        }

	processing_start();


        return new Save_Sales_Quotation_Cart($type, $order_no);
    
}


////--------------------------------------------------------------------------------
//
//function handle_delete_sales_quotation_item($line_no)
//{
//    if ($_SESSION['Items']->some_already_delivered($line_no) == 0) {
//	    $_SESSION['Items']->remove_from_cart($line_no);
//    } else {
//	display_error(_("This item cannot be deleted because some of it has already been delivered."));
//    }
//    line_start_focus();
//}


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

function copy_from_sales_quotation_cart($cart)
{
//	$cart = &$_SESSION['Items'];
	$_POST['ref'] = $cart->reference;
	$_POST['Comments'] = $cart->Comments;

	$_POST['OrderDate'] = $cart->document_date;
	$_POST['delivery_date'] = $cart->due_date;
	$_POST['cust_ref'] = $cart->cust_ref;
	$_POST['freight_cost'] = price_format($cart->freight_cost);

	$_POST['deliver_to'] = $cart->deliver_to;
	$_POST['delivery_address'] = $cart->delivery_address;
	$_POST['phone'] = $cart->phone;
	$_POST['Location'] = $cart->Location;
	$_POST['ship_via'] = $cart->ship_via;

        if(!(isset($_POST['customer_id']) && $_POST['customer_id'] > 0)){
            $_POST['customer_id'] = $cart->customer_id;
        }

	$_POST['branch_id'] = $cart->Branch;
        
        if(!(isset($_POST['sales_type']) && $_POST['sales_type'] > 0)){
            $_POST['sales_type'] = $cart->sales_type;
        }
        
        $_POST['salesman_id'] = $cart->salesman_id;
	// POS 
        
        if(!(isset($_POST['payment']) && $_POST['payment'] > 0)){
            $_POST['payment'] = $cart->payment;
        }
	if ($cart->trans_type!=ST_SALESQUOTE && $cart->trans_type!=ST_SALESQUOTE) { // 2008-11-12 Joe Hunt
		$_POST['dimension_id'] = $cart->dimension_id;
		$_POST['dimension2_id'] = $cart->dimension2_id;
	}
	$_POST['cart_id'] = $cart->cart_id;
	$_POST['_ex_rate'] = $cart->ex_rate;
}

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

function copy_to_save_sales_quotation_cart(&$cart)
{
//	$cart = &$_SESSION['Items'];

	$cart->reference = $_POST['ref'];
        $cart->cust_ref =  $_POST['cust_ref'];
	$cart->Comments =  $_POST['Comments'];

	$cart->document_date = $_POST['OrderDate'];
        
        $cart->project_id = $_POST['project_id'];

	$newpayment = false;


        $cart->payment = $_POST['payment'];
        $cart->payment_terms = get_payment_terms($_POST['payment']);
        $newpayment = true;
	
	if ($cart->payment_terms['cash_sale']) {
		if ($newpayment) {
			$cart->due_date = $cart->document_date;
			$cart->phone = $cart->cust_ref = $cart->delivery_address = '';
			$cart->ship_via = 0;
			$cart->deliver_to = '';
		}
	} else {
		$cart->due_date = $_POST['delivery_date'];
		$cart->cust_ref = $_POST['cust_ref'];
		$cart->deliver_to = $_POST['deliver_to'];
		$cart->delivery_address = $_POST['delivery_address'];
		$cart->phone = $_POST['phone'];
		$cart->ship_via = $_POST['ship_via'];
	}
        
	$cart->Location = $_POST['Location'];
	$cart->freight_cost = input_num('freight_cost');
	if (isset($_POST['email'])){
		$cart->email =$_POST['email'];
        }
	else{
		$cart->email = '';
        }
        
	$cart->customer_id	= $_POST['customer_id'];
	$cart->Branch = $_POST['branch_id'];
	$cart->sales_type = $_POST['sales_type'];
        $cart->salesman_id	= $_POST['salesman_id'];

	
        $cart->dimension_id = 0;
        $cart->dimension2_id = 0;
	
	$cart->ex_rate = input_num('_ex_rate', null);
    
        $cart->order_category_id	= $_POST['order_category_id'];
        
        $customer = get_customer($cart->customer_id);
        $cart->customer_currency = $customer["curr_code"]; 
            
        if($cart->order_no > 0){
            $so = get_sales_order_header_record($cart->order_no, ST_SALESQUOTE);
            $cart->row_state = $so["row_state"];
        }
        else{                   
            $cart->row_state = 0;
        }

        $cart->tax_group_id = $_POST['tax_group_id'];
        $cart->tax_group_array = get_tax_group_items_as_array($cart->tax_group_id );
        $sales_type = get_sales_type($cart->sales_type);
        $cart->tax_included = $sales_type['tax_included'];
        
        $cart->freight_cost = input_num('freight_cost');
}

function check_sales_quotation_integrity($order_no){
    $result = get_miss_match_sales_order_lines_with_sales_type_and_tax_group($order_no, ST_SALESQUOTE);
        while($so_integrity = db_fetch($result)){
            if(!($so_integrity['so_order_type'] == $so_integrity['sod_order_type'])){
                $message = "Line Id ".$so_integrity['sod_id'].": Price List has been changed after saving this line. Please Update Line #".$so_integrity['sod_id'];
                return array("success" => false, "message" => $message);
            }elseif(!($so_integrity['so_tax_group_id'] == $so_integrity['sod_tax_group_id'])){
                $message = "Line Id ".$so_integrity['sod_id'].": Tax Group has been changed after saving this line. Please Update Line #".$so_integrity['sod_id'];
                return array("success" => false, "message" => $message);
            }               
        }
        return array("success" => true, "message" => "");
}

?>