<?php
/**********************************************************************
***********************************************************************/
include_once($path_to_root . "/purchasing/includes/purchasing_db.inc");
include_once($path_to_root . "/projects/includes/db/tasks_db.inc");
include_once($path_to_root . "/includes/db/approval_functions_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
//--------------------------------------------------------------------------------------------------

function copy_from_cart()
{
	$cart = &$_SESSION['PO'];

	$_POST['supplier_id'] = $cart->supplier_id;
	$_POST['OrderDate'] = $cart->orig_order_date;
	if ($cart->trans_type==ST_SUPPINVOICE)
		$_POST['due_date'] = $cart->due_date;
    $_POST['supp_ref'] = $cart->supp_ref;
    $_POST['ref'] = $cart->reference;
	$_POST['Comments'] = $cart->Comments;
    $_POST['StkLocation'] = $cart->Location;
    $_POST['delivery_address'] = $cart->delivery_address;
	$_POST['_ex_rate'] = $cart->ex_rate;
    $_POST['project_id'] = $cart->project_id; 
    $_POST['task_id'] =  $cart->task_id;
    
    foreach($cart->tax_overrides as $id => $value)
	    $_POST['mantax'][$id] = price_format($value);
}

function copy_to_cart()
{
	$cart = &$_SESSION['PO'];

	$cart->supplier_id = $_POST['supplier_id'];	
	$cart->orig_order_date = $_POST['OrderDate'];
	if ($cart->trans_type==ST_SUPPINVOICE){
		$cart->due_date = $_POST['due_date'];
    }
	$cart->reference = $_POST['ref'];
//    $cart->payment_terms = $_POST['payment_terms'];
	$cart->supp_ref = $_POST['supp_ref'];
	$cart->Comments = $_POST['Comments'];	
	$cart->Location = $_POST['StkLocation'];
	$cart->delivery_address = $_POST['delivery_address'];
	$cart->ex_rate = input_num('_ex_rate', null);
        $cart->project_id = $_POST['project_id'];
    //$cart->task_id = $_POST['task_id'];
    //$cart->use_future_budgets = $_POST['use_future_budgets'];

    if (isset($_POST['mantax'])) {
		foreach($_POST['mantax'] as $id => $tax) {
			$cart->tax_overrides[$id] = user_numeric($_POST['mantax'][$id]); }
	}
}
// ------------------------------------------------------------------------------

function get_supplier_details_to_order(&$order, $supplier_id, $tax_group_id = 0)
{
	$sql = "SELECT curr_code, supp_name, supp.tax_group_id, supp.tax_included,
			supp.credit_limit - Sum(IFNULL(ov_amount + ov_gst + ov_discount,0)) as cur_credit,
				terms.terms, terms.days_before_due, terms.day_in_following_month
		FROM ".TB_PREF."suppliers supp
			 LEFT JOIN ".TB_PREF."supp_trans trans ON supp.supplier_id = trans.supplier_id
			 LEFT JOIN ".TB_PREF."payment_terms terms ON supp.payment_terms=terms.terms_indicator
		WHERE supp.supplier_id = ".db_escape($supplier_id)."
		GROUP BY
			  supp.supp_name";

	$result = db_query($sql, "The supplier details could not be retreived");

	$myrow = db_fetch($result);
	$order->credit = $myrow["cur_credit"];
    
    
	$_POST['supplier_id'] = $supplier_id;
	$_POST['supplier_name'] = $myrow["supp_name"];
	$_POST['curr_code'] = $myrow["curr_code"];
        
        if(!($tax_group_id > 0)){
            $tax_group_id = $myrow["tax_group_id"];
        }

	$order->set_supplier($supplier_id, $myrow["supp_name"], $myrow["curr_code"], 
		$tax_group_id, $myrow["tax_included"]);
}

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

function get_payment_terms_to_order(&$order, $supplier_id, $terms_indicator = 0)
{
    if($terms_indicator > 0){
        $pt = get_payment_terms($terms_indicator);
        $order->terms = array( 
            'terms_indicator' => $terms_indicator,
            'description' => $pt['terms'],
            'days_before_due' => $pt['days_before_due'], 
            'day_in_following_month' => $pt['day_in_following_month'] );
    }
    else{
        $myrow = get_supplier_payment_terms_details($supplier_id);
        $order->terms = array( 
            'terms_indicator' => $myrow['terms_indicator'],
            'description' => $myrow['terms'],
            'days_before_due' => $myrow['days_before_due'], 
            'day_in_following_month' => $myrow['day_in_following_month'] );
    }
}


function create_new_po($trans_type, $trans_no, $pr_no=0)
{
	global $Refs;

	if (isset($_SESSION['PO'])){
		unset ($_SESSION['PO']->line_items, $_SESSION['PO']);
        }

	$cart = new purch_order;
	$_POST['OrderDate'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['OrderDate'])){
		$_POST['OrderDate'] = end_fiscalyear();
        }
	$cart->due_date = $cart->orig_order_date = $_POST['OrderDate'];

	$cart->trans_type = $trans_type;
	$cart->order_no = $trans_no;
	/*read in all the selected order into the Items cart  */
	if ($trans_no) {
		read_po($trans_no, $cart, false, $pr_no);
		$cart->order_no = $trans_no;
	} 
        else{
		$cart->reference = $Refs->get_next($trans_type);
        }
	$_SESSION['PO'] = &$cart;
}

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

function display_po_header(&$order)
{
    global $Ajax, $Refs, $approval_statuses;
    
    if(isset($order->order_no) && $order->order_no > 0){
        $project_id = $order->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;
        }  
    }

    $editable = ($order->order_no == 0);

    start_outer_table(TABLESTYLE2, 'width=80%');

    table_section(1);
        if ($editable)
        {
            if (!isset($_POST['supplier_id']) && (get_global_supplier() != ALL_TEXT)){
                    $_POST['supplier_id'] = get_global_supplier();
            }

            if(count($order->line_items) > 0){
                supplier_list_row(_("Supplier:"), 'supplier_id', $order->temp_supplier_id, false, true, false, true);
            }
            else{
                supplier_list_row(_("Supplier:"), 'supplier_id', null, false, true, false, true);
            }
            
            if(list_updated('supplier_id')){            
                $_POST['supplier_tax_group_id'] = 0;
            }
            
            if(!(isset($_POST['supplier_tax_group_id']) && $_POST['supplier_tax_group_id'] > 0) && $_POST['supplier_id'] > 0){ 
                $supplier = get_supplier($_POST['supplier_id']);
                $_POST['supplier_tax_group_id'] = $supplier['tax_group_id'];
            }

        }
        else{
            hidden('supplier_id', $order->supplier_id);
            label_row(_("Supplier:"), $order->supplier_name);

            if(!(isset($_POST['supplier_tax_group_id']) && $_POST['supplier_tax_group_id'] > 0)){            
                $_POST['supplier_tax_group_id'] = $order->tax_group_id;
            }
        }

        tax_groups_list_row("Tax Group:", 'supplier_tax_group_id', null, false, true);
        
	if ($order->supplier_id != get_post('supplier_id',-1)) {
            $old_supp = $order->supplier_id;
            get_supplier_details_to_order($order, $_POST['supplier_id'], $_POST['supplier_tax_group_id']); 
            
        if (isset($order->terms["day_in_following_month"]) || isset($order->terms["days_before_due"])) {
            get_duedate_from_terms($order);
            $_POST['due_date'] = $order->due_date;
        }

            // supplier default price update
            foreach ($order->line_items as $line_no=>$item) {
                    $line = &$order->line_items[$line_no];
                    $line->price =  get_purchase_price ($order->supplier_id, $line->stock_id);
                    $line->quantity =
                            $line->quantity/get_purchase_conversion_factor ($old_supp, $line->stock_id)
                                    *get_purchase_conversion_factor ($order->supplier_id, $line->stock_id);
            }
	    $Ajax->activate('items_table');
	    $Ajax->activate('due_date');
	}
        else{
            $order->tax_group_id = $_POST['supplier_tax_group_id'];
            $order->tax_group_array = get_tax_group_items_as_array($order->tax_group_id);
        }
        
	set_global_supplier($_POST['supplier_id']);

	date_row($order->trans_type==ST_PURCHORDER ? _("Order Date:") :
		($order->trans_type==ST_SUPPRECEIVE ? _("Delivery Date:") : _("Invoice Date:")),
		'OrderDate', '', true, 0, 0, 0, null, true);

	if (isset($_POST['_OrderDate_changed'])) {
		$order->orig_order_date = $_POST['OrderDate'];
	    get_duedate_from_terms($order);
	    $_POST['due_date'] = $order->due_date;
		$Ajax->activate('due_date');
	}
        
	supplier_credit_row($order->supplier_id, $order->credit);

	if (!is_company_currency($order->curr_code))
	{
		label_row(_("Supplier Currency:"), $order->curr_code);
		exchange_rate_display(get_company_currency(), $order->curr_code,
			$_POST['OrderDate']);
	}

    
        if ($editable)
        {
            ref_row(_("Reference:"), 'ref');
        }
        else
        {
            hidden('ref', $order->reference);
            label_row(_("Reference:"), $order->reference);
        }
        locations_list_row(_("Receive Into:"), 'StkLocation', null, false, true); 

    table_section(2);

	if ($order->trans_type==ST_SUPPINVOICE)
		date_row(_("Due Date:"), 'due_date', '', false, 0, 0, 0, null, true);

    
        if(list_updated('supplier_id')){
            $supp_terms = get_supplier_payment_terms_details($_POST['supplier_id']);
            $_POST['terms_indicator'] = $supp_terms['terms_indicator'];
        }
    
        if(!(isset($_POST['terms_indicator']) && $_POST['terms_indicator'] > 0)){
            if($order->order_no > 0){
                $_POST['terms_indicator'] = $order->terms['terms_indicator'];
            }
            else{
                $supp_terms = get_supplier_payment_terms_details($_POST['supplier_id']);
                $_POST['terms_indicator'] = $supp_terms['terms_indicator'];
            }
        }
    
//    if((isset($order->terms_indicator) && $order->terms_indicator > 0)){
        payment_terms_list_row("Payment Terms:", 'terms_indicator', null, false, true);

        get_payment_terms_to_order($order, $_POST['supplier_id'], $_POST['terms_indicator']);
    
  	text_row(_("Supplier's Reference:"), 'supp_ref', null, 16, 15);
        
        if ($editable)
        {
            project_list_row(_("Project:"), 'project_id', null, _('Select a job'), true);
            
            if(isset($order->job_reference) && !list_updated('project_id')){
                label_row(_("Job Reference:"), $order->job_reference);
            }

            if(list_updated('project_id') && $_POST['project_id'] > 0)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            }    
            
            //tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], $task_id, _('Select a budget'), true);
            
            if ($_POST['project_id'] > 0)
            {
                $result = get_approval_path($_POST['project_id'], "PO");
                label_row(_("Approval Path:"), $result['approval_path_name']);
            }
            else {
                label_row(_("Approval Path:"),"");
            }
            
            label_row(_("Approval Status:"),"New");
            //yesno_list_row("Use Future Budgets", 'use_future_budgets', $order->use_future_budgets, "Yes", "No");
        }
        else
        {
            if(isset($_POST['project_id'])){
                $order->project_id  = $_POST["project_id"];
            }

            $order->approval_path_id = 0;
            $order->approval_path_description = '';
            
            

//            locations_list_row(_("Issuing Location:"), 'issuing_location', $order->issuing_location);
            if(!$order->generated_po){
                project_list_row(_("Job:"), 'project_id', $order->project_id,FALSE,TRUE);                
            }
            else{
                hidden('project_id', $order->project_id);
            }
            
            if(isset($order->job_reference) && !list_updated('project_id')){
                label_row(_("Job Reference:"), $order->job_reference);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $order->job_reference = $job_ref['description'];
                label_row(_("Job Reference:"), $order->job_reference);
            } 
            //tasks_list_row(_("Budget:"), 'task_id', $order->project_id, $order->task_id,false, TRUE);
            
            if(isset($_POST['project_id'])){
                $order->project_id  = $_POST["project_id"];
                $approval_path = get_approval_path($order->project_id, "PO");
                if($approval_path){
                    $order->approval_path_id = $approval_path['approval_path_id'];
                    $order->approval_path_description = $approval_path['approval_path_name'];
                }
            }
            
            label_row("Approval Path:", $order->approval_path_description);
            
            //yesno_list_row("Use Future Budgets", 'use_future_budgets', $order->use_future_budgets, "Yes", "No");
            
            $s = get_project_trans_view_str(98, $order->order_no."&source_type_id=".ST_PURCHORDER, "Approval Status");
            //label_cell($s);
            label_row($s,$approval_statuses[$order->approval_status]);
        }

    table_section(3);
        if (!isset($_POST['StkLocation']) || $_POST['StkLocation'] == "" ||
            isset($_POST['_StkLocation_update']) || !isset($_POST['delivery_address']) ||
            $_POST['delivery_address'] == "")
        {
            /*If this is the first time the form loaded set up defaults */

            //$_POST['StkLocation'] = $_SESSION['UserStockLocation'];
            $sql = "SELECT delivery_address, phone FROM ".TB_PREF."locations WHERE loc_code=".db_escape($_POST['StkLocation']);
            $result = db_query($sql,"could not get location info");

            if (db_num_rows($result) == 1)
            {
                    $loc_row = db_fetch($result);
                    $_POST['delivery_address'] = $loc_row["delivery_address"];
                            $Ajax->activate('delivery_address');
                    $_SESSION['PO']->Location = $_POST['StkLocation'];
                    $_SESSION['PO']->delivery_address = $_POST['delivery_address'];

            }
            else
            { /*The default location of the user is crook */
                    display_error(_("The default stock location set up for this user is not a currently defined stock location. Your system administrator needs to amend your user record."));
            }
        }

	textarea_row(_("Deliver to:"), 'delivery_address', $_POST['delivery_address'], 35, 4);

    end_outer_table(); // outer table
}

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

function display_po_items(&$order, $editable=true)
{
    display_heading(_("Order Items"));

    div_start('items_table');
    start_table(TABLESTYLE, "width=98%");

   	$th = array(_("ID"),_("PRs"),_("Allo."),_("Item Code"), _("Item Description"), _("Quantity"),
		_("Received"), _("Unit"),
   		_("Delivery Date"), _("Job"),
        $order->tax_included ? _("Price after Tax") : _("Price before Tax"),
        _("Discount"), _("Min Price"), _("Line Total"), "", "");
	if ($order->trans_type != ST_PURCHORDER)
		array_remove($th, 5);
		
	if (count($order->line_items)) $th[] = '';
   	table_header($th);

	$id = find_submit('Edit');
	$total = $discounts_total = 0;
	$k = 0;

   	foreach ($order->line_items as $line_no => $po_line)
   	{
    	$line_total =	round($po_line->tran_qty * $po_line->order_unit_price * (1 - $po_line->order_unit_price_discount/100),  user_price_dec());
    	$line_discount_total =	round($po_line->tran_qty * $po_line->order_unit_price * ($po_line->order_unit_price_discount/100),  user_price_dec());
    	if (!$editable || ($id != $line_no))
		{
    		alt_table_row_color($k);

                if(isset($po_line->row_id)){
                    label_cell($po_line->row_id, "align=center");
                    
                    $prs = get_pr_line_ids_string($po_line->row_id);
                    label_cell($prs, "align=center");
                
                    $pr_allocs = get_pr_allocation_ids_string($po_line->row_id);
                    label_cell($pr_allocs, "align=center");
                }
                else{
                    label_cell("");
                    label_cell("");                    
                    label_cell("");                    
                }
                
                
        	label_cell($po_line->stock_id);
    		label_cell($po_line->item_description);
//            qty_cell($po_line->quantity, false, get_qty_dec($po_line->stock_id));
                qty_cell($po_line->tran_qty, false, get_qty_dec($po_line->stock_id));
                    
                qty_cell($po_line->qty_received, false, get_qty_dec($po_line->stock_id));
    		if($po_line->tran_unit == ""){
                    label_cell($po_line->units);
                }
                else{
                    label_cell($po_line->tran_unit);
                }
			if ($order->trans_type == ST_PURCHORDER){
        	    label_cell($po_line->req_del_date);
                }
            
                label_cell($po_line->project_site_name);

                    amount_decimal_cell($po_line->order_unit_price);
                amount_decimal_cell($po_line->order_unit_price_discount);

                $discounted_minimum_price = $po_line->minimum_price * (1-$po_line->minimum_price_discount/100);
                amount_cell($discounted_minimum_price);
                amount_cell($line_total);

                if ($editable)
                {
                                edit_button_cell("Edit$line_no", _("Edit"),
                                  _('Edit document line'));
                                delete_button_cell("Delete$line_no", _("Delete"),
                                        _('Remove line from document'));
                }
		end_row();
                
                if(strlen($po_line->line_comment) > 0){
                    $k = $k == 0 ? 1 : 0;
                    alt_table_row_color($k);
                    label_cell("", 'colspan=4');
                    label_cell(nl2br($po_line->line_comment), 'colspan=9');
                    label_cell("", 'colspan=3');
                    end_row();
                }
            }
            else
            {
			po_item_controls($order, $k, $line_no);
		}
		$total += $line_total;
                $discounts_total += $line_discount_total;
    }

	if ($id==-1 && $editable){
		po_item_controls($order, $k);
    }
    
	$colspan = count($th)-2;
	if (count($order->line_items))
		$colspan--;

	$display_sub_total = price_format($total);

	label_row(_("Discounts Total"), price_format($discounts_total), "colspan=".($colspan)." align=right","align=right", 2);
	label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right", 2);

//	$taxes = $order->get_taxes(input_num('freight_cost'));
        
        $all_taxes = $order->get_all_taxes(input_num('freight_cost'));
	$staxes_total = $order->get_staxes_total(input_num('freight_cost'));
        
	$all_tax_total = display_edit_tax_items($all_taxes, $colspan, $order->tax_included, 2, $order->trans_type == ST_SUPPINVOICE);

        $tax_total = $all_tax_total - $staxes_total;
	$display_total = price_format(($total + input_num('freight_cost') + $tax_total));

	start_row();
	label_cells(_("Amount Total"), $display_total, "colspan=$colspan align='right'","align='right'");
	$order->order_no ? submit_cells('update', _("Update"), "colspan=2 align='center'", _("Refresh"), true)
		: label_cell('', "colspan=2");
	end_row();

	end_table(1);
	div_end();
}

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

function display_po_summary(&$po, $is_self=false, $editable=false){
    global $approval_statuses;
    
    start_table(TABLESTYLE, "width=90%");

    start_row();
        label_cells(_("Reference"), $po->reference, "class='tableheader2'");
        
        $supplier_name = get_supplier_formatted_name($po->supplier_id);
        label_cells(_("Supplier"), $supplier_name, "class='tableheader2'");
        label_cells(_("Supplier's Reference"), $po->supp_ref, "class='tableheader2'");

        if(!$is_self){
            label_cells(_("Purchase Order"), get_trans_view_str(ST_PURCHORDER, $po->order_no), "class='tableheader2'");
        }
    end_row();
	
    start_row();
        label_cells(_("Date"), $po->orig_order_date, "class='tableheader2'");

        if($editable){
            if(!isset($_POST['Location'])){
                $_POST['Location'] = $po->Location;
            }
            label_cell(_("Deliver Into Location"), "class='tableheader2'");
            locations_list_cells(null, 'Location', $_POST['Location']);
        }else{
            label_cells(_("Location"), get_location_name($po->Location), "class='tableheader2'");
            $tax_group = get_tax_group($po->tax_group_id);
            label_cells(_("Tax Group"), $tax_group['name'], "class='tableheader2'");
        }

    end_row();

    start_row();
        get_payment_terms_to_order($po, $po->supplier_id, $po->terms['terms_indicator']);
        label_cells(_("Payment Terms"), $po->terms['description'], "class='tableheader2'");
        label_cells(_("Order Currency"), $po->curr_code, "class='tableheader2'");
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $po->order_no."&source_type_id=".ST_PURCHORDER, "Approval Status");
        display_view_cell($s,$approval_statuses[$po->approval_status], "class='tableheader2'");
    end_row();
    
    start_row();
        label_cells(_("Delivery Address"), $po->delivery_address, "class='tableheader2'", "colspan=3");
        if(!is_company_currency($po->curr_code)){
            $link = get_supplier_trans_view_str(ST_IMPORT_PO_COST_DETAILS, $po->po_no,"View landed cost details");
            label_cells('Import PO Costs', $link, "class='tableheader2'", "colspan=0");
        }
    end_row();
    label_row(_("Project"), $po->project_description, "class='tableheader2'", "colspan=9");
    
    
    if($po->Comments != ""){
    	label_row(_("Order Comments"), nl2br($po->Comments), "class='tableheader2'", "colspan=9");
    }
    end_table(1);
}

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

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

        $price_caption = $order->tax_included ? _("Price After Tax") : _("Price Before Tax");
   
	alt_table_row_color($rowcounter);

	$dec2 = 0;
	$id = find_submit('Edit');
               
	if (($id != -1) && $line_no == $id)
	{
        // Editig an item
        
		$_POST['stock_id'] = $order->line_items[$id]->stock_id;
		$dec = get_qty_dec($_POST['stock_id']);
		$_POST['qty'] = qty_format($order->line_items[$id]->quantity, $_POST['stock_id'], $dec);
		$_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_qty, $order->line_items[$id]->stock_id, $dec);
		$_POST['price'] = price_decimal_format($order->line_items[$id]->price, $dec2);
                $_POST['order_unit_price'] = price_decimal_format($order->line_items[$id]->order_unit_price, $dec2);
		if ($order->trans_type == ST_PURCHORDER){
			$_POST['req_del_date'] = $order->line_items[$id]->req_del_date;
                }

		$_POST['units'] = $order->line_items[$id]->units;
		$_POST['item_description'] = $order->line_items[$id]->item_description;
                $_POST['project_site_id'] = $order->line_items[$id]->project_site_id;
                $_POST['order_unit_price_discount'] = price_decimal_format($order->line_items[$id]->order_unit_price_discount, $dec2);

                if(isset($order->line_items[$id]->row_id)){
                    label_cell($order->line_items[$id]->row_id, "align=center");
                    
                    $prs = get_pr_line_ids_string($order->line_items[$id]->row_id);
                    label_cell($prs, "align=center");

                    $pr_allocs = get_pr_allocation_ids_string($order->line_items[$id]->row_id);
                    label_cell($pr_allocs, "align=center");
                }
                else{
                    label_cell("");
                    label_cell("");
                    label_cell("");
                }
                
                echo "<td colspan=10>";       
                start_outer_table(TABLESTYLE2, "width=100%");
                table_section(1);
                    hidden('stock_id', $_POST['stock_id']);
                    label_row("Item Code", $_POST['stock_id']);

                    if ($order->line_items[$id]->descr_editable){
                            if(!isset_string_post('item_description')){
                                $_POST['item_description'] = $order->line_items[$id]->item_description;
                            }                             
//                            text_row("Item Code",'item_description', null, 45, 250);
                            textarea_row("Description", 'item_description', null, 20, 2, "", "align=right");
                            
                    }
                    else {
                            hidden('item_description', $_POST['item_description']);
    //			label_cell($_POST['item_description']);
                            label_row("Description", $order->line_items[$id]->item_description); 
                    }

                table_section(2);
                    $Ajax->activate('items_table');
                    $qty_rcvd = $order->line_items[$id]->qty_received;

                    if(!(isset($_POST['tran_unit']) && strlen($_POST['tran_unit']) > 1)){
                        $_POST['tran_unit'] = $order->line_items[$id]->tran_unit;
                    }
                
//                if($tran_unit == ""){
//                    $tran_unit = $_POST['tran_unit'];
//                }

//                hidden('tran_unit', $tran_unit);
//                label_cell($tran_unit, null, 'tran_unit');
                    units_list_row("Unit", 'tran_unit', $_POST['stock_id'], null, false, false);
                    $tran_unit = $_POST['tran_unit'];
        
                    hidden('qty', $_POST['qty']);

                    if(!isset($_POST['tran_qty'])){
                        $_POST['tran_qty'] = 1.00;
                    }
                    qty_row("Quantity", 'tran_qty', null, null, null, $dec);

                    label_row("Qty Received", $qty_rcvd, false, $dec);

                table_section(3);
                
                    date_row('Delivery Date', 'req_del_date', '', null, 0, 0, 0);

                    if(isset($_POST['project_site_id']) && $_POST['project_site_id'] > 0){
                        $project_site_id = $_POST['project_site_id'];
                    }
                    else{
                        $project_site_id = $order->line_items[$id]->project_site_id;
                    }
//              locations_list_cells(null, 'line_loc_code', $line_loc_code, "Select a location");
                    project_sites_list_row("Job", 'project_site_id', get_post('project_id'), null, "Select a job" );

                table_section(4);
                    if($qty_rcvd == 0 && 
                            (list_updated('supplier_id') || list_updated('stock_id') || list_updated('tran_unit') || list_updated('project_id'))){
                        $sup_price = get_supplier_price(get_post('stock_id'), get_post('supplier_id'), $_POST['project_id'], $tran_unit, $_POST['req_del_date']);    

                        if(isset($sup_price['price'])){
                            $_POST['order_unit_price'] = $sup_price['price'];
                            $_POST['order_unit_price_discount'] = $sup_price['discount'];
                        }
                        else{
                            $_POST['order_unit_price'] = 0.00;
                            $_POST['order_unit_price_discount'] = 0.00;
                        }

                    }
 
                if(!isset($_POST['order_unit_price']) || $qty_rcvd > 0){
                    $order_unit_price = $order->line_items[$id]->order_unit_price;
                }
                else{
                    $order_unit_price = $_POST['order_unit_price'];
                }
                $_POST['order_unit_price'] = $order_unit_price;
        
        
                if(!isset($_POST['order_unit_price_discount']) || $qty_rcvd > 0){
                    $order_unit_price_discount = $order->line_items[$id]->order_unit_price_discount;
                }
                else{
                    $order_unit_price_discount = $_POST['order_unit_price_discount'];
                }
                $_POST['order_unit_price_discount'] = $order_unit_price_discount;

                if ($qty_rcvd > 0)
                {
                    // If some quantities are received do not allow changing price
                    label_row($price_caption, price_format($order_unit_price));
                    hidden('order_unit_price', $order_unit_price);

                    label_row("Discount", price_format($order_unit_price_discount));
                    hidden('order_unit_price_discount', $order_unit_price_discount);

                    hidden('price', $_POST['price']);
                }	
                else{	
                    amount_row($price_caption, 'order_unit_price', null, null, null, $dec2);
                    amount_row("Discount", 'order_unit_price_discount', null, null, null, 2);
                    hidden('price', $_POST['price']);
                }
        
        	//$line_total = $_POST['qty'] * $_POST['price'] * (1 - $_POST['Disc'] / 100);
                $line_total = round(input_num('tran_qty') * input_num('order_unit_price') * (1-input_num('order_unit_price_discount')/100),  user_price_dec());

                $order_unit_min_price = 0;
                $order_unit_min_price_discount = 0;
                $min_price_sup_id = 0;

                $min_price = get_purchase_minimum_price(get_post('stock_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['req_del_date']);    
                if(isset($min_price['price'])){
                    $order_unit_min_price = $min_price['price'];
                    $order_unit_min_price_discount = $min_price['discount'];
                    $min_price_sup_id = $min_price['supplier_id'];
                }

        //      amount_decimal_cell($order_unit_min_price);
           
                hidden('minimum_price', $order_unit_min_price);
                hidden('minimum_price_discount', $order_unit_min_price_discount);
                hidden('min_price_supplier_id', $min_price_sup_id);

                $discounted_min_price = number_format2($order_unit_min_price*(1-$order_unit_min_price_discount/100),2);
                label_row("Min Price",$discounted_min_price, false, "", 'discounted_min_price');
                
            table_section(5);  
                if(list_updated('tran_unit')){
                        // Do not update the entered value
                    }
                    else{
                        $_POST['line_comment'] = $order->line_items[$id]->line_comment;
                    }
                    textarea_row("Comment", 'line_comment', null, 20, 2, "", "align=right");
            end_outer_table();

            echo "</td>";
            
                amount_cell($line_total, false, '','line_total');   

                //label_cell("Calculating","align=right");

                button_cell('UpdateLine', _("Update"), _('Confirm changes'), ICON_UPDATE);
		button_cell('CancelUpdate', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
                
		hidden('line_no', $line_no);
		set_focus('qty');
        
	}
	else
	{
        // New item

                label_cell("");
                label_cell("");
                label_cell("");
                
                echo "<td colspan=10>";       
                start_outer_table(TABLESTYLE2, "width=100%");
                table_section(1);
                    //Chaitanya : Manufcatured item can be purchased
                    stock_items_list_row("Item Code", 'stock_id', null, false, true, false, true);
                    //stock_purchasable_items_list_cells(null, 'stock_id', null, false, true, true);
                    if (list_updated('stock_id')) {
                                $Ajax->activate('price');
                                $Ajax->activate('units');
                                $Ajax->activate('qty');
                                $Ajax->activate('req_del_date');
                                $Ajax->activate('line_total');
                    $Ajax->activate('tran_unit');
                    $Ajax->activate('tran_qty');
                    $Ajax->activate('minimum_price');
                    }
                    
                    $dec = 0; 
                    $item_info = get_item_edit_info($_POST['stock_id']);
                    if (isset($item_info["units"]) && strlen($item_info["units"]) > 0) {
                        $_POST['units'] = $item_info["units"];
                        $dec = $item_info["decimals"];
                    }

//   		$_POST['qty'] =	number_format2(get_purchase_conversion_factor ($order->supplier_id, $_POST['stock_id']), $dec);
		//$_POST['price'] = price_format(get_purchase_price ($order->supplier_id, $_POST['stock_id']));
//		$_POST['price'] = price_decimal_format(get_purchase_price ($order->supplier_id, $_POST['stock_id']), $dec2);
                    if ($order->trans_type == ST_PURCHORDER){
                            $_POST['req_del_date'] = add_days(Today(), $SysPrefs->default_delivery_required_by());
                    }
                    $qty_rcvd = '';
	
            table_section(2);
                units_list_row("Unit", 'tran_unit', $_POST['stock_id'], null, false, true);
                $tran_unit = $_POST['tran_unit'];
        //hidden('qty', $_POST['qty']);

                if(!isset($_POST['tran_qty'])){
                    $_POST['tran_qty'] = 1.00;
                }
                qty_row("Quantity", 'tran_qty', null, null, null, $dec);

//            label_row("Qty. Received", $qty_rcvd, false, $dec);
         
    
                if ($order->trans_type == ST_PURCHORDER){
                    date_row('Delivery Date', 'req_del_date', '', null, 0, 0, 0);
                }

//        $_POST['line_loc_code'] = $_POST['StkLocation'];
                project_sites_list_row("Job", 'project_site_id', get_post('project_id'), null, "Select a job" );

                if(!isset($_POST['req_del_date'])){
                    $_POST['req_del_date'] = $_POST['OrderDate'];
                }
        
            table_section(4);
         
                if(list_updated('supplier_id') || list_updated('stock_id') || list_updated('tran_unit') || list_updated('project_id')){
                    $sup_price = get_supplier_price(get_post('stock_id'), get_post('supplier_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['req_del_date']);    

                    if(isset($sup_price['price'])){
                        $_POST['order_unit_price'] = $sup_price['price'];
                        $_POST['order_unit_price_discount'] = $sup_price['discount'];
                    }
                    else{
                        $_POST['order_unit_price'] = 0.00;
                        $_POST['order_unit_price_discount'] = 0.00;
                    }
                }

                $order_unit_price = 0;
                $order_unit_price_discount =0;

                if(!isset($_POST['order_unit_price'])){
                    $sup_price = get_supplier_price(get_post('stock_id'), get_post('supplier_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['req_del_date']);   
                    if (isset($sup_price['price'])) {
                        $order_unit_price = $sup_price['price'];
                        $order_unit_price_discount = $sup_price['discount'];
                    }
                }
                else{
                    $order_unit_price = $_POST['order_unit_price'];
                }
                $_POST['order_unit_price'] = $order_unit_price;


                if(isset($_POST['order_unit_price_discount'])){
                    $order_unit_price_discount = $_POST['order_unit_price_discount'];
                }
                $_POST['order_unit_price_discount'] = $order_unit_price_discount;

                amount_row($price_caption, 'order_unit_price', null, null, null, 2);
                amount_row("Discount", 'order_unit_price_discount', null, null, null, 2);
//                hidden('price', $_POST['price']);
        
            table_section(5);    
                textarea_row("Comment", 'line_comment', null, 20, 2, "", "align=right");
            end_outer_table();
            echo "</td>";
            
            //$line_total = $_POST['qty'] * $_POST['price'] * (1 - $_POST['Disc'] / 100);
            $line_total = round(input_num('tran_qty') * input_num('order_unit_price'),  user_price_dec());

            $order_unit_min_price = 0;
            $order_unit_min_price_discount = 0;
            $min_price_sup_id = 0;
            
            //$base_unit_min_price = get_purchase_minimum_price(get_post('stock_id'), get_post('tran_unit'));
            if(strlen(get_post('stock_id')) > 0 && strlen(get_post('tran_unit')) > 0){
                $min_price = get_purchase_minimum_price(get_post('stock_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['req_del_date']);
            }

            if(isset($min_price['price'])){
                $order_unit_min_price = $min_price['price'];
                $order_unit_min_price_discount = $min_price['discount'];
                $min_price_sup_id = $min_price['supplier_id'];
            }

            $_POST['minimum_price_discount'] = $order_unit_min_price_discount;
            hidden('minimum_price', $order_unit_min_price);
            hidden('minimum_price_discount' );
            hidden('min_price_supplier_id', $min_price_sup_id);

            $discounted_min_price = number_format2($order_unit_min_price*(1-$order_unit_min_price_discount/100),2);
            amount_cell($discounted_min_price, false, "", 'discounted_min_price');
            amount_cell($line_total, false, '','line_total');

            submit_cells('EnterLine', _("Add Item"), "colspan=2 align='center'",
		    _('Add new item to document'), true);
	}

	end_row();
    
    		//if (list_updated('stock_id')) 
                {
			    $Ajax->activate('price');
			    $Ajax->activate('units');
			    $Ajax->activate('qty');
			    $Ajax->activate('req_del_date');
			    $Ajax->activate('line_total');
                $Ajax->activate('tran_unit');
                $Ajax->activate('tran_qty');
                $Ajax->activate('order_unit_price');
                $Ajax->activate('minimum_price');
                $Ajax->activate('discounted_min_price');
		}
}

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


function get_pr_allocation_ids_string($po_line_id){
    $pr_ids_info = get_pr_allocation_ids_for_po_line($po_line_id);
    $pr_ids_string = "";
    
    while($pr_ids=db_fetch($pr_ids_info)){
        $pr_ids = array_unique($pr_ids);
        foreach($pr_ids as $pr_id){
            $pr_ids_string .= get_supplier_trans_view_str(ST_PR_PO_DETAILS,$pr_id)." ";
        }
    }
    $pr_ids_string = trim($pr_ids_string);
    return $pr_ids_string;
}


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


function get_pr_line_ids_string($po_line_id){
    $pr_ids_info = get_pr_line_ids_for_po_line($po_line_id);
    $pr_ids_string = "";
    
    while($pr_ids=db_fetch($pr_ids_info)){
        $pr_ids_string .= get_supplier_trans_view_str(ST_PURCH_REQ,$pr_ids['requisition_id'], "(".$pr_ids['requisition_id'].")".$pr_ids['id'])." ";
        
    }
    $pr_ids_string = trim($pr_ids_string);
    return $pr_ids_string;
}



function check_saved_purchase_order_integrity($order_no){
    
        $full_message = "";
    
        $result = get_miss_matching_purchase_order_lines($order_no);
        while($po_integrity = db_fetch($result)){
            if(!($po_integrity['po_tax_included'] == $po_integrity['pod_tax_included'])){
                $message = "Line Id ".$po_integrity['pod_id'].": Supplier information (Tax Included) has been changed after saving this line. Please Update Line #".$po_integrity['pod_id'];
                $full_message .= $message. " \r\n ";
            }elseif(!($po_integrity['po_tax_group_id'] == $po_integrity['pod_tax_group_id'])){
                $message = "Line Id ".$po_integrity['pod_id'].": Tax Group has been changed after saving this line. Please Update Line #".$po_integrity['pod_id'];
                $full_message .= $message. " \r\n ";
            }               
        }
        
        if($full_message == ""){
            return array("success" => true, "message" => "");
        }
        else{
            return array("success" => false, "message" => nl2br($full_message));
        }
}


function check_po_class_purchase_order_integrity(){
    
        $full_message = "";
    
        if(isset($_POST['supplier_tax_group_id']) && $_POST['supplier_tax_group_id'] > 0){
                $po_obj = $_SESSION['PO'];
                foreach ($po_obj->line_items as $po_line){
                        if(isset($po_line->row_id) && $po_line->row_id > 0){
                                    $prefix = "Line Id ".$po_line->row_id;
                        }
                        else{
                            $prefix = "Item ".$po_line->stock_id." - ".$po_line->item_description; 
                        }
                        
                        if($po_line->tax_group_id != $_POST['supplier_tax_group_id']){                                
                                $message = $prefix.": Tax Group has been changed after saving this line. Please Update this Line.";
                                $full_message .= $message. " \r\n ";
                        }
                        elseif($po_line->tax_included != $po_obj->tax_included){
                                $message = $prefix.": Supplier information (Tax Included) has been changed after saving this line. Please this Line.";
                                $full_message .= $message. " \r\n ";
                        }
                }
        }
        
        if($full_message == ""){
                return array("success" => true, "message" => "");
        }
        else{
                return array("success" => false, "message" => nl2br($full_message));
        }
}


?>