<?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 FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_SALESTRANSVIEW';
$path_to_root = "../..";
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/sales/includes/sales_ui.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/purchasing/includes/db/file_system_db.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, 600);
page(_($help_context = "View Sales Dispatch"), true, false, "", $js);


if (isset($_GET["trans_no"]))
{
	$trans_id = $_GET["trans_no"];
}
elseif (isset($_POST["trans_no"]))
{
	$trans_id = $_POST["trans_no"];
}

// 3 different queries to get the information - what a JOKE !!!!

$myrow = get_customer_trans($trans_id, ST_CUSTDELIVERY);

$branch = get_branch($myrow["branch_code"]);

$sales_order = get_sales_order_header($myrow["order_"], ST_SALESORDER);

display_heading(sprintf(_("DISPATCH NOTE #%d"),$trans_id));

echo "<br>";
start_table(TABLESTYLE2, "width='95%'");
echo "<tr valign=top><td>"; // outer table

/*Now the customer charged to details in a sub table*/
start_table(TABLESTYLE, "width='100%'");
$th = array(_("Charge To"));
table_header($th);

label_row(null, $myrow["DebtorName"] . "<br>" . nl2br($myrow["address"]), "nowrap");

end_table();

/*end of the small table showing charge to account details */

echo "</td><td>"; // outer table

/*end of the main table showing the company name and charge to details */

start_table(TABLESTYLE, "width='100%'");
$th = array(_("Charge Branch"));
table_header($th);

label_row(null, $branch["br_name"] . "<br>" . nl2br($branch["br_address"]), "nowrap");
end_table();

echo "</td><td>"; // outer table

start_table(TABLESTYLE, "width='100%'");
$th = array(_("Delivered To"));
table_header($th);

label_row(null, $sales_order["deliver_to"] . "<br>" . nl2br($sales_order["delivery_address"]),
	"nowrap");
end_table();

echo "</td><td>"; // outer table

start_table(TABLESTYLE, "width='100%'");
start_row();
label_cells(_("Reference"), $myrow["reference"], "class='tableheader2'");
label_cells(_("Currency"), $sales_order["curr_code"], "class='tableheader2'");
label_cells(_("Our Order No"),
	get_customer_trans_view_str(ST_SALESORDER,$sales_order["order_no"]), "class='tableheader2'");
end_row();
start_row();
label_cells(_("Customer Order Ref."), $sales_order["customer_ref"], "class='tableheader2'");
label_cells(_("Shipping Company"), $myrow["shipper_name"], "class='tableheader2'");
label_cells(_("Sales Type"), $myrow["sales_type"], "class='tableheader2'");
end_row();
start_row();
label_cells(_("Dispatch Date"), sql2date($myrow["tran_date"]), "class='tableheader2'", "nowrap");

label_cells(_("Due Date"), sql2date($myrow["due_date"]), "class='tableheader2'", "nowrap");
if($myrow["sales_person"])
label_cells(_("Sales Person"), get_salesman_name($myrow["sales_person"]), "class='tableheader2'", "nowrap");
end_row();
start_row();
if($myrow["vehicle_no"])
label_cells(_("Truck No."), $myrow["vehicle_no"], "class='tableheader2'", "nowrap");
if($myrow["file_system"])
label_cells(_("File System"), get_file_system_name($myrow["file_system"]), "class='tableheader2'", "nowrap");
if($myrow["company_id"])
label_cells(_("Company Name"), get_latter_hand_name($myrow["company_id"]), "class='tableheader2'", "nowrap");
if($myrow["is_broker"]){
label_cells(_("Broker"), get_supplier_name($myrow["supplier_id"]), "class='tableheader2'", "nowrap");
end_row();
start_row();
label_cells(_("Broker Amount"), $myrow["brokery_amt"], "class='tableheader2'", "nowrap");
end_row();
}
start_row();
if($myrow["mode"])
label_cells(_("Mode"), $myrow["mode"], "class='tableheader2'", "nowrap");
if($myrow["bags"])
label_cells(_("Bags"), $myrow["bags"], "class='tableheader2'", "nowrap");
end_row();

global $SysPrefs;
if($myrow["dimension_id"])
label_row(_($SysPrefs->prefs['dim1_name']), get_dimension($myrow["dimension_id"])['name'], "class='tableheader2'", "colspan=5");
if($myrow["dimension2_id"])
label_row(_($SysPrefs->prefs['dim2_name']), get_dimension($myrow["dimension2_id"])['name'], "class='tableheader2'", "colspan=5");

comments_display_row(ST_CUSTDELIVERY, $trans_id);
end_table();

echo "</td></tr>";
end_table(1); // outer table

$kv_batch = get_company_pref('kv_batch');
$kv_exp_date = get_company_pref('kv_exp_date');
$result = get_customer_trans_details(ST_CUSTDELIVERY, $trans_id);

start_table(TABLESTYLE, "width='95%'");
if($kv_exp_date)
	$colspan=11;
elseif($kv_batch)
	$colspan=9;
else
	$colspan = 9;

if (db_num_rows($result) > 0)
{
	$th = array(_("Item Code"), _("Item Description"), _("Weight"), _("Unit"),  
		_("Rate Type"), _("Rate"), _("Price"),  _("Discount %"), _("Total"),('Batch Price'),('Batch Total'),_("GL Debit"), _("GL Debit"),_('Update'));
	if($kv_exp_date){
		array_splice( $th, 6, 0, _("Batch No") );
		array_splice( $th, 7, 0, _("Exp Date") );
	}elseif($kv_batch)
		array_splice( $th, 6, 0, _("Batch No") );

		// array_splice( $th, 6, 0, _("Pack Size") );
		// array_splice( $th, 7, 0, _("Pack Unit") );
		// array_splice( $th, 8, 0, _("No of Pack") );
		
	table_header($th);

	$k = 0;	//row colour counter
	$sub_total = 0;
	$res = get_gl_trans(ST_CUSTDELIVERY, $_GET['trans_no']);
    if($_GET['void_gl']){
    	void_gl_trans(ST_CUSTDELIVERY, $_GET['trans_no'], true);

    }

   $show_void=false;
   $qty_sum=0;
	while ($myrow2 = db_fetch($result))
	{
		if($myrow2['quantity']==0) continue;
		alt_table_row_color($k);

		$value = round2(((1 - $myrow2["discount_percent"]) * $myrow2["unit_price"] * $myrow2["quantity"]),
		   user_price_dec());
		$sub_total += $value;

	    if ($myrow2["discount_percent"] == 0)
	    {
		  	$display_discount = "";
	    }
	    else
	    {
		  	$display_discount = percent_format($myrow2["discount_percent"]*100) . "%";
	    }

		label_cell($myrow2["stock_id"]);
		label_cell($myrow2["StockDescription"]);
        qty_cell($myrow2["quantity"], false, get_qty_dec($myrow2["stock_id"]));

        $qty_sum+=$myrow2["quantity"];
        label_cell(get_unit_descr($myrow2["unit_id"]), "align=right");
      amount_cell($myrow2["rate_type"]);
		amount_cell($myrow2["rate"]);
        if($kv_exp_date){
			label_cell($myrow2["batch_no"]);
			label_cell(sql2date($myrow2["exp_date"]));
		}elseif($kv_batch)
			label_cell($myrow2["batch_no"]);
         
        // $pack_row =  get_batch_no_packing($myrow2["batch_no"]);
        amount_cell($myrow2["unit_price"]);

        // label_cell($pack_row["pack_size"], "nowrap align=center");
        // label_cell(get_packing_descr($pack_row["pack_unit"]), "nowrap align=center");
        // label_cell($myrow2["quantity"]/$pack_row["no_of_pack"], "nowrap align=center");
        


        label_cell($display_discount, "nowrap align=right");
        amount_cell($value);
        unset($batch_price);
        $batch_price =  get_betch_price($myrow2["batch_no"],$myrow2["stock_id"],true,sql2date($myrow["tran_date"]));
         amount_cell($batch_price);
         amount_cell($batch_price*$myrow2["quantity"]);
         $amt=round2($batch_price*$myrow2["quantity"], user_price_dec());
         // display_error(user_price_dec());
          $row=db_fetch($res);
         amount_cell($row['amount']);
			// if($_GET['gl_update']==1  &&  abs($row['amount'])!=$amt)
			// {
			// 	$sql = "UPDATE ".TB_PREF."gl_trans SET amount=".db_escape($amt)." WHERE type=".ST_CUSTDELIVERY
			// 	." AND type_no=".db_escape($_GET['trans_no'])." AND counter=".db_escape($row['counter']);
			// 	// display_error($sql);
			// 	db_query($sql, "could not void gl transactions for type=$type and trans_no=$trans_id");
			// }
			// else 
				if($_GET['void_gl'] && abs($row['amount'])!=$amt){
			   $stock_gl_code = get_stock_gl_code($myrow2["stock_id"]);
			   add_gl_trans_std_cost(ST_CUSTDELIVERY, $_GET['trans_no'],
						sql2date($myrow["tran_date"]), $stock_gl_code["cogs_account"], $myrow["dimension_id"], $myrow["dimension_id"], "The cost of sales GL posting   update",
						$amt,
						PT_CUSTOMER, $myrow["debtor_no"],
						"The cost of sales GL posting inserted up");

			}
		if(!$row['account'])
         {
         	$stock_gl_code = get_stock_gl_code($myrow2["stock_id"]);
            $sql = "UPDATE ".TB_PREF."gl_trans SET account=".db_escape($stock_gl_code["cogs_account"])." WHERE type=".ST_CUSTDELIVERY
				." AND type_no=".db_escape($_GET['trans_no'])." AND counter=".db_escape($row['counter']);
     				display_error(" GL ACCOUNT UPDATE");
				db_query($sql, "could not updte Gl code");

         }	
         $row=db_fetch($res);
         amount_cell($row['amount']);
			// if($_GET['gl_update']==1  &&  abs($row['amount'])!=$amt)
			// {
			// 	$sql = "UPDATE ".TB_PREF."gl_trans SET amount=".db_escape(-$amt)." WHERE type=".ST_CUSTDELIVERY
			// 	." AND type_no=".db_escape($_GET['trans_no'])." AND counter=".db_escape($row['counter']);
			// 	// display_error($sql);
			// 	db_query($sql, "could not void gl transactions for type=$type and trans_no=$trans_id");
			// }
			// else
				if($_GET['void_gl'] && abs($row['amount'])!=$amt)
			{

				add_gl_trans_std_cost(ST_CUSTDELIVERY, $_GET['trans_no'], sql2date($myrow["tran_date"]),
						$stock_gl_code["inventory_account"], 0, 0, "The cost of sales GL posting update",
						-$amt,
						PT_CUSTOMER, $myrow["debtor_no"],
						"The stock side of the cost of sales GL posting update");

			}
			if(!$row['account'])
         {
         	$stock_gl_code = get_stock_gl_code($myrow2["stock_id"]);
            $sql = "UPDATE ".TB_PREF."gl_trans SET account=".db_escape($stock_gl_code["inventory_account"])." WHERE type=".ST_CUSTDELIVERY
				." AND type_no=".db_escape($_GET['trans_no'])." AND counter=".db_escape($row['counter']);
				// display_error($sql);
				db_query($sql, "could not updte Gl code");

         }

         if(round(abs($row['amount']),2)!=round(abs($amt),2))
         	{
         	   // display_error(round(abs($row['amount']),2) ."!=".round(abs($amt),2));
         	    ahref_cell("update", $path_to_root."/sales/view/view_dispatch.php?trans_no=".$_GET['trans_no']."&trans_type=13&gl_update=1");
                     $show_void=true;
           } 
         else
         	label_cell('-');


          // echo "<pre>";
          // print_r($row);
	end_row();
	} //end while there are line items to print out

	label_row(_("Total Qty"), price_format($qty_sum) , "colspan='2' align=left","nowrap align=left colspan='13'  width='15%'");
	$display_sub_tot = price_format($sub_total);
	label_row(_("Sub-total"), $display_sub_tot, "colspan=".$colspan." align=right","nowrap align=left colspan='6' width='15%'");

}
else
	display_note(_("There are no line items on this dispatch."), 1, 2);
if ($myrow['ov_freight'] != 0.0)
{
	$display_freight = price_format($myrow["ov_freight"]);
	label_row(_("Shipping"), $display_freight, "colspan=".$colspan." align=right", "nowrap align=right");
}

$tax_items = get_trans_tax_details(ST_CUSTDELIVERY, $trans_id);
display_customer_trans_tax_details($tax_items, $colspan);


$display_total = price_format($myrow["ov_freight"]+$myrow["ov_amount"]+$myrow["ov_freight_tax"]+$myrow["ov_gst"]);

$result = charges_trnas($trans_id, ST_CUSTDELIVERY);
$i = 1;
while ($myrow2 = db_fetch($result)){
	$charges_data = get_charge($myrow2['charge_id']);
	$lbl=($charges_data['is_negative'])? " (-)" : " (+)";
    $amount = $myrow2['charges_amount'];
    label_row(_($myrow2['name']." ".$lbl), price_format($amount), "colspan=9 align=right",
	"nowrap align=right");
	$display_total += $amount;
    $i++;
}

label_row(_("TOTAL VALUE"), $display_total, "colspan=".$colspan." align=right",	"nowrap align=left  colspan='6'");
if($show_void)
{
label_cell('-'," colspan='10' ");
ahref_cell("Void Gl and Update", $path_to_root."/sales/view/view_dispatch.php?trans_no=".$_GET['trans_no']."&trans_type=13&void_gl=1");
         	
}	

end_table(1);
if($_GET['void_gl']==1)
{
	meta_forward($_SERVER['PHP_SELF'], "trans_no=".$_GET['trans_no']."&trans_type=13");
}	

is_voided_display(ST_CUSTDELIVERY, $trans_id, _("This dispatch has been voided."));

end_page(true, false, false, ST_CUSTDELIVERY, $trans_id);

