<?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");


$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(900, 600);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page($_SESSION['page_title']='Srarch All Delivery  GL details', false, false, "", $js);
// 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"];
// }
// if(!isset($_GET['from']) || !isset($_GET['to']))
// {
// 	display_error("please get form and to number");
// }
// 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(_("DISPATCH NOTE WITH GL"));

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_form();
start_table(TABLESTYLE, "width='100%'");

global 	$Ajax;
// 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(_("Sales Person"), $myrow["vehicle_no"], "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);

stock_items_list_cells(_("Item:"), 'stock_id', null, true, true);
date_cells(_("from:"), 'fromdate', '', null, -user_transaction_days());
  	date_cells(_("to:"), 'todate', '', null, 1);
submit_cells('SearchOrders', _("Search"),'',_('Select documents'), 'default');

end_table();

echo "</td></tr>";
end_table(1); // outer table
// display_error($s." ss");

if (get_post('SearchOrders'))
{
	$Ajax->activate('_page_body');
	// $Ajax->activate('totals_tbl');
}

$kv_batch = get_company_pref('kv_batch');
$kv_exp_date = get_company_pref('kv_exp_date');

start_table(TABLESTYLE, "width='95%'");
if($kv_exp_date)
	$colspan=11;
elseif($kv_batch)
	$colspan=10;
else
	$colspan = 9;
// if (db_num_rows($result) > 0)
// {
	$th = array(_("Delivery No"),_("Item Code"), _("Item Description"),_("Date"), _("Quantity"), _("Unit"), _("Price"),  _("Discount %"), _("Total"),('batch_price'),('batch total'),_("GL debit"), _("GL Debit"),_('Update'),_('GL Account'));
	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, 7, 0, _("Pack Size") );
		array_splice( $th, 8, 0, _("Pack Unit") );
		array_splice( $th, 9, 0, _("No of Pack") );
		
	table_header($th);

// for ($s=$_GET['from']; $s <=$_GET['to'] ; $s++) { 
	// code...
		// display_error($_POST['stock_id']." sh");
$result2 =  get_customer_trans_details_date(ST_CUSTDELIVERY, $_POST['fromdate'],$_POST['todate'],$_POST['stock_id']);
	$k = 0;	//row colour counter
	$sub_total = 0;





    // if($_GET['void_gl']){
    // 	void_gl_trans(ST_CUSTDELIVERY, $_GET['trans_no'], true);

    // }
 // $myrow = get_customer_trans($s, ST_CUSTDELIVERY);
   $show_void=false;
   $grn_no=0;
   $gl_sum=0;
	while ($myrow2 = db_fetch($result2))
	{
		// print_r($myrow2);

		if(  $grn_no!=$myrow2["debtor_trans_no"]){

			$void_entry = get_voided_entry(ST_CUSTDELIVERY, $myrow2["debtor_trans_no"]);
		  if($void_entry)
			  continue;

				$res = get_gl_trans(ST_CUSTDELIVERY, $myrow2["debtor_trans_no"]);

			}

			  $grn_no =$myrow2["debtor_trans_no"];

		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) . "%";
	    }
		// get_customer_trans_view_str(ST_SALESORDER, $row['order_'])
       label_cell(get_customer_trans_view_str(ST_CUSTDELIVERY,$myrow2["debtor_trans_no"])." - ".get_gl_view_str(ST_CUSTDELIVERY, $myrow2["debtor_trans_no"]) );
		label_cell($myrow2["stock_id"]);
		label_cell($myrow2["StockDescription"]);
		label_cell(sql2date($myrow2["tran_date"]));
        qty_cell($myrow2["quantity"], false, get_qty_dec($myrow2["stock_id"]));
        label_cell($myrow2["units"], "align=right");
        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"]);

        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");
        
        amount_cell($myrow2["unit_price"]);


        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']);
           $gl_sum+=$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($delivery_line->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");

			}
         $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(round(abs($row['amount']),2)!=round(abs($amt),2))
         	{
         		label_cell("Not Match","style=' background:red;color: white;' ");
         		// 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('-');
         	
         	
           if(!$row['account'])
         {
         		label_cell("Empty GL","style=' background:orange;color: white;' ");


         }
         else
         	label_cell('Ok');   	


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

	start_row();

	label_cell("<b>Total</b>");
	label_cell("-","colspan=11");
	amount_cell($sub_total);
		label_cell("-","colspan=2");
		amount_cell($gl_sum);
			label_cell("-","colspan=4");
	      

	end_row();
// // }
// 	$display_sub_tot = price_format($sub_total);
// 	label_row(_("Sub-total"), $display_sub_tot, "colspan=".$colspan." align=right","nowrap align=right 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"]);

// label_row(_("TOTAL VALUE"), $display_total, "colspan=".$colspan." align=right",	"nowrap align=right");
// 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_form();
end_page();

