<?php defined('BASEPATH') OR exit('No direct script access allowed');
$dueDate_text = (!empty($label) && !empty($label['ValidTill'])) ? $label['ValidTill'] :(!empty($dueDate_text)? $dueDate_text : "DueDate") ;
$rel_tNo_text =  (!empty($label) && !empty($label['OrderNo'])) ? $label['OrderNo'] : (!empty($rel_tNo_text) ? $rel_tNo_text : '') ;
$rel_tDate_text =  (!empty($label) && !empty($label['OrderDate'])) ? $label['OrderDate'] : (!empty($rel_tDate_text) ? $rel_tDate_text : '') ;
if(!empty($paper))
{
	$paper = explode(",", $paper); 
}

if(!empty($paper) && !empty($paper[0]) && $paper[0] == '4')
{
	$this->view('export/salinv1_dot_4');
	return;
}
else if (!empty($paper) && !empty($paper[0]) && $paper[0] == 'A5')
{
	$this->view('export/salinv1_dot_a5');
	return;
}

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

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

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

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

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

echo nl();

$lines = array();

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

$row_w1 = array();
$row_w1[0] = floor($CharLen * 60/100);
$row_w1[1] = floor($CharLen * 20/100);
$row_w1[2] = $CharLen - ($row_w1[0] + $row_w1[1]);

$col_1 = array();
$col_1[] = EscPos::Bold(justify(strip_tags($company['name']),'L',$row_w1[0]));

if (!empty($company['address1']))
{
	$company['address1'] = explode(PHP_EOL, wordwrap($company['address1'], $row_w1[0], PHP_EOL));
	foreach($company['address1'] as $addr2)
	{
		$col_1[] = justify(strip_tags($addr2), 'L', $row_w1[0]);
	}
}

if (!empty($company['address2']))
{
	$company['address2'] = explode(PHP_EOL, wordwrap($company['address2'], $row_w1[0], PHP_EOL));
	foreach($company['address2'] as $addr2)
	{
		$col_1[] = justify(strip_tags($addr2), 'L', $row_w1[0]);
	}
}

$col_1[] = justify(strip_tags($company['city'] . (!empty($company['zip']) ? ' - ' . $company['zip'] : '') . ','),'L',$row_w1[0]);
$col_1[] = justify(strip_tags($company['stateName'] . ', ' . $company['country']),'L',$row_w1[0]);

if (!empty($company['phone']))
{
	$col_1[] = justify('Phone : '.strip_tags($company['phone']),'L',$row_w1[0]);
}
if (!empty($company['email']))
{
	$col_1[] = justify(strip_tags($company['email']),'L',$row_w1[0]);
}
if (!empty($company['gstin']))
{
	$col_1[] = justify('GSTIN :'.$company['gstin'],'L',$row_w1[0]);
}
if (!empty($company['addInfo']))
{
	$col_1[] = justify(strip_tags($company['addInfo']), "L", $CharLen);
}

$col_2 = array();
$col_2[] = EscPos::Bold(justify(strip_tags($titleText),'L',$row_w1[1]+$row_w1[2]));
$col_2[] = justify(strip_tags(mytranslang('No',$tNo_text)),'L',$row_w1[1]).EscPos::Bold(justify(':'.strip_tags($tNo),'L',$row_w1[2]));
$col_2[] = justify(strip_tags(mytranslang('Date', $tDate_text)),'L',$row_w1[1]).EscPos::Bold(justify(':'.strip_tags($tDate),'L',$row_w1[2]));
if (!empty($sRepName)&& !empty($issalesrep))
{
	$col_2[] = justify(strip_tags($srep_text),'L',$row_w1[1]).justify(':'.strip_tags($sRepName),'L',$row_w1[2]);
}
if (!empty($sRepMobile)&& !empty($issalesrep))
{
	$col_2[] = justify(strip_tags($srep_mobile_text),'L',$row_w1[1]).justify(':'.strip_tags($sRepMobile),'L',$row_w1[2]);
}
if (!empty($refName))
{
	$col_2[] = justify(strip_tags('ReferredBy'),'L',$row_w1[1]).justify(':'.strip_tags($refName),'L',$row_w1[2]);
}
if (!empty($isprojectname) && !empty($prjName))
{
	$col_2[] = justify(strip_tags('ProjectName'),'L',$row_w1[1]).justify(':'.strip_tags($prjName),'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 ($dueDate && !empty($relNumber))
{
	$col_2[] = justify(strip_tags($rel_tNo_text),'L',$row_w1[1]).justify(':'.strip_tags($relNumber),'L',$row_w1[2]);
}
if (!empty($relDate))
{
	$col_2[] = justify(strip_tags($rel_tDate_text),'L',$row_w1[1]).justify(':'.strip_tags($relDate),'L',$row_w1[2]);
}
if (!empty($ref))
{
	$col_2[] = justify(strip_tags(mylang("Reference")),'L',$row_w1[1]).justify(':'.strip_tags($ref),'L',$row_w1[2]);
}
if ($tType == DELCHALLAN && $classCode && get_company('countryCode')=='IN')
{
	$col_2[] = justify(strip_tags(mylang("ChallanType")),'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++)
{
	echo isset($col_1[$i])?$col_1[$i]:justify('','L',$row_w1[0]);
	echo isset($col_2[$i])?$col_2[$i]:justify('','L',$row_w1[1]+$row_w1[2]);
	echo nl();
}
echo nl('-');
if (!empty($tType!=PURINV) && !empty($tType!=PURCRNOTE) && !empty($tType != PURDBNOTE) && !empty($tType != EXPRETAIL))
{
	$classCodes = array(
		'EXPWOP' => lang('EXPWOP'),
		'EXPWP' => lang('EXPWP'),
		'SEZWP' => lang('SEZWP'),
		'SEZWOP' => lang('SEZWOP')
	);

	if (!$isQuote && !empty($classCode) && !empty($classCodes[$classCode]))
	{
		echo justify($classCodes[$classCode],'C').nl('-');
	}

	if($tType == "SI" && (empty($classCode) || empty($classCodes[$classCode])) && $isComposition)
	{
		echo justify("COMPOSITION TAXABLE PERSON, NOT ELIGIBLE TO COLLECT TAX ON SUPPLIES",'C').nl('-');
	}
	if (
		($tType == "SH" || $tType == "TD" || $tType =="GR" || $tType =="TR") &&
		!empty($contact) &&
		!empty($contact['csType']) &&
		($contact['csType'] == 'B' || $contact['csType'] == 'L')
	) {
		echo justify("Stock Transfer / Branch Transfer - Not for Sale",'C').nl('-');
	}
	$col_1 = $col_2 = $col_3 = array();
	$contact_name = !empty($contact['company']) ? $contact['company'] : (!empty($contact['contactPerson']) ? $contact['contactPerson'] :(!empty($conName) ? $conName : (!empty($contact['name']) ? ($contact['name']) : "")));
	$billing["name"] = !empty($contact_name) ? $contact_name : $conName;
		if(!empty($shipping['name']) && !empty($contact_name))
		{
			//Edited shipping name directly in grid
			if($shipping["name"] != $contact_name)
			{
				$contact_name  = $shipping["name"];
			}
		}

		$shipping["name"] = !empty($contact_name) ? $contact_name : $conName;

		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(!empty($contact['name']) || !empty($conName))
			{				
				$col_1[] = justify(strip_tags(($tType == 'PI') ? mylang("Supplier") : mylang("Issued")),'L',$row_w2[0]+$row_w2[1]);

				if (!empty($contact['name']))
				{
					$col_1[] = justify(strip_tags($contact_name),'L',$row_w2[0]+$row_w2[1]);
				}
				if (!empty($conName))
				{
				  //  $col_1[] = justify(strip_tags($conName),'L',$row_w2[0]+$row_w2[1]);
				}
			}

			if(!$expCurrencyCode)
			{
				if(!empty($conTaxNo))
				{
					$col_1[] = justify(mylang("GSTIN"),'L',$row_w2[0]).justify(':'.$conTaxNo,'L',$row_w2[1]);
				}
				else if(!empty($contact['taxNo']))
				{
					$col_1[] = justify(mylang("GSTIN"),'L',$row_w2[0]).justify(':'.$contact['taxNo'],'L',$row_w2[1]);
				}
				if(!empty($pos) && $tType != EXPRETAIL && $tType != PURINV)
				{
					$col_1[] = justify(mylang("POS"),'L',$row_w2[0]).justify(':'.$pos,'L',$row_w2[1]);
				}
				if($tType==PURINV)
				{
					$col_1[] = justify(mylang("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 = ($isAllServices || $isShipping || $isQuote) ? mylang("BillingAddress") :  mylang("Billing&Shipping Address");			
				if ($tType == 'PO')
				{
					$addr = mylang("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(mylang("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 = mylang("ShippingAddress");

					if ($tType == 'PO')
					{
						$addr = mylang("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(mylang('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++)
			{
				echo isset($col_1[$i])?$col_1[$i]:(($col_1)?justify('','L',$row_w2[0]+$row_w2[1]):'');
				echo isset($col_2[$i])?$col_2[$i]:(($col_2)?justify('','L',$row_w2[2]+$row_w2[3]):'');
				echo isset($col_3[$i])?$col_3[$i]:(($col_3)?justify('','L',$row_w2[4]+$row_w2[5]):'');
				echo nl();
			}
		}
}
echo nl('-');
if (!empty($export_details[0]['value']))
{
	// $this->view($exportDetailsView);
	echo nl('-');
}
if(!empty($fields))
{ 
	// $this->view($custFieldsView);
	$fcnt = count($fields);
	$hasVal = false;

	foreach ($fields as $key => $row)
	{
		// Skip for Invoice Item Grid, Cash Invoice Item Grid
		if ($row['tType'] == 'IG' || $row['tType'] == 'RG')
		{
			continue;
		}
		if ($row['fValue'])
		{
			$hasVal = true;
			echo justify($row['fName'],'L',18).justify($row['fValue'],'L',18);
		}

		if($key%2 && $fcnt>($key+1)) {
			echo nl();
		}
	}
	if ($hasVal)
	{
		echo nl('-');
	}
}

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

	if ($isSlNoCol)
	{
		$t_head['sno'] = array('name' => mylang("SNo"), 'wd'=>4, 'al' => 'C');
		$tlen += $t_head['sno']['wd'];
	}

	$t_head['itemName'] = array('name' => mylang('ItemDescription'), 'wd'=>0 , 'al' => 'L');

	if ($hasHSN  && $isHsnCol)
	{
		$t_head['itemHS'] = array('name' => mylang("HSN/SAC"), 'wd'=>8, 'al' => 'L');
		$tlen += $t_head['itemHS']['wd'];
	}

	if(!empty($isqty))
	{
		$t_head['qty'] = array('name' => mylang("Qty"), 'wd'=>6, 'al' => 'R');
		$tlen += $t_head['qty']['wd'];
	}

	if(!empty($isRate))
	{
		$t_head['rate'] = array('name' => mylang("Rate"), 'wd'=>10, 'al' => 'R');
		$tlen += $t_head['rate']['wd'];
	}

	$totaxamount = true;
	if(empty($isRate) && $tType == 'JO'){
		$hasDiscount = false;
		$isdiscount = false;
		$isTaxDetailCol = false;
		$showTax = false;
		$totaxamount = false;
		$tax = false;
		$issubtotal = false;
	}
	if($tType == 'SH'){
		$totaxamount = (isset($isAmount) && !$isAmount) ? false : true;
		$tax = false;
	}

	// Discount
	if($hasDiscount && !empty($isdiscount))
	{
		if($isdiscount == 1){
		$t_head['discAmount'] = array('name' => mylang("Discount"), 'wd'=>10 , 'al' => 'R');
		$tlen += $t_head['discAmount']['wd'];
		}
		if($isdiscount == 2){
			$t_head['discPercentage'] = array('name' => mylang("Discount"), 'wd'=>10 , 'al' => 'R');
			$tlen += $t_head['discPercentage']['wd'];
		}
	}

	if ($showTax && $isTaxDetailCol)
	{
		$t_head['taxName'] = array('name' =>  mylang("Tax"), 'wd'=>9, 'al' => 'L');
		$tlen += $t_head['taxName']['wd'];
	}

	if ($totaxamount)
	{
		$t_head['taxableAmount'] = array('name' =>  mylang("Amount"), 'wd'=>15, 'al' => 'R');
		$tlen += $t_head['taxableAmount']['wd'];
	}

	$t_head['itemName']['wd'] = $CharLen - $tlen;

	$i = 0;
	$t_body = array();
	foreach($details as $key=>$row)
	{
		if(!empty($row['itemType']) && $row['itemType'] == 'S' && $row['unit'] == ''){
						$row["qty"] = "";
						$row["rate"] = "";
						$row["rateWithTax"] = "";
						$row["unit"] = "";
		} 
		if(!empty($isRate) && $tType == 'JO'){
			$row["rate"] = "";
			$row['taxName'] = "";
			$row["discAmount"] = "";
			$row["excDiscAmount"] = "";
			$row["excTaxableAmount"] = "";
			// $row['taxableAmount'] = '';
		}
		
		//display printname if given
		if(!empty($row['printName']) && trim($row['printName']))
		{
			$row['itemName'] =  trim($row['printName']);
		}

		$row['itemHS'] = ' '.$row['itemHS']; 
		$row['taxName'] = '  '.$row['taxName']; 
		$row['qty'] = $row['qty'] > 0 ? floatval($row['qty']) : '';
		$row['rate'] = formatAmount($row['rate'], $currencyCode, false, true,$rateFraction);
		$row['discAmount'] = formatAmount($row['discAmount'], $currencyCode, false, true,$currFraction);
		$row['excDiscAmount'] = !empty($row['excDiscAmount']) ? formatAmount($row['excDiscAmount'], $expCurrencyCode, false, true,$currFraction): '';
		$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 = '';
		$row['sno'] = ++$i . ' ';
		foreach ($t_head as $thk => $thv)
		{
			$data .= justify($row[$thk],$thv['al'],$thv['wd']);
		}

		$t_body[] = $data . nl();
	}

	$row_w3 = array();

	foreach($t_head as $val)
	{
		echo justify($val['name'], $val['al'], $val['wd']);
	}

	echo nl('-');

	$col = ((empty($isRate) && $tType == 'JO') || $tType == 'SH') ? '' : array($CharLen - $t_head['taxableAmount']['wd'], $t_head['taxableAmount']['wd']) ;
	foreach($t_body as $val)
	{
		echo $val;
	}

	if(!empty($issubtotal))
	{
		echo nl('-');
		echo justify(($includeTax ? '(Tax Included) ' : '') . mylang('SubTotal'), 'R', $col[0]);
		$taxableAmount =formatAmount($taxableAmount, $currencyCode, "-", true, $currFraction);
		echo justify($taxableAmount, 'R', $col[1]);
		echo nl('-');
	}

	if (!empty($tax))
	{
		nl('-');
		if ($showTaxBreakup)
		{
			// Tax to be paid on Reverse Charge
			$tcnt = count($tax);
			$i = 1;
			foreach ($tax as $key => $tax_item)
			{
				echo justify($tax_item['taxTypeCode'] . ' ' . $tax_item['taxRate'] . ' % on ' . (empty($tax_item['taxableAmt']) ? '' : formatAmount($tax_item['taxableAmt'], $currencyCode, '', true,$currFraction)),'R',$col[0]);
				echo justify(formatAmount($tax_item['taxValue'], $currencyCode, false, true,$currFraction),'R',$col[1]);

				if ($i<$tcnt)
				{
					echo nl();
				}

				$i++;
			}
		}

		echo nl('-');
	}

	if((!empty($isRate) && $tType != 'JO') && ($tType != 'SH')){
		echo EscPos::Bold(justify('Total', 'R', $col[0]));
		$totAmount = formatAmount($totAmount, $currencyCode, "-", true, $currFraction);
		echo EscPos::Bold(justify($totAmount, 'R', $col[1]));
	}

	if(!empty($amtword))
	{
		echo nl('-');
		echo justify('Amount (in words) :','L');
		echo nl();
		echo dot_print($currencyCode . ' ' . $amt_str . " only", 'L');
		echo nl();
	}
}

if($tType != 'PI' && !empty($isBankDetail) && !empty($bankAccId) && !empty($accType))
{
	$row_w1= array(10,26,10,26);
	echo nl();
	echo justify('Our Bank Details','L') . nl();
   // echo  justify('A/c No','L',$row_w1[0]).justify(':'.$accNumber,'L',$row_w1[1]).justify('IFSC Code','L',$row_w1[2]).justify(':'.$ifscRouteCode,'L',$row_w1[2]).nl();
	echo  justify('A/c No','L',$row_w1[0]).justify(':'.$accNumber,'L',$row_w1[1]).nl();
	echo  justify('IFSC Code','L',$row_w1[2]).justify(':'.$ifscRouteCode,'L',$row_w1[2]).nl();
	echo  justify($bankName.','.$branchName,'L',$row_w1[0]+$row_w1[1]);
	if ($isExport)
	{
		if ($swiftCode)
		{
			echo justify('Swift Code', 'L', $row_w1[1]) . justify(':' . $swiftCode, 'L', $row_w1[2]);
		}

		if ($adCode)
		{
			echo justify('AD Code', 'L', $row_w1[1]) . justify(':' . $adCode, 'L', $row_w1[2]);
		}
	}
}

if($notes)
{
	echo nl('-');
	echo justify(strip_tags($notes),'L');
}

echo nl('-');
echo justify('E & O.E', 'R', $CharLen) . nl() . nl();
$signRowLen = $CharLen;
if (!empty($isCustSign))
{
	$signRowLen -= floor($CharLen/2);
	echo justify(mylang('CustomerSignature'), 'L', $CharLen - $signRowLen);
}

if ($tType != 'PI')
{
	echo justify(mylang('AuthorizedSignature'), 'R', $signRowLen);
}

