<?php
use Illuminate\Database\Capsule\Manager as Capsule;
use WGS\CLIENTXTEMPLATE\CLIENTX as CLASS_CLIENTX_INVOICE;
$addonActivate = false;
$addonPath = ROOTDIR.'/modules/addons/clientx';
if (file_exists($addonPath. '/classes/class.php')) {
	require_once $addonPath . '/classes/class.php';
	$getLicenseDetail = Capsule::table('tbladdonmodules')->where('setting', 'license_key')->where('module', 'clientx')->first();
	if (!empty($getLicenseDetail)) {
	    $CLIENTX = new CLASS_CLIENTX_INVOICE();
	    $license = $CLIENTX->wgs_clientx_get_license($getLicenseDetail->value);
	    $status = trim($license['status']);
	    if ($status == 'Active')
		$addonActivate = true;
	}
}
if (!empty($addonActivate)) {
        $getSetting = Capsule::table('mod_clientx_setting')->get();
        $settings = [];
        foreach ($getSetting as $key => $setting) {
            $settings[$setting->setting] = $setting->value;
        }
	$width = 75;
	$heights = 25;
	if(!empty($settings['invoice_logo_width'])){
	  $width = str_replace("px","",$settings['invoice_logo_width']);
	}
	if(!empty($settings['invoice_logo_height'])){
	  $heights = str_replace("px","",$settings['invoice_logo_height']);
	}
	if(!empty($settings['invoice_logo'])){
		$imageLink = $settings['invoice_logo'];
		$htmlImg = '<img src="'.$imageLink.'"  width="'.$width.'" height="'.$heights.'">';
		$pdf->writeHTML($htmlImg, true, 0, true, 0);
       }else{
		$logoFilename = 'placeholder.png';
		if (file_exists(ROOTDIR . '/assets/img/logo.png')) {
		$logoFilename = 'logo.png';
		} elseif (file_exists(ROOTDIR . '/assets/img/logo.jpg')) {
		$logoFilename = 'logo.jpg';
		}
		if($width == 75 && $heights == 25){
			$pdf->Image(ROOTDIR . '/assets/img/' . $logoFilename, 20, 25, 75);
		}else{
			$imageLinkE = ROOTDIR . '/assets/img/' . $logoFilename;
			$htmlImgE = '<img src="'.$imageLinkE.'"  width="'.$width.'" height="'.$heights.'">';
			$pdf->writeHTML($htmlImgE, true, 0, true, 0);
		}
       }
}else{
	# Logo
	if (file_exists(ROOTDIR.'/assets/img/logo.png')) $pdf->Image(ROOTDIR.'/assets/img/logo.png', 20, 25, 75);
	elseif (file_exists(ROOTDIR.'/assets/img/logo.jpg')) $pdf->Image(ROOTDIR.'/assets/img/logo.jpg', 20, 25, 75);
	else $pdf->Image(ROOTDIR.'/assets/img/placeholder.png', 20, 25, 75);
}


if(file_exists(dirname(dirname(__DIR__))).'/modules/addons/gsttax/classes/class.php'){
require_once dirname(dirname(__DIR__)).'/modules/addons/gsttax/classes/class.php';

$GST_TAX = new GST_TAX();

$gstIn = $GST_TAX->getAddonModuleSetting('gst_in');
$oldTaxNumber = $GST_TAX->getAddonModuleSetting('old_tax_number');
$sacCode = $GST_TAX->getAddonModuleSetting('hsn_code');
$count = $GST_TAX->getAddonModuleSetting();
$licensekey = $GST_TAX->getAddonModuleSetting('license_key');

$licenseStatus = $GST_TAX->license($licensekey);

if(isset($_GET['id']) && !empty($_GET['id'])){
$quoteId = $_GET['id'];
}else{
$quoteId = $quotenumber;
}

if(isset($quoteId) && !empty($quoteId)){
if(!empty($quoteId)){
$data = Capsule::table('tblquotes')->where('id', $quoteId)->get();

if((float) $data[0]->tax1 > 0 || (float) $data[0]->tax2 > 0){
$totalTaxInt = (float) $data[0]->tax1 + (float) $data[0]->tax2;
$currenyIdQuery = Capsule::table('tblcurrencies')->where('code','INR')->first();
$currencyData['id'] = $currenyIdQuery->id;
if($data[0]->userid){
$clientCountry = Capsule::table('tblclients')->where('id', $data[0]->userid)->first();
if (!empty($clientCountry->currency))
$currencyData['id'] = $clientCountry->currency;
}else
$currencyData['id'] = $data[0]->currency;

$totalTax = formatCurrency($totalTaxInt, $currencyData['id']);
}
$quoteData = (array) $data[0];

$quoteDate = date("d-m-Y", strtotime($quoteData['datecreated']));
if(strtotime($quoteDate) <= strtotime('30-06-2017')){
$taxlabel1 = $GST_TAX->getAddonModuleSetting('taxlabel1');
$taxlabel2 = $GST_TAX->getAddonModuleSetting('taxlabel2');
}else{
if((float) $data[0]->tax1 > 0 && (float) $data[0]->tax2 > 0){
$taxlevel1['name'] = $GST_TAX->gstGetTaxName('9.00', 1);
$taxlevel2['name'] = $GST_TAX->gstGetTaxName('9.00', 2);
$taxlevel1['rate'] = '9.00';
$taxlevel2['rate'] = '9.00';
}elseif((float) $data[0]->tax1 > 0 && (float) $data[0]->tax2 == 0){
$taxlevel1['name'] = $GST_TAX->gstGetTaxName('18.00', 1);
$taxlevel1['rate'] = '18.00';
$taxlevel2['rate'] = '0.00';
$taxlevel2['name'] = '';
}
}
}
}
}

$currenyIdQuery = Capsule::table('tblcurrencies')->where('default','1')->first();
$currencyId = $currenyIdQuery->id;
if($data[0]->userid){
$clientCountry = Capsule::table('tblclients')->where('id', $data[0]->userid)->first();
$country = $clientCountry->country;
if (!empty($clientCountry->currency))
$currencyId = $clientCountry->currency;
}else{
$country = $data[0]->country;
$currencyId = $data[0]->currency;
}
if($currencyId)
$getCurrencyCode = $GST_TAX->gstGetCurrencyCode($currencyId);

/*if ($country == 'IN') {
if($count > 0 && file_exists(dirname(dirname(__DIR__)).'/modules/addons/gsttax/gsttax.php') && $licenseStatus['status'] == 'Active' && strtotime($quoteDate) > strtotime('30-06-2017')){

$pdf->SetFont($pdfFont, '', 15);
$pdf->SetXY(12,12);
$pdf->Cell(0, 15, 'QUOTE', 0, false, 'C', 0, '', 0, false, 'M', 'T');
}
}*/
# Company Details
$pdf->SetFont($pdfFont,'',13);
$pdf->Cell(0,6,trim($companyaddress[0]),0,1,'R');
$pdf->SetFont($pdfFont,'',9);
for ( $i = 1; $i <= ((count($companyaddress)>6) ? count($companyaddress) : 6); $i += 1) {
$pdf->Cell(0,4,trim($companyaddress[$i]),0,1,'R');
}

$addonActive = false;
$oldVat = false;

if ($country == 'IN') {
if($count > 0 && file_exists(dirname(dirname(__DIR__)).'/modules/addons/gsttax/gsttax.php') && $licenseStatus['status'] == 'Active' && strtotime($quoteDate) > strtotime('30-06-2017')){
$addonActive = true;

$totalAmountInWords = $GST_TAX->GstNumberToWords($quoteData['total']);
$sign_image = $GST_TAX->gstGetSign();

$pdf->Ln(2);
$pdf->SetFont($pdfFont, '', 10);
$pdf->Cell(180, 6, 'GSTIN' . ': ' . $gstIn, 0, 1, 'R');
$pdf->Ln(10);
/*$pdf->Ln(5);
$pdf->SetXY(20, 55);
$pdf->SetFillColor(239);
$pdf->SetFont($pdfFont, '', 10);
$pdf->Cell(52, 6, 'GSTIN' . ': ' . $gstIn, 10, 1, 'L', '1');
$pdf->Ln(10);*/
}elseif ($count > 0 && file_exists(dirname(dirname(__DIR__)).'/modules/addons/gsttax/gsttax.php') && $licenseStatus['status'] == 'Active' && strtotime($quoteDate) <= strtotime('30-06-2017')) {
$addonActive = true;
$oldVat = true;

if($oldTaxNumber){
$pdf->Ln(2);
$pdf->SetFont($pdfFont, '', 10);
$pdf->Cell(180, 6, 'Service tax number' . ': ' . $oldTaxNumber, 0, 1, 'R');
$pdf->Ln(10);
/*$pdf->Ln(5);
$pdf->SetXY(15, 55);
$pdf->SetFillColor(239);
$pdf->SetFont($pdfFont, '', 10);
$pdf->Cell(60, 6, 'Service tax number' . ': ' . $oldTaxNumber, 10, 1, 'L', '1');
$pdf->Ln(10);*/
}else{
$pdf->Ln(5);
}
}
}

$pdf->SetFont($pdfFont,'B',10);
$pdf->SetX($pdf->GetX()+10);
$pdf->Cell(20,6,$_LANG['quotenumber'],1,0,'C');
$pdf->Cell(70,6,$_LANG['quotesubject'],1,0,'C');
$pdf->Cell(35,6,$_LANG['quotedatecreated'],1,0,'C');
$pdf->Cell(35,6,$_LANG['quotevaliduntil'],1,1,'C');

$pdf->SetFont($pdfFont,'',9);
$pdf->SetX($pdf->GetX()+10);
$rowcount = $pdf->getNumLines($subject, 60);
$height = $rowcount * 5;
$pdf->MultiCell(20,$height,$quotenumber,1,'C',0,0);
$pdf->MultiCell(70,$height,$subject,1,'C',0,0);
$pdf->MultiCell(35,$height,$datecreated,1,'C',0,0);
$pdf->MultiCell(35,$height,$validuntil,1,'C',0,1);

$pdf->Ln(10);

$pdf->SetFont($pdfFont,'B',10);
$pdf->Cell(0,4,$_LANG['quoterecipient'],0,1);
$pdf->SetFont($pdfFont,'',9);
if ($clientsdetails["companyname"]) {
$pdf->Cell(0,4,$clientsdetails["companyname"],0,1,'L');
$pdf->Cell(0,4,$_LANG["invoicesattn"].": ".$clientsdetails["firstname"]." ".$clientsdetails["lastname"],0,1,'L');
} else {
$pdf->Cell(0,4,$clientsdetails["firstname"]." ".$clientsdetails["lastname"],0,1,'L');
}
$pdf->Cell(0,4,$clientsdetails["address1"],0,1,'L');
if ($clientsdetails["address2"]) {
$pdf->Cell(0,4,$clientsdetails["address2"],0,1,'L');
}
$pdf->Cell(0,4,$clientsdetails["city"].', '.$clientsdetails["state"].', '.$clientsdetails["postcode"],0,1,'L');
$pdf->Cell(0,4,$clientsdetails["country"],0,1,'L');

$pdf->Ln(10);

if ($proposal) {
$pdf->SetFont($pdfFont,'',9);
$pdf->MultiCell(170,5,$proposal);
$pdf->Ln(10);
}

$pdf->SetDrawColor(200);
$pdf->SetFillColor(239);

$pdf->SetFont($pdfFont,'',8);

if(!empty($addonActive) && empty($oldVat)){
$tblhtml = '<table width="100%" bgcolor="#ccc" cellspacing="2" cellpadding="3" border="">
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td width="5%">'.$_LANG['quoteqty'].'</td>
<td width="45%">'.$_LANG['quotedesc'].'</td>
<td width="15%">'.$_LANG['quoteunitprice'].'</td>
<td width="15%">'.$_LANG['quotediscount'].'</td>
<td width="20%">'.$_LANG['quotelinetotal'].'</td>
</tr> ';
foreach ($lineitems as $key => $item) {                             
$tblhtml .= '<tr bgcolor="#fff">

<td align="left">'.$item['qty'].'</td>
<td align="left">'.nl2br($item['description']).'<br /></td>
<td align="left">'.$item['unitprice'].'</td>
<td align="left">'.$item['discount'].'</td>
<td align="left">'.$item['total'].'</td>
</tr>  ';                              
}
$tblhtml .= '<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td align="right" width="30%">'.$_LANG['invoicessubtotal'].'</td>
<td colspan="3" width="50%"></td>
<td align="left" width="20%">'.$subtotal.'</td>
</tr>
<tr bgcolor="#fff">
<td align="right" width="30%"><strong>GST</strong></td>
<td colspan="3" width="50%">
<table width="100%" bgcolor="#ccc" cellspacing="2" cellpadding="3" border="" bordercolor="#ccc">
<tr bgcolor="#efefef">
<td width="33.3%"><strong>CGST';
if ($taxlevel1['rate'] && $taxlevel1['name'] == 'CGST') {
$tblhtml .= ' ('.$taxlevel1['rate'].'%)';   
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</strong></td>
<td width="33.3%"><strong>SGST';
if ($taxlevel2['rate'] && $taxlevel2['name'] ==  'SGST') {
$tblhtml .= ' ('.$taxlevel2['rate'].'%)';  
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</strong></td>
<td width="33.3%"><strong>IGST';
if ($taxlevel1['rate'] && $taxlevel1['name'] ==  'IGST') {
$tblhtml .= ' ('.$taxlevel1['rate'].'%)';   
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</strong></td>
</tr>
<tr bgcolor="#fff">
<td width="33.3%">';
if ($taxlevel1['rate'] && $taxlevel1['name'] == 'CGST') {
$tblhtml .= $tax1;   
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</td>
<td width="33.3%">';
if ($taxlevel2['rate'] && $taxlevel2['name'] ==  'SGST') {
$tblhtml .= $tax2;  
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</td>
<td width="33.3%">';
if ($taxlevel1['rate'] && $taxlevel1['name'] ==  'IGST') {
$tblhtml .= $tax1;   
}else{
$tblhtml .= ' ';
}
$tblhtml .= '</td>
</tr>
</table>
</td>
<td width="20%">'.$totalTax.'</td>
</tr>
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td align="right" width="30%">Total Amount Incl. GST :</td>
<td colspan="3" width="50%"></td>
<td align="left">'.$total.'</td>
</tr>';
if($totalAmountInWords && $getCurrencyCode == 'INR'){
$tblhtml .= '<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td align="right" width="30%">Total Amount Incl. GST (in words):</td>
<td  align="right" colspan="4" width="70%">' . $totalAmountInWords . '</td>
</tr>';
}
$tblhtml .= '

</table><br/>';
if(!empty($sign_image)){
$tblhtml .= '<br/><table><tr bgcolor="#fff">
<td colspan="5" align="right">
<img width="70" height="50" src="'.str_replace(' ','', $sign_image).'"><br/>Authorized Signatory
</td>
</tr></table>';
}
//echo $tblhtml;exit;
}else{

$tblhtml = '<table width="100%" bgcolor="#ccc" cellspacing="1" cellpadding="2" border="0">
<tr height="30" bgcolor="#efefef" style="font-weight:bold;text-align:center;">
<td width="5%">'.$_LANG['quoteqty'].'</td>
<td width="45%">'.$_LANG['quotedesc'].'</td>
<td width="15%">'.$_LANG['quoteunitprice'].'</td>
<td width="15%">'.$_LANG['quotediscount'].'</td>
<td width="20%">'.$_LANG['quotelinetotal'].'</td>
</tr>';
foreach ($lineitems AS $item) {

$tblhtml .= '
<tr bgcolor="#fff">
<td align="center">'.$item['qty'].'</td>
<td align="left">'.nl2br($item['description']).'<br /></td>
<td align="center">'.$item['unitprice'].'</td>
<td align="center">'.$item['discount'].'</td>
<td align="center">'.$item['total'].'</td>
</tr>';
}
$tblhtml .= '
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td align="right" colspan="4">'.$_LANG['invoicessubtotal'].'</td>
<td align="center">'.$subtotal.'</td>
</tr>';
if ($taxlevel1['rate']>0){ $tblhtml .= '
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">';
if(!empty($addonActive) && !empty($oldVat))
$tblhtml .= '<td align="right" colspan="4">' . $taxlabel1 . '</td>';
else
$tblhtml .= '<td align="right" colspan="4">'.$taxlevel1['name'].' @ '.$taxlevel1['rate'].'%</td>';
$tblhtml .= '<td align="center">'.$tax1.'</td>
</tr>';
}
if ($taxlevel2['rate']>0){ $tblhtml .= '
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">';
if(!empty($addonActive) && !empty($oldVat))
$tblhtml .= '<td align="right" colspan="4">' . $taxlabel2 . '</td>';
else
$tblhtml .= '<td align="right" colspan="4">'.$taxlevel2['name'].' @ '.$taxlevel2['rate'].'%</td>';
$tblhtml .= '<td align="center">'.$tax2.'</td>
</tr>';
}
$tblhtml .= '
<tr height="30" bgcolor="#efefef" style="font-weight:bold;">
<td align="right" colspan="4">'.$_LANG['invoicestotal'].'</td>
<td align="center">'.$total.'</td>
</tr>
</table>';
}
$pdf->writeHTML($tblhtml, true, false, false, false, '');
if ($notes) {
$pdf->Ln(6);
$pdf->SetFont($pdfFont,'',8);
$pdf->MultiCell(170,5,$_LANG['invoicesnotes'].": $notes");
}
?>
