<?php defined("BASEPATH") OR exit("No direct script access allowed");

require_once(APPPATH . "/third_party/EscPos.php");

$min_lines = $this->config->item("print_min_lines");

$totQty = 0;

$CharLen = empty($CharLen) ? $this->config->item("print_char_length") : $CharLen;

if (!empty($CharLen))
{
	EscPos::$CharLen = $CharLen;
}
else
{
	$CharLen = EscPos::$CharLen;
}

/*
$_CharLen = $this->config->item("print_char_length");
$CharLen = 38;

// To use in justify helper.
$this->config->set_item("print_char_length", $CharLen);
*/

if ($isShipping && $tType != "PE" && (!$sameAsBill || empty($hidShipAdr)))
{
	$isShipping = true;
}
else
{
	$isShipping = false;
}
$lines = array();

//---Company Name & Address Begins

$lines[] = EscPos::Bold(justify(strtoupper(strip_tags($company["name"])), "C", $CharLen));

// Begin
$address = "";
if (!empty($company["address1"]))
{
	$lines[] = justify(ucfirst(preg_replace("!\s+!", " ", $company["address1"])), "C", $CharLen);
}
if (!empty($company["address2"]))
{
	$lines[] = justify(ucfirst(preg_replace("!\s+!", " ", $company["address2"])), "C", $CharLen);
}
if (!empty($company["city"]))
{
	$str = $company["city"];
	$str .= (!empty($company["zip"]) ? "-" . $company["zip"] : "");
	if (!empty($company["stateName"]))
	{
		$str .= ", " . strip_tags($company["stateName"]);
	}

	$lines[] = justify($str, "C", $CharLen);
}
/*
if (!empty($company["country"]))
{
	$lines[] = $company["country"];
}*/
if (!empty($company["phone"]))
{
	$lines[] = justify("Phone: " . strip_tags($company["phone"]), "C", $CharLen);
}
if (!empty($company["email"]))
{
	$lines[] = justify($company["email"], "C", $CharLen);
}
if (!empty($company["gstin"]))
{
	$lines[] = justify(mylang("GSTIN") . ' :' . strip_tags($company["gstin"]), "C", $CharLen);
}
if (!empty($company['addInfo']))
{
	$lines[] = justify(strip_tags($company['addInfo']), "C", $CharLen);
}
$lines[] = "";

$lines[] = EscPos::Bold(justify(strip_tags($titleText), "C", $CharLen));
$lines[] = "";
if (
		($tType == "SH" || $tType == "TD" || $tType =="GR" || $tType =="TR") &&
		!empty($contact) &&
		!empty($contact['csType']) &&
		($contact['csType'] == 'B' || $contact['csType'] == 'L')
	) {
		$lines[] = EscPos::Bold(justify("Stock Transfer / Branch Transfer",'C', $CharLen));
	}
$line = "";
$line .= "BillNo: " . strip_tags($tNo);
$line .= justify(strip_tags($tDate), "R", $CharLen - strlen($line));
// $lines[] = justify("BillNo: " . strip_tags($tNo), "L", $CharLen);
// $lines[] = justify("Date: " . strip_tags($tDate), "L", $CharLen);
$lines[] = $line;

$str = array();
if (!empty($conName))
{
	$str[] = $conName . (!empty($city) ? "," . $city : "");
}
$str = implode(", ", $str);
if (!empty($str))
{
	$lines[] = justify(strip_tags($str), "L", $CharLen);
}
$sale_rep = array();
if (!empty($sRepName)&& !empty($issalesrep))
{
 	$sale_rep[]  = $sRepName . (!empty($sRepMobile) ? "," . $sRepMobile : "");
}
$sale_rep = implode(", ", $sale_rep);
if(!empty($sale_rep)){
	$lines[] = justify("Sales Rep:" .strip_tags($sale_rep), "L", $CharLen);
}
if (!empty($isprojectname) && !empty($prjName)){
	$lines[] = justify(mylang("ProjectName").":".strip_tags($prjName), "L", $CharLen);
}
if(!empty($refName)){
	$lines[] = justify(mylang("ReferredBy").":".strip_tags($refName), "L", $CharLen);
}
/*$table = array(array(),array(),array());

// Max str length begins

$colWid = array(
	floor($CharLen / 2)
	// 40
);


$inv_info = array();
// Customer Name & Address Begins
if(!empty($contact))
{
	$contact["name"] = !empty($contact["conName"]) ? $contact["conName"] : $contact["name"];
	if (!empty($contact["name"]))
	{
		$issuedTo = ($tType == "PI") ? lang("Supplier") : lang("Issued");
		$table[0][] = justify($issuedTo . ":", "L", $colWid[0]);
		$table[0][] = justify(strip_tags($contact["name"]), "L", $colWid[0]);
	}
}

if(!empty($billing["above_addr"]))
{
	foreach($billing["above_addr"] as $row)
	{
		$table[0][] = justify(strip_tags($row), "L", $colWid[0]);
	}
}
$showPos = ($conStateCode == $company["stateCode"]) ? false : true;
if(!empty($isShowAddress) && !empty($billing["countryCode"]))
{
	$line = array();
	if (!empty($billing["address1"]))
	{
		$line[] = ucwords(trim($billing["address1"], ","), ",\n ");
	}
	if (!empty($billing["address2"]))
	{
		$line[] = ucwords(trim($billing["address2"], ","), ",\n ");
	}
	if (!empty($billing["city"]))
	{
		$line[] = ucwords(trim($billing["city"] . (empty($billing["zip"]) ? "" : ("-" . $billing["zip"])), ","), ",\n ");
	}*/
	/*
	if (!empty($billing["country"]))
	{
		$line[] = $billing["country"];
	}
	*/

	/*$line = explode("\n", wordwrap(strip_tags(implode(", ", $line)), $colWid[0]));
	$table[0] = array_merge($table[0], $line);
	// $table[0][] = $line;
}
*/
/*if(empty($conTaxNo) && !empty($contact["taxNo"]))
{
	$conTaxNo = $contact["taxNo"];
}
$line = array();
if(!empty($conTaxNo))
{
	// $line[] = "GSTIN: " . $conTaxNo;
	$table[0][] = justify("GSTIN: " . $conTaxNo, "L", $colWid[0]);
}
if($showPos && !empty($pos))
{
	$table[0][] = justify(($tType == PURINV ? "SOS" : "POS") . ": " . $pos, "L", $colWid[0]);
	// $line[] = ($tType == PURINV ? "SOS" : "POS") . ": " . $pos;
}

if ($line && count($line) > 0)
{
	$line = implode(",", $line);
	$table[0][] = justify($line, "L", $colWid[0]);
}

if ($tType != SALRETAIL && !empty($billing["mobile"]))
{
	$table[0][] = justify("Mobile: " . $billing["mobile"], "L", $colWid[0]);
}
if(!empty($billing["below_addr"]))
{
	foreach($billing["below_addr"] as $row)
	{
		$table[0][] = justify(strip_tags($row), "L", $colWid[0]);
	}
}
// Customer Name & Address End
*/
// Inv No Begins
/*$tNo_text = strip_tags($tNo_text);
$tNo = strip_tags($tNo);
$table[1][] = $tNo_text;
$table[2][] = ": " . $tNo;
// Inv No End

// Inv Date Begins
$tDate_text = strip_tags($tDate_text);
$tDate = strip_tags($tDate);
$table[1][] = $tDate_text;
$table[2][] = ": " . $tDate;
// Inv Date End

if ($dueDate && !empty($isDueDate))
{
	$dueDate_text = strip_tags($dueDate_text);
	$dueDate = strip_tags($dueDate);
	$table[1][] = $dueDate_text;
	$table[2][] = ": " . $dueDate;
}
if (!empty($sRepName) && !empty($issalesrep))
{
	$dueDate_text = strip_tags($srep_text);
	$dueDate = strip_tags($sRepName);
	$table[1][] = $srep_text;
	$table[2][] = ": " . $sRepName;
}
if (!empty($sRepMobile) && !empty($issalesrep))
{
	$srep_mobile_text = strip_tags($srep_mobile_text);
	$sRepMobile = strip_tags($sRepMobile);
	$table[1][] = $srep_mobile_text;
	$table[2][] = ": " . $sRepMobile;
}

if ($dueDate && !empty($relNumber))
{
	$rel_tNo_text = strip_tags($rel_tNo_text);
	$relNumber = strip_tags($relNumber);
	$table[1][] = $rel_tNo_text;
	$table[2][] = ": " . $relNumber;
}

if (!empty($relDate))
{
	$rel_tDate_text = strip_tags($rel_tDate_text);
	$relDate = strip_tags($relDate);
	$table[1][] = $rel_tDate_text;
	$table[2][] = ": " . $relDate;
}

if ($paymentName)
{
	$table[1][] = "Payment Mode";
	$table[2][] = ": " . $paymentName;
}

$lengths = array_map("strlen", $table[0]);
if (!empty($lengths))
{
	$lengths = max($lengths) + 1;
	$colWid[0] = $lengths;
}
else
{
	$colWid[0] = 0;
}

$lengths = array_map("strlen", $table[1]);
$lengths = max($lengths) + 1;
$lengths = $CharLen < $lengths ? $CharLen : $lengths;
$colWid[1] = $lengths;
$colWid[2] = $CharLen - ($colWid[0] + $colWid[1]);

// $line .= justify($tNo_text, "L", $colWid[1]) . ": " . $tNo;
// $lines[] = $line;

$rowsCnt = max(array_map("count", $table));
for($i=0; $i<$rowsCnt; $i++)
{
	$line = "";
	if (!empty($colWid[0]))
	{
		$line .= justify(empty($table[0][$i]) ? "" : $table[0][$i], "L", $colWid[0]);
	}
	$line .= justify(empty($table[1][$i]) ? "" : $table[1][$i], "L", $colWid[1]);
	$line .= justify(empty($table[2][$i]) ? "" : $table[2][$i], "L", $colWid[2]);
	$lines[] = $line;
}

// echo nl();

$col_1 = array();
$row_w1= array(40,20,18);
$col_2 = array();*/
/*
$col_2[] = justify(strip_tags($tNo_text),"L",$row_w1[1]).EscPos::Bold(justify(":".strip_tags($tNo),"L",$row_w1[2]));
$col_2[] = justify(strip_tags($tDate_text),"L",$row_w1[1]).EscPos::Bold(justify(":".strip_tags($tDate),"L",$row_w1[2]));
if ($dueDate && !empty($isDueDate)) {
	$col_2[] = justify(strip_tags($dueDate_text),"L",$row_w1[1]).justify(":".strip_tags($dueDate),"L",$row_w1[2]);
}*/

/*if (!empty($ref))
{
	$col_2[] = justify(strip_tags("Reference No"),"L",$row_w1[1]).justify(":".strip_tags($ref),"L",$row_w1[2]);
}
if ($tType == DELCHALLAN && $classCode)
{
	$col_2[] = justify(strip_tags("Challan Type"),"L",$row_w1[1]).justify(":".strip_tags($classCode),"L",$row_w1[2]);
}
$n = count($col_1) > count($col_2) ? count($col_1) : count($col_2);
for($i=0;$i<$n;$i++)
{
	$line = isset($col_1[$i]) ? $col_1[$i] : justify("", "L", $row_w1[0]);
	$line .= isset($col_2[$i]) ? $col_2[$i] : justify("", "L", $row_w1[1] + $row_w1[2]);
	if($i != $n - 1)
	{
		$lines[] = $line;
	}
}
$lines[] = EscPos::DrawLine();

if (!empty($tType!=PURINV) && !empty($tType!=PURCRNOTE) && !empty($tType != PURDBNOTE) && !empty($tType != EXPRETAIL))
{

	$col_1 = $col_2 = $col_3 = array();
	if(!empty($billing["name"]) || !empty($shipping["name"]))
	{
		$row_w2 = array(10,26,10,26);
		if(!empty($isShowAddress) && !empty($billing["countryCode"]))
		{
			if ($isShipping && !$isAllServices)
			{
				$row_w2 = array(8,18,8,16,8,16);
			}
		}
*/
	 /*   if(!$expCurrencyCode)
		{
			if(!empty($conTaxNo))
			{
				$col_1[] = justify("GSTIN","L",$row_w2[0]).justify(":".$conTaxNo,"L",$row_w2[1]);
			}
			else if(!empty($contact["taxNo"]))
			{
				$col_1[] = justify("GSTIN","L",$row_w2[0]).justify(":".$contact["taxNo"],"L",$row_w2[1]);
			}
			if(!empty($pos) && $tType!=EXPRETAIL && $tType!=PURINV)
			{
				$col_1[] = justify("POS","L",$row_w2[0]).justify(":".$pos,"L",$row_w2[1]);
			}
			if($tType==PURINV)
			{
				$col_1[] = justify("SOS","L",$row_w2[0]).justify(":".$pos,"L",$row_w2[1]);
			}
		}
*/
   /*	 if (!empty($contact["contactPersonMobile"]))
		{
			$billing["mobile"] = $contact["contactPersonMobile"];
			$shipping["mobile"] = $contact["contactPersonMobile"];
		}

		if(!empty($isShowAddress) && !empty($billing["countryCode"])) { 
			$addr = "Billing" . ($isAllServices || $isShipping ? "" : " & Shipping") . " Address :";

			if ($tType == "PO")
			{
				$addr = "Supplier";
			}
			$col_2[] = justify($addr,"L",$row_w2[2]+$row_w2[3]);

			$col_2[] = justify(strip_tags($billing["name"]),"L",($row_w2[2]+$row_w2[3]));
			$col_2[] = justify(strip_tags($billing["address1"]),"L",$row_w2[2]+$row_w2[3]);
			if (!empty($billing["address2"])) {
				$col_2[] = justify(strip_tags($billing["address2"]),"L",$row_w2[2]);
			}
			$str = $billing["city"].(!empty($billing["zip"])?" - ".$billing["zip"]:"").",".$billing["stateName"];
			if(!empty($billing["mobile"]))
			{
				$col_2[] = justify("Mobile","L",$row_w2[2]).justify(":".$billing["mobile"],"L",$row_w2[3]);
			}

			if(!empty($billing["phone"]))
			{
				$col_2[] = justify("Phone","L",$row_w2[2]).justify(":".$billing["phone"],"L",$row_w2[3]);
			}

			if(!empty($billing["email"]))
			{
				$col_2[] = justify($billing["email"],"L",$row_w2[2]+$row_w2[3]);
			}

			if ($isShipping && !$isAllServices) {
				$addr = "Shipping Address :";

				if ($tType == "PO")
				{
					$addr = "Supplier";
				}
				$col_3[] = justify($addr,"L",$row_w2[4]+$row_w2[5]);
				
				$col_3[] = justify(strip_tags($shipping["name"]),"L",$row_w2[4]+$row_w2[5]);
				$col_3[] = justify(strip_tags($shipping["address1"]),"L",$row_w2[4]+$row_w2[5]);
				if (!empty($shipping["address2"])) {
					$col_3[] = justify(strip_tags($shipping["address2"]),"L",$row_w2[4]+$row_w2[5]);
				}
				$str = $shipping["city"].(!empty($shipping["zip"])?" - ".$shipping["zip"]:"").",".$shipping["stateName"];
				if(!empty($shipping["mobile"]))
				{
					$col_3[] = justify("Mobile","L",$row_w2[4]).justify(":".$shipping["mobile"],"L",$row_w2[5]);
				}

				if(!empty($shipping["phone"]))
				{
					$col_3[] = justify("Phone","L",$row_w2[4]).justify(":".$shipping["phone"],"L",$row_w2[5]);
				}

				if(!empty($shipping["email"]))
				{
					$col_3[] = justify($shipping["email"],"L",$row_w2[4]+$row_w2[5]);						
				}
			}
		}
*/
		/*$n = count($col_1)>count($col_2)?count($col_1):count($col_2);
		for($i=0; $i<$n; $i++)
		{
			$line = isset($col_1[$i]) ? $col_1[$i] : (($col_1) ? justify("", "L", $row_w2[0] + $row_w2[1]) : "");
			$line .= isset($col_2[$i]) ? $col_2[$i] : (($col_2) ? justify("", "L", $row_w2[2] + $row_w2[3]) : "");
			$line .= isset($col_3[$i]) ? $col_3[$i] : (($col_3) ? justify("", "L", $row_w2[4] + $row_w2[5]) : "");

			$lines[] = $line;
		}
	}
}
*/
//if (!empty($export_details[0]["value"]))
//{
	// $this->view($exportDetailsView);
	$lines[] = EscPos::DrawLine();
//}

/*$gridFields = array();
if(!empty($fields))
{
	// $this->view($custFieldsView);
	$fcnt = count($fields);
	$hasVal = false;

	$line = "";
	foreach ($fields as $key => $row)
	{
		if (empty($row["isPrint"]))
		{
			continue;
		}

		// Skip for Invoice Item Grid, Cash Invoice Item Grid
		if ($row["tType"] == "IG" || $row["tType"] == "RG")
		{
			$row["fValue"] = json_decode($row["fValue"], true);
			$gridFields[] = $row;
			continue;
		}

		if ($row["fValue"])
		{
			$hasVal = true;
			$line .= justify($row["fName"] . ": " . $row["fValue"], "L", floor($CharLen / 2));
		}

		if($key%2 && $fcnt>($key+1))
		{
			$lines[] = $line;
			$line = "";
		}
	}

	if ($line)
	{
		$lines[] = $line;
	}

	if ($hasVal)
	{
		$lines[] = EscPos::DrawLine();
	}
}
*/

if (!empty($details))
{
	$t_head = array();
	$tlen = 0;
	$subTotalCols = array(0,0,0,0);

	/*if ($isSlNoCol)
	{
		$t_head["sno"] = array("name" => "SNo", "wd"=>3, "al" => "R");
		$tlen += $t_head["sno"]["wd"];
		$subTotalCols[0] += $t_head["sno"]["wd"];
	}
	*/
	$t_head["itemName"] = array("name" => "Item", "wd"=>0 , "al" => "L");

	/*if ($isSkuCol && $isSkuCol == 2)
	{
		$t_head["SKU"] = array("name" => "SKU", "wd"=>13, "al" => "R");
		$tlen += $t_head["SKU"]["wd"];
		$subTotalCols[0] += $t_head["SKU"]["wd"];
	}
	*/
	/*
	if ($hasHSN && $isHsnCol)
	{
		$t_head["itemHS"] = array("name" => "HSN/SAC", "wd"=>9, "al" => "R");
		$tlen += $t_head["itemHS"]["wd"];
		$subTotalCols[0] += $t_head["itemHS"]["wd"];
	}
	*/
	/*foreach($gridFields as $gfVal)
	{
		$t_head[$gfVal["fName"]] = array("name" => $gfVal["fName"], "wd"=>8, "al" => "L");
		$tlen += $t_head[$gfVal["fName"]]["wd"];
		$subTotalCols[0] += $t_head[$gfVal["fName"]]["wd"];
	}
	*/
	if(!empty($isqty))
	{
		$t_head["qty"] = array("name" => "Qty", "wd"=>9, "al" => "R");
		$tlen += $t_head["qty"]["wd"];
		$subTotalCols[1] += $t_head["qty"]["wd"];
	}

	if(!empty($price))
	{
		$t_head["rate"] = array("name" => "Rate(".$currencyCode.")", "wd"=>10, "al" => "R");
		$tlen += $t_head["rate"]["wd"];
		$subTotalCols[2] += $t_head["rate"]["wd"] ? $t_head["rate"]["wd"] : 0;
	}
	
	
	// Discount
	/*if($hasDiscount)
	{
		$t_head["discAmount"] = array("name" => "Dis(".$currencyCode.")", "wd"=>10 , "al" => "R");
		$tlen += $t_head["discAmount"]["wd"];
		$subTotalCols[2] += $t_head["discAmount"]["wd"];
	}
	*/
	/*if ($showTax && $isTaxDetailCol)
	{
		$t_head["taxName"] = array("name" => "Tax", "wd"=>8, "al" => "L");
		$tlen += $t_head["taxName"]["wd"];
		$subTotalCols[3] += $t_head["taxName"]["wd"];
	}
	*/
	$t_head["taxableAmount"] = array("name" => "Amt(".$currencyCode.")", "wd"=>12, "al" => "R");
	$tlen += $t_head["taxableAmount"]["wd"];
	$subTotalCols[3] += $t_head["taxableAmount"]["wd"];

	$t_head["itemName"]["wd"] = $CharLen - $tlen;
	$subTotalCols[0] += $t_head["itemName"]["wd"];

	$i=0;
	$t_body=array();
	$attrWid = $CharLen - (!empty($t_head["sno"]["wd"]) ? $t_head["sno"]["wd"] : 0)  - $t_head["taxableAmount"]["wd"];

	foreach($details as $key=>$row)
	{
		if(!empty($row['itemType']) && $row['itemType'] == 'S' && $row['unit'] == ''){
						$row["qty"] = "";
						$row["rate"] = "";
						$row["rateWithTax"] = "";
						$row["unit"] = "";
		} 
		// For Testing
		// $row["itemName"] = substr($row["itemName"], 0, 7);
		//display printname if given
		if(!empty($row['printName']) && trim($row['printName'])){
			$row['itemName'] =  trim($row['printName']);
		}
		if ($isSkuCol && $isSkuCol == 1)
		{
			$row["itemName"] = $row["SKU"] . " - " . $row["itemName"];
		}
		if ((!empty($isItemDesc) && !empty($row["itemDesc"])) || !empty($row["attrs"])){
		// Wrap item name to next line.
		//$row["itemName"] = substr($row["itemName"], 0, $t_head["itemName"]["wd"]) . PHP_EOL . wordwrap(substr($row["itemName"], $t_head["itemName"]["wd"]-1), $attrWid, PHP_EOL, true);
		}
		if (!empty($isItemDesc) && !empty($row["itemDesc"]))
		{
			$row["itemName"] .= PHP_EOL . str_replace("<br/>", PHP_EOL, $row["itemDesc"]);
		}

		if (!empty($row["attrs"]))
		{
			$row["itemName"] .=  PHP_EOL . str_replace("<br/>", PHP_EOL, $row["attrs"]);
		}

		/*foreach($gridFields as $gfVal)
		{
			if (!empty($gfVal["fValue"]) && !empty($gfVal["fValue"][$row["id"]]))
			{
				$row[$gfVal["fName"]] = $gfVal["fValue"][$row["id"]];
			}
		}
		*/
		if(!empty($row['qty']) && $details[0]['unit'] == $row['unit'])
		{
			$totQty += floatval($row["qty"]);
		}

		$row["qty"] = $row["qty"] > 0 ? floatval($row["qty"]) . " ".(!empty($units) ? $row["unit"]: "") : "";
		$row["rate"] = formatAmount($row["rate"], $currencyCode, false, true,$rateFraction);
		$row["discAmount"] = ($row["discAmount"] > 0) ? formatAmount($row["discAmount"], $currencyCode, false, true,$currFraction) : "-";
		$row["excDiscAmount"] = (!empty($row["excDiscAmount"]) && $row["excDiscAmount"] > 0) ? formatAmount($row["excDiscAmount"], $expCurrencyCode, false, true,$currFraction) : "-";

		if ($includeTax)
		{
			$row["taxableAmount"] = formatAmount($row["itemTotal"], $currencyCode, false, true,$currFraction);
		}
		else
		{
			$row["taxableAmount"] = formatAmount($row["taxableAmount"], $currencyCode, false, true,$currFraction);
		}
		if(!empty($row["excTaxableAmount"])){
		$row["excTaxableAmount"] = formatAmount($row["excTaxableAmount"], $expCurrencyCode, false, true,$currFraction);
		}
		if ($row["discPercentage"])
		{
			$row["discPercentage"] = round($row["discPercentage"], 2);
			$row["discPercentage"] = $row["discPercentage"] . "%";
		}

		$data = "";
		$data1 = "";
		$row["sno"] = ++$i;
		$itemName = array();

		foreach ($t_head as $thk => $thv)
		{
			//////print_R($row[$thk]);exit;
			if ($thk == "qty")
			{
				$data .= justify($row[$thk], $thv["al"], $thv["wd"]);
				// $data .= justify($row[$thk], $thv["al"], $thv["wd"]+$t_head["itemName"]["wd"]);
			}
			/*
			else if ($thk == "itemName")
			{
				$itemName = $row["itemName"];
				$data1 = justify($itemName, $thv["al"], 38);
			}
			*/
			else if ($thk == "rate")
			{		
				if(empty($t_head["qty"]["wd"]))
				{
					 $thv["wd"] =  $thv["wd"] + $t_head["itemName"]["wd"];
				}
				$data .= justify($row[$thk], $thv["al"], $thv["wd"]);
			}
			else
			{
				$data .= justify(!empty($row[$thk]) ? $row[$thk] : "", $thv["al"], $thv["wd"]);
			}
		}
		// $t_body[] = $data1;
		$t_body[] .= $data;
		/*if (count($itemName) > 1 && !empty($itemName[1]))
		{
			$sNoSpace = "";
			if (!empty($t_head["sno"]) && !empty($t_head["sno"]["wd"]))
			{
				$sNoSpace = str_repeat(" ", $t_head["sno"]["wd"]);
			}

			$thv = $t_head["itemName"];
			$attrs = $itemName;
			unset($attrs[0]);
			$isSingline = false;
			if ($isSingline)
			{
				$attrs = str_replace(" : ", ":", implode("; ", $attrs));
				$attrs = explode(PHP_EOL, wordwrap($attrs, $attrWid));
				foreach($attrs as $attr)
				{
					$t_body[] = $sNoSpace . justify(trim($attr), "L", $attrWid);
				}
			}
			else
			{
				$attrs = implode(PHP_EOL, $attrs);
				$attrs = explode(PHP_EOL, wordwrap($attrs, $attrWid));
				foreach($attrs as $attr)
				{
//					$attr = explode(PHP_EOL, wordwrap($attr, $attrWid));
					$t_body[] = $sNoSpace . justify(trim($attr), "L", $attrWid);
				}
			}

			$t_body[] = $sNoSpace;
		}*/
	}

	$row_w3 = array();

	$line = "";
	foreach($t_head as $key=>$val)
	{
		$line .= justify($val["name"], $val["al"], $val["wd"]); 
	}

	$lines[] = $line;
	$lines[] = EscPos::DrawLine();

	$col = array($CharLen - $subTotalCols[3], $subTotalCols[3]);

	$lines = array_merge($lines, $t_body); 

// Details End
	$lines2 = array();
	$lines2[] = EscPos::DrawLine();
	if (!empty($totQty)&& !empty($isqty))
	{
		$taxableAmount = formatAmount($taxableAmount, $currencyCode, false, true,$currFraction);
		
		$lines2[] = justify( "Total", "L", $subTotalCols[0]+1) . justify($totQty . " " .(!empty($units) ?  $details[0]['unit'] : ""), "R", $subTotalCols[1]-1) . justify($taxableAmount, "R", ($subTotalCols[2] ? $subTotalCols[2] : 0) + $subTotalCols[3]);
	}
	else
	{
		$lines2[] = justify("Total", "R", $col[0]) . justify($taxableAmount, "R", $col[1]);
	}

	if (!empty($tax))
	{
		if ($showTaxBreakup)
		{
			$lines2[] = EscPos::DrawLine();

			// Tax to be paid on Reverse Charge
			$tcnt = count($tax);
			$i=1;
			$line = "";
			foreach ($tax as $key => $tax_item)
			{				
				$line .= justify($tax_item["taxName"]." ".$tax_item["taxRate"]. ($tax_item["taxCalc"] == "Q" ? "/Unit" : "%")  . " on ".(empty($tax_item["taxableAmt"]) ? "" : formatAmount($tax_item["taxableAmt"], $currencyCode, "", true,$currFraction)),"R",$col[0]);
				$line .= justify(formatAmount($tax_item["taxValue"], $currencyCode, false, true,$currFraction), "R", $col[1]);
				$lines2[] = $line;

				if($i < $tcnt)
				{
					$line = "";
				}
				$i++;
			}
		}
		$lines2[] = EscPos::DrawLine();
	}

	// dot_print
	$totAmount = formatAmount($totAmount, $currencyCode, false, true,$currFraction);
	$amt_str = explode(PHP_EOL, wordwrap($currencyCode . " " . $amt_str . " only", $col[0] - 6));

	$line = justify("Grand Total", "R", $col[0]);
	$line .= EscPos::Bold(justify($totAmount, "R", $col[1]));
	$lines2[] = $line;
	/*if (count($amt_str) > 1)
	{
		for ($i=1; $i < count($amt_str); $i++)
		{
			$lines2[] = justify($amt_str[$i], "L", $col[0] - 6);
		}
	}*/
	//echo dot_print($currencyCode . " " . $amt_str . " only","L");
	 //echo nl("-");
}

$cashtxt = "Cash :";
$cashtentxt = "Cash tendered :";
$balancetxt = "Balance :";
$showreceivedAmt = false;
$showbalance = false;
if(!empty($recAmt) && ($recAmt - 0) > 0)
{
		$showreceivedAmt = true;
}
if(!empty($balAmt) && ($balAmt - 0) > 0)
{
	$showbalance = true;
}
if($showreceivedAmt)
{
	$lines2[] = EscPos::DrawLine();
	$splitLength = $CharLen/2;
	$line = justify($cashtxt, "L", $splitLength);
	$line .= justify("".$totAmount,"R" ,$splitLength);
	$line1 = justify($cashtentxt,"L",$splitLength);
	$line1 .= justify("".$recAmt,"R",$splitLength);
	if($showbalance)
	{
		$line2 = justify($balancetxt,"L",$splitLength );
		$line2 .= justify("".$balAmt,"R",$splitLength );
	}
	$lines2[] = $line;
	$lines2[] = $line1;
	if($showbalance)
	{
		$lines2[] = $line2;
	}
}

if($tType != "PI" && !empty($isBankDetail) && !empty($bankAccId) && !empty($accType))
{
	$lines2[] = EscPos::DrawLine();

	$line = array(
		"A/C No: " . $accNumber,
		"IFSC Code: " . $ifscRouteCode,
		$bankName,
		$branchName
	);

	if ($isExport)
	{
		if ($swiftCode)
		{
			$line[] = "Swift Code: " . $swiftCode;
		}

		if ($adCode)
		{
			$line[] = "AD Code: " . $adCode;
		}
	}

	$lines2 = array_merge($lines2, explode(PHP_EOL, wordwrap("Our Bank Details:- " . implode(", ", $line), $CharLen, PHP_EOL)));
}

if($notes)
{
	$lines2[] = EscPos::DrawLine();
	$lines2[] = justify(strip_tags($notes), "L");
}
$lines2[] = EscPos::DrawLine();
$lines2[] = justify("E & OE", "R", $CharLen);

// Signature
$line = "";
if (!empty($isCustSign))
{
	$line = "Customer Signature";
	// $line1 =  justify($cust[1] ? $cust[1] : "", "L", 19);
}

if ($tType != "PI")
{
	// $line .= justify("Authorized Signature", "R", $CharLen - strlen($line));
	$line .= justify("For", "R", $CharLen - strlen($line));
	// $line .= justify(trim(strip_tags($company["name"])), "R", $CharLen);
}

if ($line)
{
	$lines2[] = $line;
	$lines2[] = justify(trim(strip_tags($company["name"])), "R", $CharLen);
}

$classCodes = array(
	"EXPWOP" => lang('EXPWOP'),
	"EXPWP" => lang('EXPWP'),
	"SEZWP" => lang('SEZWP'),
	"SEZWOP" => lang('SEZWOP')
);

if (!$isQuote && !empty($classCode) && !empty($classCodes[$classCode]))
{
	//$lines2[] = justify($classCodes[$classCode],"C", $CharLen);
	// echo justify($classCodes[$classCode],"C") . EscPos::DrawLine();
}

if($tType == "SI" && (empty($classCode) || empty($classCodes[$classCode])) && $isComposition)
{
	//$lines2[] = justify("COMPOSITION TAXABLE PERSON, NOT ELIGIBLE TO COLLECT TAX ON SUPPLIES", "C", $CharLen); 
}
/*
if (!empty($topMargin))
{
	echo EscPos::Feed($topMargin, true);
}
*/

if (!empty($fontSize) && $fontSize == 2)
{
	$lines = preg_filter('/^/', _FNTA, $lines);
	$lines2 = preg_filter('/^/', _FNTA, $lines2);
}
echo EscPos::init();
echo implode(PHP_EOL, $lines) . PHP_EOL;
$totLines = count($lines) + count($lines2);
if (!empty($min_lines) && $totLines < $min_lines)
{
	echo str_repeat(PHP_EOL, $min_lines - $totLines);
}
echo implode(PHP_EOL, $lines2);
if (!empty($fontSize) && $fontSize == 2)
{
	echo _FNTNORMAL;
}

/*
if (!empty($bottomMargin))
{
	echo EscPos::Feed($bottomMargin);
}
*/

// exit;

