<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_GRN';
$path_to_root = "..";
include_once($path_to_root . "/purchasing/includes/po_class.inc");

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/purchasing/includes/purchasing_db.inc");
include_once($path_to_root . "/purchasing/includes/ui/purchasing_ui.inc");
include_once($path_to_root . "/inventory/includes/lots_validation.inc");
include_once($path_to_root . "/inventory/includes/serial_no_validation.inc");
include_once($path_to_root . "/inventory/includes/db/serial_no_adjustments_db.inc");
include_once($path_to_root . "/inventory/includes/db/serial_no_db.inc");

include_once($path_to_root . "/purchasing/includes/pr_validations.inc");
include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/purchasing/includes/db/pr_issues_db.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/includes/db/project_cost_functions_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");


$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Receive Purchase Order Items"), false, false, "", $js);

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

if (isset($_GET['AddedID']))
{
	$grn = $_GET['AddedID'];
        
        $pri_id = 0;
        if(isset($_GET['PriID'])){
            $pri_id = $_GET['PriID'];
        }
	$trans_type = ST_SUPPRECEIVE;

        if($pri_id > 0){
            display_warning("PR Issue may have lesser quantities than the GRN. Please view PR Issue before issuing any items");
            br(1);
            display_note(get_trans_view_str(ST_PR_ISSUE, $pri_id, _("&View PR Issue")));
            br(1);
        }
        else{
            display_notification_centered(_("Purchase Order Delivery #$grn has been created"));
            br(1);
        }
        

	display_note(get_trans_view_str($trans_type, $grn, _("&View this Delivery")));
        
        
	
//        $clearing_act = get_company_pref('grn_clearing_act');
//	if ($clearing_act)	
//		display_note(get_gl_view_str($trans_type, $grn, _("View the GL Journal Entries for this Delivery")), 1);

//	hyperlink_params("$path_to_root/purchasing/supplier_invoice.php", _("Entry purchase &invoice for this receival"), "New=1");

	hyperlink_no_params("$path_to_root/purchasing/inquiry/po_search.php", _("Select a different &purchase order for receiving items against"));

	display_footer_exit();
}



if (isset($_GET['ClosedID']))
{
	$po_no = $_GET['ClosedID'];
	$trans_type = ST_SUPPRECEIVE;

	display_notification_centered(_("Purchase Order ".$po_no." has been closed"));

	display_footer_exit();
}

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

if ((!isset($_GET['PONumber']) || $_GET['PONumber'] == 0) && !isset($_SESSION['PO']))
{
	die (_("This page can only be opened if a purchase order has been selected. Please select a purchase order first."));
}

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

function display_po_receive_items($pr_no)
{
    global $Ajax;
    
	div_start('grn_items');
    start_table(TABLESTYLE, "colspan=7 width=98%");
    if($_SESSION['PO']->receiving_pr_no > 0){
        $th = array("Id", "PRs", "Alloc.", _("Item Code"), _("Description"), _("Job"), _("Units"),_("Ordered"),_("Received"), _("PR Qty"),_("Issd Qty"), _("Rec. Unit"), _("Receiving Qty"), _("Price"), _("Discount"), _("Total"), "", "");
    }
    else{
        $th = array("Id", "PRs", "Alloc.", _("Item Code"), _("Description"), _("Job"), _("Units"),_("Ordered"),_("Received"),                             _("Rec. Unit"), _("Receiving Qty"), _("Price"), _("Discount"), _("Total"), "", "");
    }
    
    table_header($th);

    /*show the line items on the order with the quantity being received for modification */

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

    if (count($_SESSION['PO']->line_items)> 0 )
    {
       	foreach ($_SESSION['PO']->line_items as $ln_itm)
       	{
            
            alt_table_row_color($k);
            
            $prefix = $ln_itm->pr_line_id."_".$ln_itm->pr_po_line_id."_".$ln_itm->row_id;
            
            if($_SESSION['PO']->receiving_pr_no > 0){
//                $ids_text = $ln_itm->pr_line_id." ".$ln_itm->pr_po_line_id." ".$ln_itm->row_id;
                $ids_text = $ln_itm->row_id;
            }
            else{
                $ids_text = $ln_itm->row_id;
            }
                label_cell($ids_text);
            
                $prs = get_pr_line_ids_string($ln_itm->row_id);
                label_cell($prs, "align=center");
                
                $pr_allocs = get_pr_allocation_ids_string($ln_itm->row_id);
                label_cell($pr_allocs, "align=center");
                
                
            
    		$qty_outstanding = $ln_itm->quantity - $ln_itm->qty_received;

 		if (!isset($_POST['Update']) && !isset($_POST['ProcessGoodsReceived']) && $ln_itm->receive_qty == 0)
    	  	{   //If no quantites yet input default the balance to be received
                    $ln_itm->receive_qty = $qty_outstanding;
    		}


                label_cell($ln_itm->stock_id);
                if ($qty_outstanding > 0){
                        text_cells(null, $prefix."Desc", $ln_itm->item_description, 30, 50);
                }
		else{
			label_cell($ln_itm->item_description);
                }
            
            
			$dec = get_qty_dec($ln_itm->stock_id);
            
//            label_cell($ln_itm->line_location_name);
            if(get_post($prefix.'_site_id') > 0){
                $project_site_id = get_post($prefix.'_site_id');
            }
            else{
                $project_site_id = $ln_itm->project_site_id;
            }
            project_sites_list_cells(null, $prefix.'_site_id', $_SESSION['PO']->project_id, $project_site_id,"");
            
            label_cell($ln_itm->alternate_unit_name);
             
            //PO quantities
            qty_cell($ln_itm->order_unit_qty, false, $dec);
			
            $tran_unit_rec_qty = $ln_itm->qty_received / $ln_itm->order_unit_conv_factor;
            qty_cell($tran_unit_rec_qty, false, $dec);
            
            //PR quantities
            if($_SESSION['PO']->receiving_pr_no > 0){
                $tran_unit_pr_qty = $ln_itm->pr_qty / $ln_itm->order_unit_conv_factor;
                qty_cell($tran_unit_pr_qty, false, $dec);
                $tran_unit_pr_iss_qty = $ln_itm->pr_issued_qty / $ln_itm->order_unit_conv_factor;
                qty_cell($tran_unit_pr_iss_qty, false, $dec);
            }
            
//			qty_cell($qty_outstanding, false, $dec);
            
            if(get_post($prefix.'_tran_unit') != ''){
                $current_tran_unit = get_post($prefix.'_tran_unit');
            }
            else{
                $current_tran_unit = $ln_itm->tran_unit;
            }
            
            $alternate_unit = get_alternate_unit_info($ln_itm->stock_id, $current_tran_unit);
            if($alternate_unit){
                $alternate_unit_convertion_factor = $alternate_unit['convertion_factor'];
            }
            else{
                $alternate_unit_convertion_factor = 1;
            }

            $ln_itm->receive_unit_conv_factor = $alternate_unit_convertion_factor;
            
//            units_list_cells(null, $ln_itm->row_id.'_tran_unit', $ln_itm->stock_id, $alternate_unit['alternate_unit'], false, true);
            
            $suggested_recev_qty_po = $suggested_issu_qty_pr = 0;
            if(list_updated($prefix.'_tran_unit') || !isset($_POST[$prefix."_tran_qty"] )){
                $base_unit_ord_qty_po = $ln_itm->quantity; //* $ln_itm->convertion_factor;
                $suggested_recev_qty_po = ( $base_unit_ord_qty_po - $ln_itm->qty_received) / $ln_itm->receive_unit_conv_factor;
                if($suggested_recev_qty_po < 0){
                    $suggested_recev_qty_po = 0;
                }
                
                $base_unit_req_qty_pr = $ln_itm->pr_qty; // * $ln_itm->convertion_factor;
                $suggested_issu_qty_pr = ( $base_unit_req_qty_pr - $ln_itm->pr_issued_qty) / $ln_itm->receive_unit_conv_factor;
                if($suggested_issu_qty_pr < 0){
                    $suggested_issu_qty_pr = 0;
                }
                
                $suggested_grn_qty = $suggested_recev_qty_po;
                if($pr_no > 0 && $suggested_grn_qty > $suggested_issu_qty_pr){
                    $suggested_grn_qty = $suggested_issu_qty_pr;
                }
                $_POST[$prefix."_tran_qty"] = $suggested_grn_qty;
            }
            else{
                $suggested_grn_qty = input_num($prefix."_tran_qty");
            }

//            qty_cells(null, $ln_itm->row_id."_qty", $suggested_issu_qty, null, null, $dec);
            
            units_list_cells(null, $prefix.'_tran_unit', $ln_itm->stock_id, $current_tran_unit, false, true);
            $unit_of_parent = get_post($prefix.'_tran_unit');

            $item_info = get_item_edit_info($ln_itm->stock_id);
            $_POST['stock_control_method'] = $item_info["stock_control_method"];

            display_quantity_cells(get_post('guid'), ST_SUPPRECEIVE, $ln_itm->line_ref, $ln_itm->stock_id, 
                                            $item_info["stock_control_method"], $prefix.'_', $suggested_grn_qty, $unit_of_parent, 
                                            $dec = 2, "items_table");

//			if ($qty_outstanding > 0)
//				qty_cells(null, $ln_itm->line_no, number_format2($ln_itm->receive_qty, $dec), "align=right", null, $dec);
//			else
//				label_cell(number_format2($ln_itm->receive_qty, $dec), "align=right");

			amount_decimal_cell($ln_itm->order_unit_price);
            
            amount_decimal_cell($ln_itm->order_unit_price_discount);
            
//            $order_unit = get_alternate_unit_info($ln_itm->stock_id, $ln_itm->stock_id);
//            if($alternate_unit){
//                $alternate_unit_convertion_factor = $alternate_unit['convertion_factor'];
//            }
//            else{
//                $alternate_unit_convertion_factor = 1;
//            }
            
            
            $ln_itm->receive_qty = input_num($prefix."_tran_qty") * $ln_itm->receive_unit_conv_factor; 
            $ln_itm->price = $ln_itm->order_unit_price * (1-$ln_itm->order_unit_price_discount/100)/ $ln_itm->order_unit_conv_factor;
        
            if(isset($_POST[$prefix.'_check_grn_item']) && $_POST[$prefix.'_check_grn_item'] == true){
//              $line_total = ($ln_itm->receive_qty * $ln_itm->price);
                $line_total = (input_num($prefix."_tran_qty") * $ln_itm->order_unit_price * (1-$ln_itm->order_unit_price_discount/100) / $ln_itm->order_unit_conv_factor * $ln_itm->receive_unit_conv_factor);
            }
            else{
                $line_total = 0;
            }
            
            $total += $line_total;
            
            amount_cell($line_total);
            
            if($_POST['stock_control_method'] == SKCM_LOTS || $_POST['stock_control_method'] == SKCM_SERIAL_NOS){
                button_cell("UpdateItem", _("Update"), _('Confirm changes'), ICON_UPDATE);
//                hidden('LineNo', $line_no);
            }
            else{
                label_cell('');
            }
            
            if($ln_itm->requisition_id == $pr_no){
                check_cells(null, $prefix.'_check_grn_item');
            }
            elseif($pr_no == -1){
                check_cells(null, $prefix.'_check_grn_item');
            }
            else{
//                label_cell('');
                check_cells(null, $prefix.'_check_grn_item');
            }
            
			end_row();
       	}
    }

	$colspan = count($th)-3;

	$display_sub_total = price_format($total/* + input_num('freight_cost')*/);

	label_row(_("Sub-total"), $display_sub_total, "colspan=$colspan align=right","align=right");
        
//	$taxes = $_SESSION['PO']->get_taxes(input_num('freight_cost'), true);
        $all_taxes = $_SESSION['PO']->get_all_taxes(input_num('freight_cost'), true);
	
//	$tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['PO']->tax_included);
        $all_taxes_total = display_edit_tax_items($all_taxes, $colspan, $_SESSION['PO']->tax_included);
        
        $staxes_total = 0;
        foreach ($all_taxes as $taxitem) // Calculate staxes only for the receiving item quantities
	{
            if ($taxitem['suspended'] == 1 && $taxitem['Value'] != 0){
                $staxes_total += $taxitem['Value'];
            }
        }

        $tax_total = $all_taxes_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'");
	end_row();
    end_table();
	div_end();
}

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

function check_po_changed()
{
	/*Now need to check that the order details are the same as they were when they were read
	into the Items array. If they've changed then someone else must have altered them */
	// Sherifoz 22.06.03 Compare against COMPLETED items only !!
	// Otherwise if you try to fullfill item quantities separately will give error.
	$result = get_po_items($_SESSION['PO']->order_no);

	$line_no = 0;
	while ($myrow = db_fetch($result))
	{
        foreach ($_SESSION['PO']->line_items as $ln_item) {            
            if($ln_item->row_id == $myrow['po_detail_item']){
                $qty_outstanding = $ln_item->quantity - $ln_item->qty_received;
                // only compare against items that are outstanding
                if ($qty_outstanding > 0)
                {
                    if ($ln_item->qty_inv != $myrow["qty_invoiced"]){
                        return true;
                    }
                    elseif($ln_item->stock_id != $myrow["item_code"]){
                        return true;
                    }
                    elseif((string)$ln_item->quantity != $myrow["quantity_ordered"]){
                        return true;
                    }
                    elseif($ln_item->qty_received != $myrow["quantity_received"]){
                        return true;
                    }
                }
            }
        }
	 	$line_no++;
	} /*loop through all line items of the order to ensure none have been invoiced */

    $po = get_po_edit_info($_SESSION['PO']->order_no);
    if($po['row_state'] != $_SESSION['PO']->row_state){
        return true;
    }
    
    if($po['approval_status'] == AS_APPROVED){
        return false;
    }    
    else{// Might have reopened or closed
	return true;
    }
}

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

function can_process_po_receive()
{
	global $SysPrefs, $Refs;
	
	if(!(isset($_SESSION['PO']->receiving_pr_no) && $_SESSION['PO']->receiving_pr_no > 0)){// No PR selected
            if(!$_SESSION["wa_current_user"]->can_access('SA_GRNS_WITHOUT_PRS'))// No access to receive item without a PR        
            {
                display_error(_("You are not alllowed to receive items without a purchase requisition."));
                return false;
            }
        }
	
	if (count($_SESSION['PO']->line_items) <= 0)
	{
        display_error(_("There is nothing to process. Please enter valid quantities greater than zero."));
    	return false;
	}

        if (!(strlen(get_post('Location')) > 1)) 
	{
		display_error(_("Please select receiving Location."));
		set_focus('Location');
		return false;
	}
    
	if (!is_date($_POST['DefaultReceivedDate']))
	{
		display_error(_("The entered date is invalid."));
		set_focus('DefaultReceivedDate');
		return false;
	}

	if (!is_date_in_fiscalyear($_POST['DefaultReceivedDate'])) 
	{
		display_error(_("The entered date is not in fiscal year"));
		set_focus('DefaultReceivedDate');
		return false;
	}
        
        $msg = is_accounting_period_open($_POST['DefaultReceivedDate']);
        if ($msg['success'] !== true)
        {
            display_error($msg['message']);
            set_focus('DefaultReceivedDate');
            return false;
        }

        if (!(get_post('project_id') > 0)) 
	{
		display_error(_("Please select a project."));
		set_focus('project_id');
		return false;
	}


        if (!$Refs->is_valid($_POST['ref']))
        {
		display_error(_("You must enter a reference."));
		set_focus('ref');
		return false;
	}

//	if (!is_new_reference($_POST['ref'], ST_SUPPRECEIVE))
//	{
//		display_error(_("The entered reference is already in use."));
//		set_focus('ref');
//		return false;
//	}
        $ref_msg = reference_exists($_POST['ref'], ST_SUPPRECEIVE);
        if($ref_msg){
            display_error($ref_msg);
            set_focus('ref');
            return false;
        }

	$something_received = 0;
	foreach ($_SESSION['PO']->line_items as $order_line)
	{
	  	if ($order_line->item_selected == true && $order_line->receive_qty > 0)
	  	{
			$something_received = 1;
			break;
	  	}
	}

        if ($something_received == 0)
        { 
            display_error(_("There is nothing to process. Please enter valid quantities greater than zero and select the lines."));
            return false;
        }
        
        // Check whether trying to deliver more items than are recorded on the actual purchase order (+ overreceive allowance)
        $delivery_qty_too_large = 0;
	foreach ($_SESSION['PO']->line_items as $order_line)
	{
            if($order_line->item_selected == true){
                // PO Line
                $receiving_base_unit_qty = $order_line->receive_qty+$order_line->qty_received;
                $receiving_tran_unit_qty = $receiving_base_unit_qty / $order_line->convertion_factor;
                
                $receiving_allowed_base_unit_qty = $order_line->quantity * (1+ ($SysPrefs->over_receive_allowance() / 100));
                $receiving_allowed_tran_unit_qty = $receiving_allowed_base_unit_qty / $order_line->convertion_factor;
                
                if ($receiving_tran_unit_qty > $receiving_allowed_tran_unit_qty + 0.00000001 )
                {
                    $delivery_qty_too_large = 1;
                    $tran_unit_received_qty = $order_line->qty_received / $order_line->convertion_factor;
                    
                    $s = "Line Id ".$order_line->po_detail_rec." : Item ".$order_line->stock_id." - ".$order_line->item_description;
                    $n = ($receiving_allowed_tran_unit_qty - $tran_unit_received_qty) > 0 ? ($receiving_allowed_tran_unit_qty - $tran_unit_received_qty): 0;
                    $s .= " - Maximum allowed receiving qty is ".number_format($n,2).".";
                    $s .= '<br>'." Total quantity already received is ".number_format($tran_unit_received_qty,2).".";
                    $s .= " Maximum allowed quantity including the allowed over-receive percentage is ".number_format($receiving_allowed_tran_unit_qty,2).".";
                    display_error(_($s));
                    
                    return false;
                }
                
                // PR line
//                if($_SESSION['PO']->receiving_pr_no > 0){
//                        $pr_issuing_base_unit_qty = $order_line->receive_qty + $order_line->pr_issued_qty;
//                        $pr_issuing_tran_unit_qty = $pr_issuing_base_unit_qty / $order_line->convertion_factor;
//
//                        $pr_issuing_allowed_base_unit_qty = $order_line->pr_qty;
//                        $pr_issuing_allowed_tran_unit_qty = $pr_issuing_allowed_base_unit_qty / $order_line->convertion_factor;
//
//                        if ($pr_issuing_tran_unit_qty > $pr_issuing_allowed_tran_unit_qty + 0.00000001 )
//                        {
//                            $delivery_qty_too_large = 1;
//                            $pr_tran_unit_issued_qty = $order_line->pr_issued_qty / $order_line->convertion_factor;
//
//                            $s = "Line Id ".$order_line->po_detail_rec." : Item ".$order_line->stock_id." - ".$order_line->item_description;
//                            $n_pr = ($pr_issuing_allowed_tran_unit_qty - $pr_tran_unit_issued_qty) > 0 ? ($pr_issuing_allowed_tran_unit_qty - $pr_tran_unit_issued_qty): 0;
//                            $s .= " - Purchase Requisition - Maximum allowed issuing qty is ".number_format($n_pr,2).".";
//                            $s .= '<br>'." Total quantity already issued is ".number_format($pr_tran_unit_issued_qty,2).".";
//                            $s .= " Maximum allowed issuing quantity is ".number_format($pr_issuing_allowed_tran_unit_qty,2).".";
//                            display_error(_($s));
//
//                            return false;
//                        }
//                }
            }
	}

    $vtqd_msg = validate_transaction_quantity_details($_SESSION['PO']);
    if ($vtqd_msg['success'] !== true) 
    {
        display_error($vtqd_msg['message']);
        return false;
    }
    
	return true;
}

function add_lot_details()
{
    foreach ($_SESSION['PO']->line_items as &$line_item) {
        $lot_details = get_selected_lot_serial_info('guid', $line_item);   
        $line_item->lot_details = $lot_details; 
    }    
}  
//--------------------------------------------------------------------------------------------------

function process_receive_po()
{
	global $path_to_root, $Ajax;
    
    add_lot_details();
	if (!can_process_po_receive())
		return;

	if (check_po_changed())
	{
		display_error(_("This order has been changed or invoiced since this delivery was started 
                    to be actioned. Processing halted. To enter a delivery against this purchase order, 
                    it must be re-selected and re-read again to update the changes made by the other user."));

		hyperlink_no_params("$path_to_root/purchasing/inquiry/po_search.php",
		 _("Select a different purchase order for receiving goods against"));

		hyperlink_params("$path_to_root/purchasing/po_receive_items.php", 
			 _("Re-Read the updated purchase order for receiving goods against"),
			 "PONumber=" . $_SESSION['PO']->order_no);

		unset($_SESSION['PO']->line_items);
		unset($_SESSION['PO']);
		unset($_POST['ProcessGoodsReceived']);
		$Ajax->activate('_page_body');
		display_footer_exit();
	}
	
	$grn = &$_SESSION['PO'];
	$grn->orig_order_date = $_POST['DefaultReceivedDate'];
	$grn->reference = $_POST['ref'];
	$grn->Location = $_POST['Location'];
	$grn->ex_rate = input_num('_ex_rate', null);

        begin_transaction();
        $grn_no = add_grn($grn);
        if($grn_no > 0){
            if($grn->receiving_pr_no > 0 && $grn->pr_complete == 0){// receiving with a pr
	//                $cigrn = create_pr_issue_for_grn($grn->receiving_pr_no, $grn, $grn_no);	
//                if($cigrn['success'] !== true){//GRN successful but PR is not successful	
//                    cancel_transaction();// GRN will be rolled back	
//                    display_error($cigrn['message']);	
//                }	
//                else{//GRN & PR successful	
                    commit_transaction();	
                    new_doc_date($_POST['DefaultReceivedDate']);	
                    unset($_SESSION['PO']->line_items);	
                    unset($_SESSION['PO']);	
//                    $pr_issue_no = $cigrn["tran_no"];	
//                    meta_forward($_SERVER['PHP_SELF'], "AddedID=$grn_no&PriID=$pr_issue_no");	
                    meta_forward($_SERVER['PHP_SELF'], "AddedID=$grn_no");	
//                }
            }
            else{//GRN successful. No PR
                commit_transaction();
                new_doc_date($_POST['DefaultReceivedDate']);
                unset($_SESSION['PO']->line_items);
                unset($_SESSION['PO']);
                meta_forward($_SERVER['PHP_SELF'], "AddedID=$grn_no");
            }
        }
        else{// No GRN
            display_error("Could not create GRN");
            cancel_transaction();
        }
    

	
}


function create_pr_issue_for_grn($pr_no, $grn, $grn_no){
        
    global $Refs;
    
//    read_pr($pr_no, $im_cart);
    
//    $im_cart->issuing_location = $grn->Location;
//    $im_cart->reference = $Refs->get_next(ST_PR_ISSUE);
    
//    $po_supplier = get_po_supplier($grn->order_no);
//    
//    foreach ($grn->line_items as $grn_line)
//    {
//        if($grn_line->item_selected){
//            foreach ($im_cart->line_items as &$im_line)
//            {
//                if($grn_line->pr_line_id == $im_line->row_id){
//                    $tran_unit = $grn_line->tran_unit;
//                    $conversion_factor = $grn_line->order_unit_conv_factor;
//                    get_convertion_factor2($grn_line->stock_id, $tran_unit, $conversion_factor);                
//                    $im_line->tran_unit_conv_factor = $conversion_factor;
//                    $im_line->tran_unit = $tran_unit;
//
//                    $lot_details = '';
//    //                $lot_details = get_selected_lot_serial_info('guid', $line_item);   
//                    $im_line->lot_details = $lot_details;    
//
//                    $im_line->quantity = $grn_line->receive_qty;
//                    $im_line->tran_qty = $grn_line->tran_qty;
//                    $im_line->charging_cost = get_tax_free_price_for_item($im_line->stock_id, $grn_line->price, $po_supplier['tax_group_id'], $po_supplier['tax_included']);
//                    $im_line->item_selected = true;
//    //                $line_item->project_site_id = $_POST[$line_item->row_id."_project_site_id"];   
//                }
//            } 
//        }
//    }
    
    $prh = get_pr_edit_info($pr_no);
//    $pri_reference = $Refs->get_next(ST_PR_ISSUE);
    $pri_reference = "GRN#".$grn_no;
    $cppi = can_process_pr_issue_from_grn($prh['pr_complete'],$prh['approval_status'], $pri_reference, $prh['location']);
//    $cppi = can_process_pr_issue($im_cart);
    if($cppi["success"] !== true){
        unset($im_cart);
        return $cppi;
    }
    
    $api_msg = add_pr_issue_from_grn($grn, $prh, $pri_reference);
                
    unset($im_cart);
	
    return $api_msg;
    
}

function check_grn_quantities()
{
    global $Ajax;
    
    $count = 0;
    
    foreach ($_SESSION['PO']->line_items as $line)
	{  
        $prefix = $line->pr_line_id."_".$line->pr_po_line_id."_".$line->row_id;
        
        if(isset($_POST[$prefix.'_check_grn_item']) && $_POST[$prefix.'_check_grn_item'] == true){
//            $_POST[$line->line_no] = max($_POST[$line->line_no], 0);
//            if (!check_num($line->line_no)){
//                $_POST[$line->line_no] = number_format2(0, get_qty_dec($line->stock_id));
//            }

            if (!isset($_POST['DefaultReceivedDate']) || $_POST['DefaultReceivedDate'] == ""){
                $_POST['DefaultReceivedDate'] = new_doc_date();
            }

            $_SESSION['PO']->line_items[$line->line_no]->project_site_id = $_POST[$prefix."_site_id"];
            
            $_SESSION['PO']->line_items[$line->line_no]->tran_qty = input_num($prefix."_tran_qty");
            $_SESSION['PO']->line_items[$line->line_no]->tran_unit = $_POST[$prefix."_tran_unit"];

            $alternate_unit = get_convertion_factor($_POST[$prefix."_tran_unit"], $line->stock_id);
            if($alternate_unit == false){
                $issue_convertion_factor = 1;
            }
            else{
                $issue_convertion_factor = $alternate_unit['convertion_factor'];
            }
            $_SESSION['PO']->line_items[$line->line_no]->convertion_factor = $issue_convertion_factor;

            $_SESSION['PO']->line_items[$line->line_no]->receive_qty = input_num($prefix."_tran_qty")*$issue_convertion_factor;

            if (isset($_POST[$prefix."Desc"]) && strlen($_POST[$prefix."Desc"]) > 0)
            {
                $_SESSION['PO']->line_items[$line->line_no]->item_description = $_POST[$prefix. "Desc"];
            }
            
            if(isset($_POST[$prefix."_check_grn_item"]) && $_SESSION['PO']->line_items[$line->line_no]->receive_qty > 0){
                $_SESSION['PO']->line_items[$line->line_no]->item_selected = true;
                $count++;
            }
            else{
                $_SESSION['PO']->line_items[$line->line_no]->item_selected = false;
            }
            
            if(get_post($prefix.'_site_id') > 0){
                $_SESSION['PO']->line_items[$line->line_no]->project_site_id = get_post($prefix.'_site_id');
            }
            else{
                $_SESSION['PO']->line_items[$line->line_no]->project_site_id = 0;
            }
        }
        else{
            $_SESSION['PO']->line_items[$line->line_no]->item_selected = false;
        }
	}
    
	$Ajax->activate('grn_items');
    
    if($count == 0){
        display_error("No items with quantities selected");
        return false;
    }
    else{
        return true;
    }

}


function close_po()
{
    $po_no = $_SESSION['PO']->order_no;
    $row_state = $_SESSION['PO']->row_state;
    $po = get_po_edit_info($po_no);
    if($po['approval_status'] != AS_APPROVED){
        display_error("Status of this PO does not allow closing.");
        return;
    }
    
//    $n = update_close_po($po_no, $row_state);
//    if($n != 1){
//        display_error("Could not close this PO.");
//        return;
//    }
    
    $closing_status = AS_CLOSED;
    $po_close_msg = direct_update_document_status(ST_PURCHORDER, $po_no, $closing_status, $row_state);     

    if($po_close_msg['success'] !== true ){
        cancel_transaction();
        return array("success" => false, "message" => $po_close_msg['message']);
    }
    else{
        commit_transaction();

        new_doc_date($_POST['DefaultReceivedDate']);
        unset($_SESSION['PO']->line_items);
        unset($_SESSION['PO']);

        meta_forward($_SERVER['PHP_SELF'], "ClosedID=$po_no");
    }
    
    
}
//--------------------------------------------------------------------------------------------------

$pr_no = 0;
if(isset($_GET['PRNumber']) && $_GET['PRNumber'] != 0){
    $_POST['PRNumber'] = $_GET['PRNumber'];
}
if(isset($_POST['PRNumber']) && $_POST['PRNumber'] != 0){
    $pr_no = $_POST['PRNumber'];
}
    
    
if (isset($_GET['PONumber']) && $_GET['PONumber'] > 0 && !isset($_POST['Update']))
{

        
//    $pr_no = 0;
    create_new_po(ST_PURCHORDER, $_GET['PONumber'], $pr_no);    
        
    if($_SESSION['PO']->approval_status != AS_APPROVED){
        display_error("This PO is not approved. Can not receive items against this order");
        return;
    }
        
	$_SESSION['PO']->trans_type = ST_SUPPRECEIVE;
	$_SESSION['PO']->reference = $Refs->get_next(ST_SUPPRECEIVE);
    
	copy_from_cart();
}

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

if (isset($_POST['Update']))
{
    check_grn_quantities();
}
	/* if update quantities button is hit page has been called and ${$line->line_no} would have be
 	set from the post to the quantity to be received in this receival*/
	
function handle_update_item($row_id)
{

}
//--------------------------------------------------------------------------------------------------

if (isset($_POST['ProcessGoodsReceived']))
{
    if(check_grn_quantities()){
        process_receive_po();
    }
}

if (isset($_POST['Close_PO'])){
    close_po();
}


if (isset($_POST['UpdateItem'])){
    $row_id = $_POST['UpdateItem'];
	handle_update_item($row_id);
}
//--------------------------------------------------------------------------------------------------

start_form();

$guid = ST_SUPPRECEIVE;
$_POST['guid'] = $guid;
hidden("guid",$guid);

hidden('PRNumber', $pr_no);

edit_grn_summary($_SESSION['PO'], true);

if($pr_no > 0){
    display_heading(_("Items to Receive and Issue to Purchase Requisition $pr_no"));
}
else{
    display_heading(_("Items to Receive"));
}


if($pr_no == -1){
    $msg = "There has been open Purchase Requitions for this Purchase Order. You have decided to receive goods without Purchase Requistions.<br/>
            <u>Below are the consequences:</u><br/>
            Goods will be received in to the store (stock) and will NOT be issued to the project automatically.<br/>
            You will need to create a manual Purchase Requisition Issue to issue materials to the project and charge the project on Purchase Order prices.";
    
    $msg = "<left>$msg</left>";
    display_warning($msg, false);
}
elseif(!($pr_no > 0)){
    $msg = "You are receiving goods without Purchase Requistions.<br/>
            <u>Below are the consequences:</u><br/>
            Goods will be received in to the store (stock) and will NOT be issued to the project automatically.<br/>
            You will need to create a manual Purchase Requisition Issue to issue materials to the project and charge the project on Purchase Order prices.";
    
    $msg = "<left>$msg</left>";
    display_warning($msg, false);
}





display_po_receive_items($pr_no);

echo '<br>';
//if($pr_no > 0){
//    display_note("<font color='DarkBlue'>".text_bold("PR Issue will be created for the balance quantities only. Please view the PR Issue before issuing any items.")."</font>");
//    br();
//}
submit_center_first('Update', _("Calculate"), '', true);
submit_center_last('ProcessGoodsReceived', _("Process Receive Items"), _("Clear all GL entry fields"), 'default');

br();

if(check_po_has_advance_payments($_SESSION['PO']->order_no)){
    $m = "This purchase order has advance payments. You may request approval before closing this purchase order.";
    display_note("<font color='red'>".text_bold($m)."</font>");
}

br();



submit_center_first('Close_PO', _("Close Purchase Order"), '', true);

end_form(2);

//--------------------------------------------------------------------------------------------------
end_page();
?>

