<?php


$page_security = $_POST['PARAM_0'] == $_POST['PARAM_1'] ?
	'SA_SUPPTRANSVIEW' : 'SA_SUPPBULKREP';

$path_to_root="..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");


print_supp_invoices();


//----------------------------------------------------------------------------------------------------
//pk

function get_invoice_range($from, $to)
{
	global $SysPrefs;

	$ref = ($SysPrefs->print_invoice_no() == 1 ? "trans_no" : "reference");

	$sql = "SELECT trans.trans_no, trans.reference, trans.brokery_percent
		FROM ".TB_PREF."supp_trans trans 
			LEFT JOIN ".TB_PREF."voided voided ON trans.type=voided.type AND trans.trans_no=voided.id
		WHERE trans.type=".ST_SUPPINVOICE
			." AND ISNULL(voided.id)"
			." AND trans.reference>=".db_escape(get_reference(ST_SUPPINVOICE, $from))
			." AND trans.reference<=".db_escape(get_reference(ST_SUPPINVOICE, $to))
		." ORDER BY trans.tran_date, trans.$ref";

// display_error($sql);
	return db_query($sql, "Cant retrieve invoice range");
}

function get_gl_dimension($trans_no,$type){
	$sql = " SELECT * FROM ".TB_PREF."gl_trans WHERE type_no = '$trans_no' AND type = '$type' AND (dimension_id !=0 OR dimension2_id != 0) ";
	// display_error($sql);exit;
	$result =  db_query($sql, " ");
	return db_fetch($result);
}

function get_grn_items_data($id){
	$sql = " SELECT * FROM ".TB_PREF."grn_items WHERE id = '$id' ";
	$result =  db_query($sql, " ");
	return db_fetch($result);
}
function get_purch_order_details_data($id){
	$sql = " SELECT * FROM ".TB_PREF."purch_order_details WHERE po_detail_item = '$id' ";
	$result =  db_query($sql, " ");
	return db_fetch($result);
}

function get_purch_order_data($order_no){
	$sql = " SELECT * FROM ".TB_PREF."purch_orders WHERE order_no = '$order_no' ";
	$result =  db_query($sql, " ");
	return db_fetch($result);
}
function get_grn_batch_data($id){
	$sql = " SELECT * FROM ".TB_PREF."grn_batch WHERE id = '$id' ";
	$result =  db_query($sql, " ");
	return db_fetch($result);
}
//----------------------------------------------------------------------------------------------------
function print_supp_invoices(){

	global $path_to_root, $SysPrefs;

	include_once($path_to_root . "/reporting/includes/pdf_report.inc");

	$from = $_POST['PARAM_0'];
	$to = $_POST['PARAM_1'];
	$currency = $_POST['PARAM_2'];
	$email = $_POST['PARAM_3'];
	$pay_service = $_POST['PARAM_4'];
	$comments = $_POST['PARAM_5'];
	$supplier = $_POST['PARAM_6'];
	$show_logo = $_POST['PARAM_7'];
	$orientation = $_POST['PARAM_8'];

	if (!$from || !$to) return;

	$orientation = ($orientation ? 'L' : 'P');
	$dec = user_price_dec();

 	$fno = explode("-", $from);
	$tno = explode("-", $to);
	$from = min($fno[0], $tno[0]);
	$to = max($fno[0], $tno[0]);
	// display_error($from ."     ".$to);exit;

	//-------------code-Descr-Qty--uom--tax--prc--Disc-Tot--//
	$cols = array(4, 60, 200,300, 360, 410, 450, 515);

	// $headers in doctext.inc
	$aligns = array('left',	'left',	'left',	'left', 'center', 'right');

	$params = array('comments' => $comments);

	$cur = get_company_Pref('curr_default');

	if ($email == 0)
		$rep = new FrontReport(_('INVOICE'), "InvoiceBulk", user_pagesize(), 9, $orientation);
	if ($orientation == 'L')
		recalculate_cols($cols);

    // $rep->show_logo=$show_logo;
	$range = get_invoice_range($from, $to);
	while($row = db_fetch($range)){

		if (!exists_supp_trans(ST_SUPPINVOICE, $row['trans_no']))
				continue;
		
		$sign = 1;
		$myrow = get_supp_trans($row['trans_no'], ST_SUPPINVOICE);
		// print_r($myrow);exit();
		if ($supplier && $myrow['supplier_id'] != $customer) {
			continue;
		}
		if ($currency != ALL_TEXT && $myrow['curr_code'] != $currency) {
			continue;
		}

		$baccount = get_default_bank_account($myrow['curr_code']);
		$params['bankaccount'] = $baccount['id'];

		$branch = null;
		$po_order = null;

		if ($email == 1)
		{
			$rep = new FrontReport("", "", user_pagesize(), 9, $orientation);
			$rep->title = _('INVOICE');
			$rep->filename = "Invoice" . $myrow['reference'] . ".pdf";
		}
		// -------------------for delivery note # ----------------------------------
			$result = get_supp_invoice_items(ST_SUPPINVOICE, $row['trans_no']);
			while($grn_item_id = $myrow2=db_fetch($result)){
				if($grn_item_id['grn_item_id'] != -1){
					$grn_item_id = $grn_item_id['grn_item_id'];
					break;
				}
			}

			$grn_item_row=get_grn_items_data($grn_item_id);
			$grn_batch_row =  get_grn_batch_data($grn_item_row['grn_batch_id']);

            $po_order =	$grn_batch_row['purch_order_no'];

            $order_row = get_purch_order_data($po_order);

			// print_r($order_row);exit();

			// $grn_item_id


            // display_error( $rep->formData['last_del_date'] );exit();

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

		$rep->currency = $cur;
		$rep->Font();
		$rep->Info($params, $cols, null, $aligns);
        // print_r($myrow);exit();
		$contacts = null;
		$baccount['payment_service'] = $pay_service;
		$rep->SetCommonData($myrow, $branch, $order_row, $baccount, ST_SUPPINVOICE, $contacts,$grn_item_id);
		          $rep->formData['last_del_date'] = $myrow2['exp_date'];

		$rep->SetHeaderType('Header2');
		$rep->NewPage();

		// calculate summary start row for later use
			$summary_start_row = $rep->bottomMargin + (15 * $rep->lineHeight);

		$result = get_supp_invoice_items(ST_SUPPINVOICE, $row['trans_no']);
		$SubTotal = 0;
		$gl_codes =0;
		while ($myrow2=db_fetch($result)){
			
			if ($myrow2["quantity"] == 0){
				$gl_codes = 1;
				continue;

			}

			$Net = round2(($sign *   $myrow2["unit_price"] * $myrow2["quantity"]),user_price_dec());
			$SubTotal += $Net;

			$DisplayPrice = number_format2($myrow2["unit_price"],$dec);
    		$DisplayQty = number_format2($sign*$myrow2["quantity"],get_qty_dec($myrow2['stock_id']));
    		$DisplayNet = number_format2($Net,$dec);

    		$c=0;
			$rep->TextCol($c++, $c,	$myrow2['stock_id'], -2);
			$oldrow = $rep->row;
			$rep->TextColLines($c++, $c, $myrow2['description'] , -2);
			$newrow = $rep->row;
			$rep->row = $oldrow;

			if ($Net != 0.0 || !is_service($myrow2['mb_flag']) || !$SysPrefs->no_zero_lines_amount())
			{
				$rep->TextCol($c++, $c,	$DisplayQty, -2);
				$rep->TextCol($c++, $c,	get_unit_descr($myrow2['units']), -2);
				$rep->TextCol($c++, $c,	$DisplayPrice, -2);
				// $rep->TextCol($c++, $c,	$DisplayDiscount, -2);
				$rep->TextCol($c++, $c,	$DisplayNet, -2);
			}
			$rep->row = $newrow;

			if ($rep->row < $summary_start_row)
				$rep->NewPage();

		if($grn_batch_row['kat_percentage']){
			// $rep->TextCol(1, 2, _("Kat %") , -2);
			// $rep->TextCol(2, 3, number_format2($grn_batch_row['kat_percentage'], $dec) , -2);
			// $rep->NewLine();
			// $rep->TextCol(1, 2, _("Kat Weight") , -2);
			$kat_perc = $myrow2["quantity"]/100;
			$kat_weight = $grn_batch_row['kat_percentage']*$kat_perc;
			// $rep->TextCol(2, 3, number_format2($kat_weight, $dec) , -2);
			$rep->NewLine();
			// $rep->TextCol(1, 2, _("Net Weight") , -2);
			$net_weight = $myrow2["quantity"]-$kat_weight;
			// $rep->TextCol(2, 3, number_format2($net_weight, $dec) , -2);
		}

		}

		//----------------------- code for gl codes
		if($gl_codes == 1){
			// $headers = array(_("Account"), _("Name"), _("Dimension 1"),_("Dimension 2"), _("Amount"));
			// $cols = array(4, 70, 180, 280, 380, 460, 515);
			// $aligns = array('left',	'left',	'left', 'left', 'right');
			
			// $rep->Info($params, $cols, $headers, $aligns);
			// $rep->NewPage();

			$result = get_supp_invoice_items(ST_SUPPINVOICE, $row['trans_no']);
			$newrow = [];
			while ($myrow3=db_fetch($result)){

				if ($myrow3["gl_code"] == 0){
					continue;
				}

				$c=4;
				// $rep->TextCol($c++, $c,	$myrow3['gl_code'], -2);
				$oldrow = $rep->row;
				// $rep->TextColLines(3, 6, trim(get_gl_account_name($myrow3['gl_code'])) , -2);
				$newrow[] = $rep->row;
				$rep->row = $oldrow;

				// $oldrow = $rep->row;
				// $rep->TextColLines($c++, $c,	trim(get_dimension_string($myrow3['dimension_id'])), -2);
				// $newrow[] = $rep->row;
				// $rep->row = $oldrow;

				// $oldrow = $rep->row;
				// $rep->TextColLines($c++, $c,	trim(get_dimension_string($myrow3['dimension2_id'])), -2);
				// $newrow[] = $rep->row;
				// $rep->row = $oldrow;
				// $c+=1;
				$rep->aligns[7]='right';
				// if($myrow3['FullUnitPrice']>0)
				// $rep->TextCol(7, 8,	number_format2($myrow3['FullUnitPrice'],$dec), -2);
				// else
				// $rep->TextCol(7, 8,	" ( " .number_format2(abs($myrow3['FullUnitPrice']),$dec).")" , -2);

				// memo_
				$rep->row = min($newrow);
				$rep->newLine(0.5);
				unset($newrow);
				if ($rep->row < $summary_start_row)
					$rep->NewPage();	

			}			


		}

		$memo = get_comments_string(ST_SUPPINVOICE, $row['trans_no']);
		if ($memo != ""){
			$rep->NewLine();
			$rep->TextColLines(1, 3, $memo, -2);
		}

         $truck_row=get_truck_details($po_order,0,$grn_item_row['grn_batch_id']);
 // print_r($truck_row);
 //          print_r($grn_item_row);exit();
         $show_detail= "X-Weight : ".$truck_row['x_weight']."  ,  Mill Weight : ".$truck_row['mill_weigh']."\nTruck # : ".$truck_row['truck_of_no']."  ,  Batch No : ".$grn_item_row['batch_no'];
   		$rep->TextColLines(1, 3, $show_detail, -2);
		//--------------------- code for gl codes


		$DisplaySubTot = number_format2($SubTotal,$dec);

		$rep->row = $summary_start_row-20;
		$doctype = ST_SUPPINVOICE;
		// $rep->cols[2] += 20;
		$rep->cols[2] += 40;
		// $rep->aligns[3] = 'left';

		$rep->TextCol(2, 5, _("Sub-total"), -2);
		$rep->TextCol(5, 6,	 $DisplaySubTot, -2);
		$rep->NewLine();

		if($row['brokery_percent']){
			$rep->TextCol(2, 5, _("Brokery (Rs)"), -2);
			$rep->TextCol(5, 6,	 $row['brokery_percent'], -2);
		}
		$rep->NewLine();

		$tax_items = get_trans_tax_details(ST_SUPPINVOICE, $row['trans_no']);
		$first = true;
    	while ($tax_item = db_fetch($tax_items))
		{
			if ($tax_item['amount'] == 0)
				continue;
			$DisplayTax = number_format2($sign*$tax_item['amount'], $dec);

			if ($SysPrefs->suppress_tax_rates() == 1)
				$tax_type_name = $tax_item['tax_type_name'];
			else
				$tax_type_name = $tax_item['tax_type_name']." (".$tax_item['rate']."%) ";

			if ($myrow['tax_included'])
			{
				if ($SysPrefs->alternative_tax_include_on_docs() == 1)
				{
					if ($first)
					{
						$rep->TextCol(2, 5, _("Total Tax Excluded"), -2);
						$rep->TextCol(5, 6,	number_format2($sign*$tax_item['net_amount'], $dec), -2);
						$rep->NewLine();
					}
					$rep->TextCol(2, 6, $tax_type_name, -2);
					$rep->TextCol(5, 6,	$DisplayTax, -2);
					$first = false;
				}
				else{
					// $rep->cols[3] -= 40;
					$rep->TextCol(2, 6, _("Included") . " " . $tax_type_name . _("Amount") . ": " . $DisplayTax, -2);
				}
			}
			else
			{
				$rep->TextCol(2, 6, $tax_type_name, -2);
				$rep->TextCol(5, 6,	$DisplayTax, -2);
			}
			$rep->NewLine();
		}
		$rep->NewLine();
		$SubTotal=$sign*($myrow["ov_gst"] + $myrow["ov_amount"]);
		$DisplayTotal = number_format2($sign*($myrow["ov_gst"] + $myrow["ov_amount"]),$dec);
		$rep->Font('bold');
		$rep->TextCol(2, 6, $rep->formData['prepaid'] ? _("TOTAL ORDER VAT INCL.") : _("TOTAL INVOICE"), - 2);
		$rep->TextCol(5, 6, $DisplayTotal, -2);

			$words = price_in_words($SubTotal, ST_PURCHORDER);
		if ($words != "")
		{
			$rep->NewLine(1);
			$rep->TextCol(1, 7, $myrow['curr_code'] . ": " . $words, - 2);
		}

		$rep->Font();
		if ($email == 1)
		{
			$rep->End($email);
		}

		$rep->TextWrap(96,47,150,"_________________"); 
	    $rep->TextWrap(105,35,150, _("Prepared By")); 

	    $rep->TextWrap(260,47,150,"_________________"); 
	    $rep->TextWrap(270,35,150, _("Reviewed By")); 

	    // $rep->TextWrap(441,47,150,"_________________"); 
	    // $rep->TextWrap(452,35,150, _("Approved By"));

	    
     $rep->TextWrap(410,47,180,"________________________________________________"); 
	 $rep->TextWrap(410,35,180, _("For ".$rep->company['coy_name']),'center');
     $rep->TextWrap(410,23,180, _("Authurized Signature"),'center');

	}


	if ($email == 0)
		$rep->End();
}