<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or pTNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$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/purchasing_ui.inc");
include_once($path_to_root . "/fixed_assets/includes/fixed_assets_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/sales/includes/db/charges_db.inc");
include_once($path_to_root . "/purchasing/includes/db/charges_rate_per_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();
//Receive Purchase Order Items
page(_($help_context = " GRN"), false, false, "", $js);

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

if (isset($_GET['AddedID']))
{
	$grn = $_GET['AddedID'];
	$trans_type = ST_SUPPRECEIVE;
	$invoice_no = get_invoice_number($grn);

	display_notification_centered(_("Purchase Order Delivery has been processed"));

	display_note(get_trans_view_str($trans_type, $grn, _("&View this Delivery")));
	br();
	display_note(print_document_link($grn, _("&Print This GRN"), true, $trans_type), 0, 1);

// 	display_note(print_document_link($invoice_no, _("&Print This Invoice"), true, ST_SUPPINVOICE));

    $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['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($kv_batch=0, $kv_exp_date=0,$cost_amt=0)
{
	div_start('grn_items');
    start_table(TABLESTYLE, "colspan=7 width='90%'");
    $th = array(_("Item Code"), _("Description"), _("Ordered"), _("Units"), _("Received"),	_("Outstanding"), _("Gross Weight"), _("Rate Type"), _("Rate"), _("Price"), _("Total")); //, _("Gross Weight"), _("Kat Weight"), _(" Net Weight")
	if($kv_exp_date){
		array_splice( $th, 9, 0, _("Batch No") );
		array_splice( $th, 10, 0, _("Exp Date") );
	}elseif($kv_batch)
		array_splice( $th, 7, 0, _("Batch No") );
	
	array_splice( $th, 8, 0, _("Pack Size") );
		array_splice( $th, 9, 0, _("Pack Unit") );
		array_splice( $th, 10, 0, _("No of Pack") );

        // if($cost_amt){
		// 	array_splice( $th, 11, 0, _("Import cost") );
		// 	array_splice( $th, 12, 0, _("Import Unit cost") );
		// 	array_splice( $th, 13, 0, _("PO price") );
        // }



    table_header($th);

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

    $total = 0;
    $k = 0; //row colour counter
// display_error(count($_SESSION['PO']->line_items));
    $sum_cost=0;
    if (count($_SESSION['PO']->line_items)> 0 )
    {
    	$cost_item_amt=0; //= $cost_amt / count($_SESSION['PO']->line_items);
    // 	if($cost_amt){
    //     	$cost_item_amt = $cost_amt / count($_SESSION['PO']->line_items) ;
    //     	// display_error($cost_item_amt);
    // 	}

       	foreach ($_SESSION['PO']->line_items as $ln_itm)
       	{
       		// display_error($_POST[$ln_itm->stock_id.'pack_size'.$ln_itm->line_no]);
       		//  echo "<pre>";
       		// var_dump($_SESSION['PO']->line_items);

       			$unit__item_cost= 0;
       			if($cost_amt){
       	// 			if(!isset($_POST['imp_item_cost'.$ln_itm->line_no]) || !isset($_POST['Update']))
       	// 				$_POST['imp_item_cost'.$ln_itm->line_no]=$cost_item_amt;


					$unit__item_cost = input_num('imp_item_cost'.$ln_itm->line_no) /$ln_itm->receive_qty ;
       				// display_error(input_num('imp_item_cost'.$ln_itm->line_no) ." == ".$ln_itm->line_no);
					$_POST['imp_cost'.$ln_itm->line_no]=$unit__item_cost;
				// 	display_error($unit__item_cost." =  ".$ln_itm->quantity."  / ".input_num('imp_item_cost'.$ln_itm->line_no) );
					// if(!input_num('imp_cost'.$ln_itm->line_no))
					$ln_itm->price= $ln_itm->old_price+$unit__item_cost;

       	           
             	   // $ln_itm->price+= input_num('imp_cost'.$ln_itm->line_no);
             	    $sum_cost+=input_num('imp_cost'.$ln_itm->line_no)*$ln_itm->receive_qty;
             	    // display_error(round2(input_num('imp_cost'.$ln_itm->line_no)*$ln_itm->quantity,4)." in  ".input_num('imp_cost'.$ln_itm->line_no)."  * ". $ln_itm->quantity);
             	
       			}


			alt_table_row_color($k);
            
    		$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;
    		}
            // if($cost_amt)
            // $line_total = ($ln_itm->receive_qty * ($ln_itm->price + input_num('imp_cost'.$ln_itm->line_no)) );	
            // else	
    		$line_total = ($ln_itm->receive_qty * $ln_itm->price);
    		$total += $line_total;


			label_cell($ln_itm->stock_id);
			if ($qty_outstanding > 0)
				text_cells(null, $ln_itm->stock_id . "Desc", $ln_itm->item_description, 30, 50);
			else
				label_cell($ln_itm->item_description);
			$dec = get_qty_dec($ln_itm->stock_id);
			qty_cell($ln_itm->quantity, false, $dec);
			// label_cell($ln_itm->units);
  			label_cell(get_unit_descr($ln_itm->unit_id));
			qty_cell($ln_itm->qty_received, false, $dec);
			qty_cell($qty_outstanding, false, $dec);
			// qty_cell($ln_itm->qty_inward, false, $dec);
			// qty_cells(null,  'weight_gross'.$ln_itm->line_no, number_format2($ln_itm->receive_qty, $dec), "align=right", null, $dec);
			// qty_cells(null, 'kat_weight'.$ln_itm->line_no, number_format2($_POST['kat_weight'.$ln_itm->line_no], $dec), "align=right", null, $dec, true);
			// $_POST[$ln_itm->line_no] = input_num('weight_gross'.$ln_itm->line_no)-input_num('kat_weight'.$ln_itm->line_no);
			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");
			$_stock_id = get_item($ln_itm->stock_id);
			$fixed_asset = is_fixed_asset($_stock_id['mb_flag']);
			if(!$_POST[$ln_itm->stock_id .'batch_no'])
			$_POST[$ln_itm->stock_id .'batch_no']="LOT#";//$_POST['ref'];
			if($kv_exp_date){
				if($fixed_asset != 1)
				text_cells(null,$ln_itm->stock_id .'batch_no', null, 20, 20);
				date_cells(null, $ln_itm->stock_id .'exp_date', '', null, 0, 0, 0);
			} elseif($kv_batch){
				if($fixed_asset != 1)
				  text_cells(null,$ln_itm->stock_id .'batch_no', null, 20, 20);
				else
				  label_cell(null, '');
				hidden($ln_itm->stock_id .'exp_date', '');
			} else{
				hidden($ln_itm->stock_id .'batch_no', 0);
				hidden($ln_itm->stock_id .'exp_date', '');
			}
    		// $qty_total = $_POST[$ln_itm->line_no];
    		$qty_total = input_num($ln_itm->line_no);
    		$price_total += $ln_itm->price;

				// qty_cells(null, $ln_itm->stock_id.'pack_size'.$ln_itm->line_no, 0, "align=right ", null, $dec);
    if(input_changed($ln_itm->stock_id.'pack_size'.$ln_itm->line_no))
    $_POST[$ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no]=(input_num($ln_itm->line_no))/input_num($ln_itm->stock_id.'pack_size'.$ln_itm->line_no);
    if(input_changed($ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no))
    $_POST[$ln_itm->stock_id.'pack_size'.$ln_itm->line_no]=round((input_num($ln_itm->line_no))/input_num($ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no),2) ;
    
            amount_cells(null, $ln_itm->stock_id.'pack_size'.$ln_itm->line_no, $_POST[$ln_itm->stock_id.'pack_size'.$ln_itm->line_no], null, null, $dec, true);
			stock_packing_unit_list_cells(null, $ln_itm->stock_id.'pack_unit'.$ln_itm->line_no, $_POST[$ln_itm->stock_id.'pack_unit'.$ln_itm->line_no]);

            // display_error($_POST[$ln_itm->stock_id.'pack_size'.$ln_itm->line_no]);
    

			qty_cells(null, $ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no,$_POST[ $ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no] , "align=right ", null, $dec,'readonly');
			global $Ajax;
		   $Ajax->activate($ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no);

           //  if($cost_amt){

           //   amount_cells(null, 'imp_item_cost'.$ln_itm->line_no, $_POST['imp_item_cost'.$ln_itm->line_no], null, null, $dec, true);            	
		   //  amount_cells(null, 'imp_cost'.$ln_itm->line_no, $_POST['imp_cost'.$ln_itm->line_no], null, null, $dec, true,'readonly');
		   //  	amount_decimal_cell($ln_itm->old_price);
           //  }
			//date_cells(null, $ln_itm->stock_id .'exp_date', '', null, 0, 0, 0);
			//month_year_cells(null, 'exp_date', null, null, 0, 0, 0);

       		// hidden($ln_itm->stock_id.'pack_size'.$ln_itm->line_no, 1);
			// stock_packing_unit_list_cells(null, $ln_itm->stock_id.'pack_unit'.$line->line_no, $_POST[$ln_itm->stock_id.'pack_unit'.$line->line_no]);
			// $_POST[$ln_itm->stock_id.'pack_unit'.$line->line_no] = 'Pcs';
			// hidden($ln_itm->stock_id.'pack_unit'.$line->line_no, 'Pcs');
            // display_error($_POST[$ln_itm->stock_id.'pack_size'.$ln_itm->line_no]);
			// $_POST[$ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no]=($ln_itm->receive_qty)/input_num($ln_itm->stock_id.'pack_size'.$ln_itm->line_no);
			// hidden($ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no, $_POST[$ln_itm->stock_id.'no_of_pack'.$ln_itm->line_no]);
			
              hidden('price'.$ln_itm->line_no,$ln_itm->price);
          	amount_decimal_cell($ln_itm->rate_type);
			amount_decimal_cell($ln_itm->rate);
			if(!$_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST'))
			{
			label_cell("-");
			label_cell("-");
			}
			else{

			amount_decimal_cell($ln_itm->price);
		    // display_error($ln_itm->price."  == ".$cost_amt." == ". $line_total);

			amount_cell($line_total);
			}

			end_row();
       	}

        $is_not_equl_cost=0;
       	if($cost_amt){
           global 	$Ajax;
           	$Ajax->activate('_page_body');
       			// display_error($cost_amt." ==== ".$sum_cost." == ".floatcmp($cost_amt,$sum_cost));
       				label_cells(_("Cost Sum"), $sum_cost, "colspan=11 align=right class='tableheader2 headingtext ' style='color: darkmagenta;' ","align=right colspan=0");
       				label_cell("","colspan=3");
       		if(floatcmp($cost_amt,$sum_cost)<>0)
       		{
       			$is_not_equl_cost=1;

       			display_error("totol import cost can not equal divide");
       		}
       	}

    }
    
	if($_SESSION["wa_current_user"]->can_access('SA_WORKORDERCOST')){
			
	// $colspan = count($th)-2;

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



	$taxes = $_SESSION['PO']->get_taxes(input_num('freight_cost'), true);
	  // label_cell('-',"colspan='6'");
	  end_row();
	// qty_cells(_("Kat %"), 'kat_percentage', number_format2($_POST['kat_percentage'], $dec), "colspan='6' align=right", null, $dec, true);
	// label_cell('-',"colspan='6'");
 end_row();
	// $kat_perc = $qty_total/100;
	// $_POST['kat_weight'] = input_num('kat_percentage')*$kat_perc;
	// display_error(input_num('kat_percentage')." * ".$kat_perc);
	qty_cells(_("Kat Weight"), 'kat_weight', number_format2($_POST['kat_weight'], $dec), "colspan='6' align=right", null, $dec, true);
	label_cell(submit_center_last('Update', _("Update"), '', true)) ;
	label_cell('-',"colspan='6'");
	 end_row();
	if(input_num('kat_weight'))
	$net_weight = $qty_total-input_num('kat_weight');
	label_cells(_("Net Weight"), price_format($net_weight), "colspan='6' align=right","align=right");
	$kat_amt = input_num('kat_weight')*$price_total;
	$_POST['kat_amt'] = $kat_amt;
	label_cell('-',"colspan='6'");
	 end_row();
	label_cells(_("Kat Amount"), price_format($kat_amt), "colspan='6' align=right","align=right");
	hidden('kat_amt', $_POST['kat_amt']);
	label_cell('-',"colspan='6'");
	 end_row();
	 $total-=input_num('kat_amt');
	 	label_cells(_("Sub-total"), price_format($total), "colspan='11' align=right","align=right");
	 		  end_row();
	$result = get_charges(check_value('show_inactive'));
	$i = 1;
	while ($myrow = db_fetch($result)){
	// display_error($myrow['kat_percentage']);
		// print_r($myrow['is_negative']);
	    start_row();
	    if($myrow['is_percentage'])
	    	$colspan = 9;
		else
		    $colspan = 11;

     		$lbl=($myrow['is_negative'])? " (-)" : " (+)";
	    if($myrow['is_percentage']){
     		label_cell(null,"colspan=$colspan");
	    	text_cells_ex(_($myrow['name']." ".$lbl), 'percentage'.$i, 2, 255, null, null, "colspan='1' align=left", null, true);
	    	// $charges_ = get_charge_is_percentage($myrow['is_percentage'], $myrow['is_weight']);
			$charges_rate_per = get_charge_rate_per_charges_id($myrow['id'], input_num('percentage'.$i));
			if($myrow['is_percentage'] == 1 && $myrow['is_weight'] == 0){
				$_POST['charges_amount'.$i] = $total/100*input_num('percentage'.$i);
			}
			elseif($myrow['is_percentage'] == 1 && $myrow['is_weight'] == 1){
				$_POST['charges_amount'.$i] =  ($qty_total/100)*$charges_rate_per['amount'];
			}
			text_cells(null, "charges_amount".$i, price_format(input_num('charges_amount'.$i)), 15, "", false, "colspan=$colspan align=right", "", "", false);	 
	    }else{
	    	text_cells($myrow['name']." ".$lbl, "charges_amount".$i, price_format(input_num('charges_amount'.$i)), 15, "", false, "colspan=$colspan align=right", "", "", false);
	    }
	    // label_cell(null, "colspan=2", null);
         if($myrow['is_negative'])
	    $total-=input_num('charges_amount'.$i);
	    else
	     $total+=input_num('charges_amount'.$i);
	    end_row();
	    $i++;
	}

	$tax_total = display_edit_tax_items($taxes, $colspan, $_SESSION['PO']->tax_included);
	$display_total = price_format(($total + input_num('freight_cost') + $tax_total));

	start_row();
	label_cells(_("Amount Total"), $display_total, "colspan='11' align='right'","align='right'");
	end_row();
		
	}
    end_table();

    // display_heading(_('Truck Details'));
	// start_table(TABLESTYLE2, "width='100%'");
	// if(!$_POST['truck_of_no'])
	// 	$_POST['truck_of_no'] = 1;
	// start_row();
	// text_cells_ex(_("Number Of Truck"), 'truck_of_no', 15, 255, null, null, "class='tableheader2'",
	// null, true);
	// end_row();
	// $j = $_POST['truck_of_no'];
	// for ($i=0; $i < $j; $i++) { 
	// 	start_row();
	// 	text_cells_ex(_("Truck #"), 'truck_number'.$i, 15, 255, null, null, "class='tableheader2'");
	// 	text_cells_ex(_("Builty #"), 'builty_number'.$i, 15, 255, null, null, "class='tableheader2'");
	// 	text_cells_ex(_("Gross Weight"), 'gross_weight'.$i, 15, 255, null, null, "class='tableheader2'");
	// 	text_cells_ex(_("No Of Bags"), 'no_of_bags'.$i, 15, 255, null, null, "class='tableheader2'");
	// 	truck_details_cells(_("Status"), "is_status".$i, null, false, true, "class='tableheader2'");	
	// 	end_row();
	// }
	// end_table();

	// br();
	// display_heading(_('Brokery Service'));
	// start_table(TABLESTYLE2, "width='50%'");

	// supplier_list_row(_("Supplier:"), 'supplier_id', null, false, false, false, true);
	// if($_POST['brokery_percent'])
	// 	$_POST['brokery_price'] = $total/100*input_num('brokery_percent');
	// amount_row(_("Brokery (Rs)"), 'brokery_price');
	// amount_row(_("Brokery %"), 'brokery_percent',null,null,null,null,true);
	// end_table();

	div_end();
	return $is_not_equl_cost;
}

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

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 */
	// 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))
	{
		$ln_item = $_SESSION['PO']->line_items[$line_no];
		// only compare against items that are outstanding
		$qty_outstanding = $ln_item->quantity - $ln_item->qty_received;
		if ($qty_outstanding > 0)
		{
    		if ($ln_item->qty_inv != $myrow["qty_invoiced"]	||
    			$ln_item->stock_id != $myrow["item_code"] ||
    			$ln_item->quantity != $myrow["quantity_ordered"] ||
    			$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 */

	return false;
}

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

function can_process()
{
	global $SysPrefs;
	
	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($_POST['dc_no']) == 0) 
	{
		$input_error = 1;
		display_error(_("The DC No. must be entered."));
		set_focus('dc_no');
			return false;
	}

		if (strlen($_POST['vehicle_no']) == 0) 
	{
		$input_error = 1;
		display_error(_("The vehicle No must be entered"));
		set_focus('vehicle_no');
      	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 out of fiscal year or is closed for further data entry."));
		set_focus('DefaultReceivedDate');
		return false;
	}

	if (!check_reference($_POST['ref'], ST_SUPPRECEIVE))
	{
		set_focus('ref');
		return false;
	}

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

    // 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->receive_qty+$order_line->qty_received >
	  		$order_line->quantity * (1+ ($SysPrefs->over_receive_allowance() / 100)))
	  	{
			$delivery_qty_too_large = 1;
			break;
	  	}
	}

    if ($something_received == 0)
    { 	/*Then dont bother proceeding cos nothing to do ! */
        display_error(_("There is nothing to process. Please enter valid quantities greater than zero."));
    	return false;
    }
    elseif ($delivery_qty_too_large == 1)
    {
    	display_error(_("Entered quantities cannot be greater than the quantity entered on the purchase order including the allowed over-receive percentage") . " (" . $SysPrefs->over_receive_allowance() ."%)."
    		. "<br>" .
    	 	_("Modify the ordered items on the purchase order if you wish to increase the quantities."));
    	return false;
    }

	return true;
}

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

function process_receive_po()
{
	global $path_to_root, $Ajax, $Refs;


	// if ($_POST['is_status'] > 0) {
			
			// update_quantity_received($_SESSION['PO']->order_no, input_num('0'));

	// }




	if($_POST['is_status'] == 1){


		$sql = "INSERT INTO ".TB_PREF."truck_details (po_no, truck_of_no, builty_number, no_of_bags, station, is_status, dc_no, analytics_by) VALUES (".db_escape($_SESSION['PO']->order_no) . ",
			".db_escape($_POST['vehicle_no']) . ", ".db_escape($_POST['builty_no']) . ",".db_escape($_POST['no_bags']) . ", 
			".db_escape($_POST['station']) . ", ".db_escape($_POST['is_status']) . ", ".db_escape($_POST['dc_no']) . ",
			".db_escape($_POST['analytics_by']) . ")";
			db_query($sql,"The sales group could not be added");

		$po_row = get_po($_SESSION['PO']->order_no);
		foreach ($_SESSION['PO']->line_items as $line_no => $order_line) {
			if ($po_row['is_replacement']) {
			    $sql = "UPDATE " . TB_PREF . "purch_order_details 
				SET quantity_received = quantity_received + " . db_escape($order_line->receive_qty) . " 
				WHERE po_detail_item = " . db_escape($order_line->po_detail_rec);
				// display_error($sql." =============".$_POST['is_status'] );
				// exit();
				db_query($sql, "The sales group could not be updated");
			}
		}
		meta_forward($path_to_root."/purchasing/inquiry/po_search.php?");
		exit();
	}

// exit();

	if (!can_process())
		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->dc_no = ($_POST['dc_no']) ? $_POST['dc_no'] : 0;
	$grn->vehicle_no = $_POST['vehicle_no'];
	$grn->ex_rate = input_num('_ex_rate', null);
	$grn->add_code_id = $_POST['add_code_id'];
	$grn->add_imp_item_cost = input_num('add_imp_item_cost');
	$grn->station = $_POST['station'];
	$grn->broken = $_POST['broken'];
	$grn->analytics_by = $_POST['analytics_by'];
	$grn->no_bags = $_POST['no_bags'];
	$grn->builty_no = $_POST['builty_no'];
	$grn->file_system = $_POST['file_system'];
	$grn->kat_percentage = $_POST['kat_percentage'] ? $_POST['kat_percentage'] : 0;
	$grn->broker_id = $_SESSION['PO']->broker_id;
	$grn->brokery_amt = $_SESSION['PO']->brokery_amt;
	// display_error($_SESSION['PO']->dimension2);
	// exit();
	$grn_no = add_grn($grn);

	// GRN Charges Amount 
	$result2 = get_charges(check_value('show_inactive'));
	$i = 1;
	while ($myrow2 = db_fetch($result2)){
		if($myrow2['is_negative']==1)
			$_POST['charges_amount'.$i] = input_num('charges_amount'.$i)*-1;
		if(input_num('charges_amount'.$i) != 0){
			$sql = "INSERT INTO ".TB_PREF."charges_trans (trans_no, type, charge_id, gl_code, name, charges_amount) VALUES (".db_escape($grn_no) . ", ".db_escape(ST_SUPPRECEIVE) . ", ".db_escape($myrow2['id']) . ", ".db_escape($myrow2['gl_code']) . ", 
				".db_escape($myrow2['name']) . ", ".db_escape(input_num('charges_amount'.$i)) . ")";
			// display_error($sql);
   			db_query($sql,"The charges could not be added");
		}
			$i++;
	}
	
	  if(input_num('kat_amt')){

  	$sql = "INSERT INTO ".TB_PREF."charges_trans (trans_no, type, charge_id, gl_code, name, charges_amount) VALUES (".db_escape($grn_no) . ", ".db_escape(ST_SUPPRECEIVE) . ", ".db_escape(0) . ", ".db_escape(get_company_pref('kat_weight_acc')) . ", 
				'Kat Amount' , ".db_escape(-input_num('kat_amt')) . ")";
			// display_error($sql);
   			db_query($sql,"The charges could not be added");


  }



    $sql = "INSERT INTO ".TB_PREF."truck_details (grn_no,po_no, truck_of_no, builty_number, no_of_bags, station, is_status, dc_no, analytics_by, x_weight, mill_weigh) VALUES (".db_escape($grn_no) . ",".db_escape($_SESSION['PO']->order_no) . ",
			".db_escape($_POST['vehicle_no']) . ", ".db_escape($_POST['builty_no']) . ",".db_escape($_POST['no_bags']) . ", 
			".db_escape($_POST['station']) . ", ".db_escape($_POST['is_status']) . ", ".db_escape($_POST['dc_no']) . ",
			".db_escape($_POST['analytics_by']) . ",
			".db_escape(input_num('x_weight') ) . ",
			".db_escape(input_num('mill_weigh') ) . ")";
			db_query($sql,"The sales group could not be added");


	// if ($_POST['vehicle_no'] > 0) {
	// 		$sql = "INSERT INTO ".TB_PREF."truck_details (po_no, truck_of_no, builty_number, gross_weight, no_of_bags, is_status) VALUES (".db_escape($_SESSION['PO']->order_no) . ",
	// 		".db_escape($_POST['vehicle_no']) . ", ".db_escape($_POST['builty_no']) . ",".db_escape($_POST['gross_weight']) . ", 
	// 		".db_escape($_POST['no_bags']) . ", ".db_escape($_POST['is_status']) . ")";
	// 		db_query($sql,"The sales group could not be added");
	// }

    update_for_partial_qc($grn->order_no);

// 	if ($_SESSION['PO']->order_no && $_POST['ProcessGoodsReceived'] != '') {
// 	// ------------------------------------------------------------------------------
// 	// PO Auto Invoiced
// 	// ------------------------------------------------------------------------------
// 	$supp_inv_ref =	$Refs->get_next(ST_SUPPINVOICE, null, 
//   		array('supplier' => $_SESSION['PO']->supplier_id, 'date' => $_SESSION['PO']->orig_order_date));

// 	$inv = new supp_trans(ST_SUPPINVOICE);
// 	$inv->Comments = 'Auto Invoiced';
// 	$inv->supplier_id = $_SESSION['PO']->supplier_id;
// 	$inv->tran_date = $_SESSION['PO']->orig_order_date;
// 	$inv->due_date = $_SESSION['PO']->orig_order_date;
// 	$inv->dimension = 0;
// 	$inv->dimension2 = 0;
// 	$inv->reference = $supp_inv_ref;
// 	$inv->supp_reference = $_SESSION['PO']->supp_ref;
// 	$inv->tax_included = $_SESSION['PO']->tax_included;
// 	$supp = get_supplier($_SESSION['PO']->supplier_id);
// 	$inv->tax_group_id = $supp['tax_group_id'];
// 	$inv->ov_amount = $inv->ov_gst = $inv->ov_discount = 0;
// 	$inv->terms = $_SESSION['PO']->payment_terms;
// 	$inv->file_system = $_SESSION['PO']->file_system;

// 	$_SESSION['supp_trans'] = $inv;
// 	$result2 = get_charges(check_value('show_inactive'));
// 	if($_POST['kat_amt'] > 0){
// 		$data = db_fetch_row($result1);
// 		$kat_acc_name = $data[1];
// 		// display_error($kat_acc_name);
// 		$_SESSION['supp_trans']->add_gl_codes_to_trans(get_company_pref('kat_weight_acc'), 
// 			$kat_acc_name, 0, 0, -input_num('kat_amt'), 'Kat Amount');
// 	}
	
// 	$i = 1;
// 	while ($myrow2 = db_fetch($result2)){
// 		// GL PO Charges Amount 
// 		if(input_num('charges_amount'.$i) != 0){
// 			$result1 = get_gl_account_info($myrow2['gl_code']);
// 			$myrow1 = db_fetch_row($result1);
// 			$gl_act_name1 = $myrow1[1];
// 			$_SESSION['supp_trans']->add_gl_codes_to_trans($myrow2['gl_code'], $gl_act_name1, 0, 0, input_num('charges_amount'.$i), $myrow2['name']);
// 		}
// 			$i++;
// 	}

	

// 	foreach ($_SESSION['PO']->line_items as $line_item_inv)
// 	{
// 		global $Ajax;
// 		// print_r($line_item_inv);
//             if($_SESSION['PO']->line_items[$line_item_inv->line_no]->receive_qty > 0 )
// 		$_SESSION['supp_trans']->add_grn_to_trans($line_item_inv->grn_item_id, $line_item_inv->po_detail_rec,
// 		$line_item_inv->stock_id, $line_item_inv->item_description, 
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->receive_qty,
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->receive_qty, 
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->receive_qty, 
// 		$line_item_inv->price, $line_item_inv->price, 
// 		'complete', $line_item_inv->standard_cost, $line_item_inv->batch_no, TOday(), 
// 		$_SESSION['PO']->tax_group_id, $_SESSION['PO']->unit_id, 
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->no_of_qty,
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->rate_type,
// 		$_SESSION['PO']->line_items[$line_item_inv->line_no]->rate);
// 		// display_error($line_item_inv->quantity. '=='.  $line_item_inv->qty_received);

// 		$Ajax->activate('_page_body');
// 	}
// 	$po_invoice_no = add_supp_invoice($_SESSION['supp_trans']);

//     $_SESSION['supp_trans']->clear_items();
//     unset($_SESSION['supp_trans']);
// 	}



	if(input_num('brokery_amt') > 0)
	{
			 global $path_to_root, $Refs;
	
			 $broker_id = $_SESSION['PO']->broker_id;
			 $brokery_amt = input_num('brokery_amt');
			 $file_system = $_SESSION['PO']->file_system;
             $lot_no=$_SESSION['PO']->line_items[0]->batch_no;
			if (isset($_SESSION['PO']))
			unset ($_SESSION['PO']->line_items, $_SESSION['PO']);
		// display_error($_SESSION['PO']->brokery_amt .'=='. 'sdfsdf223');

			$cart_po = new purch_order;
			// $_POST['DefaultReceivedDate'] = new_doc_date();
			// if (!is_date_in_fiscalyear($_POST['DefaultReceivedDate']))
			// $_POST['DefaultReceivedDate'] = end_fiscalyear();
			$cart_po->due_date = $cart_po->orig_order_date = $_POST['DefaultReceivedDate'];

			$cart_po->trans_type = ST_SUPPINVOICE;//$trans_type;
			$cart_po->order_no =  0; //$trans_no;
			$cart_po->supplier_id=$broker_id;
			$cart_po->orig_order_date=$_POST['DefaultReceivedDate'];
			$cart_po->Location=$_POST['Location'];
   			$cart_po->delivery_address = $_POST['Location'];
			$cart_po->file_system = $file_system;
			$cart_po->Comments = "Auto Brokery Invoiced - GRN # ".$grn_no."  -  ".$lot_no." - Truck # : ".$_POST['vehicle_no'];
			$cart_po->broker_id = $broker_id;
			$cart_po->brokery_amt = $brokery_amt;
			$cart_po->is_replacement=1;

			// $cart_po->brokery_percent=$_POST['brokery_percent'];
			// exit();
			// display_error($_POST['brokery_percent']);
			// $cart_po->sales_invoice_no=$invoice_no;
			
			/*read in all the selected order into the Items cart_po  */
			// if ($trans_no) {
			// read_po($trans_no, $cart_po);
			// $cart_po->order_no = $trans_no;
			// } else
		// display_error($_SESSION['PO']->brokery_amt .'=='. 'sdfsdf');

			$cart_po->reference = $Refs->get_next($cart_po->trans_type, null,
			array('supplier_id' => $broker_id, 'date' => get_post('DefaultReceivedDate')));
	    	get_supplier_details_to_order($cart_po, $broker_id); 
	    	


	    	// print_r($_SESSION['PO']->line_items);

			$_SESSION['PO'] = &$cart_po;
	    	$_SESSION['PO']->add_to_order (count($_SESSION['PO']->line_items), 'EXP-002', 1, 
					'',  $brokery_amt, '', Today(), 0, 0, $cart_po->reference, '', 0,0,0,0,null,0, 
					'KG');
	    	$trans_no_po = add_direct_supp_trans($_SESSION['PO']);
	    	// Update Inv No In Service Order Inv
	   // 	update_invoice_no($po_invoice_no, $trans_no_po);

	    	// if ($trans_no_po) 
			unset($_SESSION['PO']);

		}	


	if (count($messages)) { 
		$Ajax->activate('_page_body');
		display_footer_exit();
	}

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

	meta_forward($_SERVER['PHP_SELF'], "AddedID=$grn_no");
}

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

if (isset($_GET['PONumber']) && $_GET['PONumber'] > 0 && !isset($_POST['Update']))
{
	create_new_po(ST_PURCHORDER, $_GET['PONumber']);
	$_SESSION['PO']->trans_type = ST_SUPPRECEIVE;
	$_SESSION['PO']->reference = $Refs->get_next(ST_SUPPRECEIVE, 
		array('date' => Today(), 'supplier' => $_SESSION['PO']->supplier_id));
	copy_from_cart();
}

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

if (isset($_POST['Update']) || isset($_POST['ProcessGoodsReceived']))
{

	/* 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*/
	foreach ($_SESSION['PO']->line_items as $line)
	{
	 if( ($line->quantity - $line->qty_received)>0) {
		$_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]->receive_qty = input_num($line->line_no);
		// if(isset($_POST['ProcessGoodsReceived']))
		// $_SESSION['PO']->line_items[$line->line_no]->price = input_num('price'.$line->line_no)+input_num('imp_cost'.$line->line_no);

		if (isset($_POST[$line->stock_id . "Desc"]) && strlen($_POST[$line->stock_id . "Desc"]) > 0)
		{
			$_SESSION['PO']->line_items[$line->line_no]->item_description = $_POST[$line->stock_id . "Desc"];
			$_stock_id = get_item($line->stock_id);
			$fixed_asset = is_fixed_asset($_stock_id['mb_flag']);
			if ($fixed_asset != 1) {
			if(!$_POST[$line->stock_id . "batch_no"])
			{
				  display_error(_("There is nothing to process. Please enter All Items Batch No."));
				  unset($_POST['ProcessGoodsReceived']);
			}
			# 12/16/2023 abdus sami : fn check_batch_use for check dublicate batch unique price. 
			$check_val = check_batch_use($line->stock_id,trim($_POST[$line->stock_id . "batch_no"]));  
			// display_error($check_val);
			if($check_val>0)
			{
				display_error(_("There is nothing to process. batch No ".trim($_POST[$line->stock_id . "batch_no"])." is alredy exist for item ".$line->stock_id." ."));
				  unset($_POST['ProcessGoodsReceived']);

			}	
		 }	

			$_SESSION['PO']->line_items[$line->line_no]->batch_no = trim($_POST[$line->stock_id . "batch_no"]);
			$_SESSION['PO']->line_items[$line->line_no]->exp_date = $_POST[$line->stock_id . "exp_date"];

			$_SESSION['PO']->line_items[$line->line_no]->pack_size = $_POST[$line->stock_id . "pack_size".$line->line_no];
			$_SESSION['PO']->line_items[$line->line_no]->pack_unit = $_POST[$line->stock_id . "pack_unit".$line->line_no];
			$_SESSION['PO']->line_items[$line->line_no]->no_of_pack = $_POST[$line->stock_id . "no_of_pack".$line->line_no];
			// display_error($_SESSION['PO']->line_items[$line->line_no]->pack_unit);
		}
	 }
	}
// 	$Ajax->activate('grn_items');
$Ajax->activate('_page_body');
}

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

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

//--------------------------------------------------------------------------------------------------
$kv_batch = get_company_pref('kv_batch');
$kv_exp_date = get_company_pref('kv_exp_date');
start_form();

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


$invoice_result = get_bank_trans(ST_BANKPAYMENT,null, null, null,$_SESSION['PO']->order_no);
$k = 0;

$cost_mat=0;

if (db_num_rows($invoice_result) > 0)
{

    echo "</td><td valign=top>"; // outer table



		display_heading2(_("additional Import cost"));
		start_table(TABLESTYLE);
		$th = array(_("code"),_("GL Account"),_("Additional Cost Amount"));
		table_header($th);
		echo gl_all_accounts_list('add_code_id', null, true, true);
		amount_cells(null, 'add_imp_item_cost', $_POST['add_imp_item_cost'], null, null, $dec, true);  
		end_table();
     br(2);

    display_heading2(_("Bank Payment For PO"));
    start_table(TABLESTYLE);
    $th = array(_("GL View"),_("Ref"), _("Date"), _("Total"));
    table_header($th);
       // $tot_sum=0;
    while ($myrow = db_fetch($invoice_result))
    {
// print_r($myrow);
        alt_table_row_color($k);

        label_cell(get_gl_view_str($myrow["type"],$myrow["trans_no"]));
           label_cell($myrow["ref"]);
        label_cell(sql2date($myrow["trans_date"]));
        amount_cell(abs($myrow["amount"]));
        $cost_amt += abs($myrow["amount"]);
        end_row();
    }

       $cost_amt=$cost_amt+input_num('add_imp_item_cost');
       label_cells("Total ",price_format($cost_amt)," colspan=3 class='tableheader2 headingtext' ","align='right'");

         if (!is_company_currency($po->curr_code)){
         	global $Ajax;
         	 end_row();
         	// $rate = get_date_exchange_rate($_SESSION['PO']->curr_code,  get_post('DefaultReceivedDate')); // try local
         		$rate = get_exchange_rate_from_home_currency($_SESSION['PO']->curr_code,  get_post('DefaultReceivedDate'));
           if($_POST['_ex_rate'])         	
         	$cost_amt=$cost_amt/$_POST['_ex_rate'];
            else
            $cost_amt=$cost_amt/$rate;	

         	 label_cells("Total in ".$_SESSION['PO']->curr_code ,price_format($cost_amt)," colspan=3 class='tableheader2 headingtext ' style='color: darkmagenta;'  ","align='right'");

         	 // display_error($cost_amt);

         	// display_error($_POST['_ex_rate']."  rr".$rate);
         }

    end_table();
}

display_heading(_("Items to Receive"));
$is_show=display_po_receive_items($kv_batch, $kv_exp_date,abs($cost_amt) );
global $Ajax;
         		$Ajax->activate('_page_body');
echo '<br>';
submit_center_first('Update', _("Update"), '', true);
// display_error($is_show);
if(!$is_show && isset($_POST['Update']))
submit_center_last('ProcessGoodsReceived', _("Process Receive Items"), _("Clear all GL entry fields"), 'default');

end_form();

//--------------------------------------------------------------------------------------------------
end_page();
