<?php
require_once  dirname(__DIR__, 1) . '/pdf/db_connection.php';
require_once  dirname(__DIR__, 1) . '/fpdf/fpdf.php';
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ( !$conn ) {
	die( 'Not Connected: ' . mysql_error());
}
$invoice = $table_prefix . 'cip_member_invoice';
$account = $table_prefix . 'sm_accounts_management';
$site = get_site_url();
$header_img = $site."/wp-content/uploads/2021/10/Asset-10.png";
$paid_img = $site."/wp-content/plugins/cip-helper/images/Asset_Paid.png";
define('EURO',chr(128));
class PDF extends FPDF{

	function SetCellMargin($margin){
		// Set cell margin
		$this->cMargin = $margin;
	}
}
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','B',15);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetLeftMargin(12);

if((isset($_GET['id'])) || (isset($_GET['key']))){
	$id = $_GET['id'];
	$key = $_GET['key'];
	$email= ( !empty( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if ($id){
		
		if( isset( $_GET['paid'] ) && $_GET['paid'] == 1 ){
			$type = "Invoice";
		}
		
		if( current_user_can('supportagent') ){
			$sel_invoice = "SELECT * FROM $invoice WHERE id='$id'";
		}else{			
			$sel_invoice = "SELECT * FROM $invoice WHERE id='$id' AND Email='$email'";
		}
	}else{
		$sel_invoice = "SELECT * FROM $invoice WHERE UniqueKey=$key";
	}
	
	$result = mysqli_query($conn, $sel_invoice);
	$count_rows = mysqli_num_rows($result);
	if($count_rows){
		while($row = mysqli_fetch_assoc($result)){

			if( strtoupper( $row['token'] ) == 'CSR25' ){
				$header_img = $site."/wp-content/plugins/cip-helper/images/csr-25-blue-invoice.png";
			}
			$pdf->Image($header_img,12,18,45);

			$status = $row['Status'];

			$inclusiveUnit = ( !empty( $row['inclusiveUnit'] ) ) ? $row['inclusiveUnit'] : 8;
			if(strpos($row['Date'], '2021') !== false){
				$inclusiveUnit = 10;
			}
			if( $row['ProformaInvoiceNumber'] <= 1318 ){
				$csr_inc = csr_to_two_decimal( $row['Kgs'] * $inclusiveUnit );
			}else{				
				$csr_inc = cip_convert_csr_by_price_pdf( $row['ProductPrice'], $inclusiveUnit );
			}
			
			
	
			$Package = $row['Package'];
			$InvoiceTxt = 'Invoice #';
			$DateTxt = 'Date:';
			$ReferenceTxt = 'Reference:';
			$PurchaseOrderTxt = 'Purchase Order';
			$VATNumberTxt = 'VAT Number:';
			$SupplierTxt = 'Supplier';
			$SupporterTxt = 'Supporter';
			$CSRServicesEuropeOUTxt = 'CSR Services Europe OU';
			$DescriptionTxt = 'Description';
			$PlasticNeutralitypackageTxt = 'Plastic Neutrality package';
			$InclusiveTxt = 'Receipted '.$row['token'].':';
			$InclusiveAmountTxt = $csr_inc .' '.$row['token'];
			$PlasticCreditTxt ='Plastic Neutrality package:';
			$PlasticCreditAmountTxt = $row['Kgs']. ' kg ' .$Package;
			$PoNotesTxt = "This purchase order is valid for 30 days. If purchase order is not paid for and/or redeemed in specified time, Company can refuse to fulfil the order, in full or partially, if conditions have changed and cannot be met.";
			
			$PriceTxt = 'Price ('.EURO.')';
			$VatPercentageTxt = 'VAT %:';
			$VatTxt = 'VAT:';
			$TotalPayableTxt = 'Total Payable ('.EURO.')';
			$BankDetailsTxt = 'Bank Details';
			$AccountHolderTxt = 'Account Holder:';
			$IBANTxt = 'IBAN:';
			$BICTxt = 'BIC:';
			$BankNameTxt = 'Bank Name:';
			$BankAddressTxt = 'Bank Address:';
			$RegisteredInTxt = 'CSR Services Europe OU Registered in Estonia number 16317035';
			
			
			if( $row['Country'] == 'Italy' ){
				
				switch ($row['Package']) {
					case "Monthly":
						$Package = 'Mese';
						break;
					case "One Time":
						$Package = 'Pagamento unico';
						break;
					case "Yearly":
						$Package = 'anno';
						break;
					default:
					
				}
				
				$InvoiceTxt = 'Fattura #';
				$DateTxt = 'Data:';
				$ReferenceTxt = 'Numero ordine:';
				$PurchaseOrderTxt = 'Ordine d’acquisto';
				$PurchaseOrderTxt = iconv('UTF-8', 'windows-1252', $PurchaseOrderTxt);
				$VATNumberTxt = 'Partita IVA:';
				$SupplierTxt = 'Fornitore';
				$SupporterTxt = 'Sostenitore';
				$CSRServicesEuropeOUTxt = 'CSR Services Europe OU';
				$DescriptionTxt = 'Causale';
				$PlasticNeutralitypackageTxt = 'Servizio per la sostenibilità';
				$PlasticNeutralitypackageTxt = iconv('UTF-8', 'windows-1252', $PlasticNeutralitypackageTxt);
				$InclusiveTxt = $row['token'].' ricevuto:';
			
				$InclusiveAmountTxt = $csr_inc .' '.$row['token'];
				$PlasticCreditTxt ='Quantità di plastica eliminata:';
				$PlasticCreditTxt = iconv('UTF-8', 'windows-1252', $PlasticCreditTxt);
				$PlasticCreditAmountTxt = $row['Kgs']. ' kg ' .$Package;
				$PoNotesTxt = "Questo ordine di acquisto è valido per 30 giorni. Se l'ordine di acquisto non viene pagato e/o riscattato nei tempi stabiliti, la Società può rifiutarsi di evadere l'ordine, in tutto o in parte, se le condizioni sono cambiate e non possono essere soddisfatte.";
				$PoNotesTxt = iconv('UTF-8', 'windows-1252', $PoNotesTxt);
				
				$PriceTxt = 'Prezzo ('.EURO.')';
				$VatPercentageTxt = 'IVA %:';
				$VatTxt = 'IVA:';
				$TotalPayableTxt = 'Totale da pagare ('.EURO.')';
				$BankDetailsTxt = 'Coordinate bancarie';
				$AccountHolderTxt = 'Titolare del conto:';
				$IBANTxt = 'IBAN:';
				$BICTxt = 'BIC:';
				$BankNameTxt = 'Nome della banca:';
				$BankAddressTxt = 'Indirizzo della banca:';
				$RegisteredInTxt = 'CSR Services Europe OU Registrata in Estonia numero 16317035';
			}
			$pdf->SetLeftMargin(118);
			if($status == 'Paid' && $type == 'Invoice'){
				
				$pdf->Cell(80,2,'', "T,L,R,0","1","L");
				$pdf->Cell(80,10,'   '. $InvoiceTxt . $row['InvoiceNumber'], "L,R,0,0","1","L");
				$pdf->Cell(80,2,'', "T,L,R,0","1","l");
				$pdf->SetTextColor(0, 0, 0);
				$pdf->SetFont( 'Arial', '', 12 );
				$pdf->Cell(35,6,'   '. $DateTxt, "L,0,0,0","0","l");
				$pdf->SetFont( 'Arial', '', 12 );
				$pdf->Cell(45,6, $row['PaidDate'], "0,R,0,0","1","l");
				$pdf->Cell(35,6,'   '. $ReferenceTxt , "L,0,0,0","0","l");
				$pdf->SetFont( 'Arial', '', 12 );
				$pdf->MultiCell(45,6, "CSR-PO-" . $row['ProformaInvoiceNumber'], "0,R,0,0","l");
			}
			else{
				$pdf->Cell(80,2,'', "T,L,R,0","1","L");
				$pdf->Cell(80,10,'   '. $PurchaseOrderTxt, "L,R,B,0","1","L");
				
				$pdf->SetTextColor(0, 0, 0);
				$pdf->SetFont( 'Arial', '', 12 );
				$pdf->Cell(80,2,'', "0,L,R,T","1","l");
				$pdf->Cell(35,6,'   '. $DateTxt, "L,0,0,0","0","l");
				$pdf->Cell(45,6, $row['Date'], "0,R,0,0","1","l");
				$pdf->Cell(35,6,'   '. $ReferenceTxt, "L,0,0,0","0","l");
				$pdf->MultiCell(45,6, "CSR-PO-" . $row['ProformaInvoiceNumber'], "0,R,0,0","l");
			}

			$pdf->Cell(35,6,'   '.$VATNumberTxt, "L,0,0,0","0","l");
			$pdf->MultiCell(45,6, 'EE102417928', "0,R,0,0","l");
			$pdf->Cell(80,2,' ', "L,R,B,0","0","l");
			$pdf->SetLeftMargin(12);
			$pdf->Ln( 5 );
			
			
			$pdf->SetFont('Arial','B',14);
			
			$pdf->Cell(93,12,'   '.$SupplierTxt, "T,R,B,L","0","l");
			$pdf->Cell(93,12,'   '.$SupporterTxt, "T,R,B,0","1","l");
			$pdf->SetFont('Arial','B',11);
			$pdf->Cell(93,8,'   '.$CSRServicesEuropeOUTxt, "0,R,0,L","0","l");
			$user_name = iconv('UTF-8', 'windows-1252', $row['FirstName']." " .$row['LastName']);
			$pdf->Cell(93,8,'   ' . $user_name , "0,R,0,0","1","l");
			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('Arial','',11);
			$pdf->MultiCell(93,8,"   Keemia 4", "0,R,0,L", "l");
			$x = $pdf->GetX();
			$y = $pdf->GetY();
			$pdf->SetXY($x + 93, $y);
			
			if($row['BusinessName']){
				$pdf->MultiCell(93,-8,'   ' . $row['BusinessName'], "0,R,0,0", "l");
			}
			else{
				$pdf->MultiCell(93,-8,'   ' . $row['Address1'], "0,R,0,L", "l");
			}
			$x = $pdf->GetX();
			$y = $pdf->GetY();
			$pdf->SetXY($x , $y+8);
			
			$pdf->Cell(93,8,'   Kristiine linnaosa', "0,R,0,L","0","l");
			if($row['BusinessName']){
				$pdf->Cell(93,8,'   ' . $row['Address1'].", " .$row['Address2'] , "0,R,0,0","1","l");
			}
			else{
				$pdf->Cell(93,8,'   '.$row['Address2'] , "0,R,0,L","1","l");
			}
			$pdf->MultiCell(93,8,'   Tallinn', "0,R,0,L", "l");
			$x = $pdf->GetX();
			$y = $pdf->GetY();
			$pdf->SetXY($x + 93, $y);
			$pdf->MultiCell(93,-8,'   ' . $row['City'].", " .$row['State'] , "0,R,0,0", "l");
			
			$x = $pdf->GetX();
			$y = $pdf->GetY();
			$pdf->SetXY($x , $y+8);

			$pdf->Cell(93,8,'   10616', "0,R,0,L","0","l");
			$pdf->Cell(93,8,'   ' . $row['Zipcode'] . ', ' . $row['Country'], "0,R,0,0","1","l");
			
			if( empty( $row['VatNumber'] ) ){
				$VATNumberTxt = "";
			}
			
			$pdf->MultiCell(93,8,"   Estonia", "0,R,0,L", "l");
			$x = $pdf->GetX();
			$y = $pdf->GetY();
			$pdf->SetXY($x + 93, $y);
			$pdf->MultiCell(93,-8,"   " . $VATNumberTxt . $row['VatNumber'], "0,R,0,L", "l");
			$pdf->SetTextColor(0, 0, 0);
			$pdf->Ln( 8 );
			$pdf->Cell(186,1,'  ', "T,0,0,0","1","l");

			$pdf->SetFont('Arial','B',12);
			$pdf->SetTextColor(0, 0, 0);
			$pdf->Ln( 5 );
			$pdf->Cell(186,8,'   '.$DescriptionTxt, "T,L,R,0","1","l");
			$pdf->SetFont('Arial','',11);
			$pdf->SetTextColor(0, 0, 0);
			$pdf->Cell(186,8,'   '.$PlasticNeutralitypackageTxt, "0,L,R,0","1","l");
			$pdf->Cell(93,8,'   '.$InclusiveTxt, "0,L,0,0","0","l");
			$pdf->Cell(93,8,'   '.$InclusiveAmountTxt, "0,0,R,0","1","l");
			$pdf->Cell(93,8,'   '.$PlasticCreditTxt, "0,L,0,0","0","l");
			$pdf->Cell(93,8,'   '.$PlasticCreditAmountTxt, "0,0,R,0","1","l");
			$pdf->SetFont('Arial','B',11);
			$pdf->Cell(93,11,'   '.$PriceTxt, "1","0","l");
			$pdf->SetFont('Arial','',11);
			$pdf->Cell(93,11,"   " . EURO . " " . cip_pdf_number_formater( $row['ProductPrice'] ), "1","1","l");
			$pdf->SetFont('Arial','B',11);
			$pdf->Cell(93,11,"   ".$VatPercentageTxt, "0,L,R,B","0","l");
			$pdf->SetFont('Arial','',11);
			$pdf->Cell(93,11,"   " . $row['POVATPercentage'], "0,L,R,B","1","l");
			$pdf->SetFont('Arial','B',11);
			$pdf->Cell(93,11,"   ".$VatTxt, "0,L,R,B","0","l");
			$pdf->SetFont('Arial','',11);
			$pdf->Cell(93,11,"   "  .EURO. " " . cip_pdf_number_formater( $row['VATAmount'] ), "0,L,R,B","1","l");
			$pdf->SetFont('Arial','B',11);
			$pdf->Cell(93,11,'   '.$TotalPayableTxt, "0,L,R,B","0","l");
			$pdf->SetFont('Arial','',11);
			$pdf->Cell(93,11,"   " .EURO. " " . cip_pdf_number_formater( $row['NetAmount'] ), "0,L,R,B","1","l");
			
			$assign_to=$row['BankId'];
			
			$sel_account = "SELECT * FROM $account WHERE id='$assign_to'";
			$result = mysqli_query($conn, $sel_account);
			$count_rows = mysqli_num_rows($result);
			

			/* if($count_rows == 1){
				$result = mysqli_query($conn, $sel_account);
			}
			else{
				$sel_rotation_account = "select * from $account where Status ='Active' order by Status limit 1";
				$result = mysqli_query($conn, $sel_rotation_account);
				$count_rows = mysqli_num_rows($result);
			} */
			
			if($count_rows){
				while($row = mysqli_fetch_assoc($result)){
					
					$pdf->SetTextColor(0, 0, 0);
					$pdf->SetFont( 'Arial', 'B', 14 );
					$pdf->Ln( 5 );
					$pdf->Cell(186,12,'   '.$BankDetailsTxt, "T,L,R,0","1","l");

					$pdf->SetFont('Arial','',11);
					$pdf->SetTextColor(0,0,0);
					$pdf->Cell(93,11,'   '.$AccountHolderTxt, "T,L,R,B","0","l");
					$pdf->MultiCell(93,11,"   " . $row['AccountHolder'], "T,L,R,B","l");

					$pdf->Cell(93,11,'   '.$IBANTxt, "0,L,R,B","0","l");
					$pdf->MultiCell(93,11,"   " . $row['IBAN'], "0,L,R,B","l");

					$pdf->Cell(93,11,'   '.$BICTxt, "0,L,R,B","0","l");
					$pdf->MultiCell(93,11,"   " . $row['BIC'], "0,L,R,B","l");

					$pdf->Cell(93,11,'   '.$BankNameTxt, "T,L,R,B","0","l");
					$pdf->MultiCell(93,11,"   " . $row['BankName'], "T,L,R,B","l");

                    $str = $row['BankAddress'];
					$a = strlen($str);

					if(($a>36)&&($a<60)){
                        $pdf->Cell(93,14,'   '.$BankAddressTxt, "0,L,R,B","0","l");
						// CELL SPACING
						$pdf->setCellMargin(4);
						// END CELL SPACING
                        $pdf->MultiCell(93,7,$row['BankAddress'], "0,L,R,B","l");
                    }
					else if($a>60){
						$pdf->Cell(93,21,'   '.$BankAddressTxt, "0,L,R,B","0","l");
						// CELL SPACING
						$pdf->setCellMargin(4);
						// END CELL SPACING
                        $pdf->MultiCell(93,7,$row['BankAddress'], "0,L,R,B","l");
					}
                    else{
						$pdf->Cell(93,11,'   '.$BankAddressTxt, "0,L,R,B","0","l");
						// CELL SPACING
						$pdf->setCellMargin(4);
						// END CELL SPACING
						$pdf->MultiCell(93,11,$row['BankAddress'], "0,L,R,B","l");
					}
					//$pdf->Ln( 12 );
					
				}
			}
			if( isset( $type ) && $type == 'Invoice' ){

			}else{ //PO Note
				$pdf->SetTextColor(0, 0, 0);
				$pdf->SetFont( 'Arial', 'I', 9 );
				$pdf->SetLeftMargin(8);
				$pdf->Ln( 2 );
				$pdf->MultiCell(0,4, $PoNotesTxt , 0,"L");
				$pdf->SetLeftMargin(12);
			}

			if($status == 'Paid' && $type == 'Invoice'){
				$pdf->Ln( 15 );
				$pdf->Image($paid_img,108,266,90,30);
				$pdf->SetAutoPageBreak(false);
				$pdf->SetY(-17);
				$pdf->SetFont('Arial','I',8);
				$pdf->SetTextColor(140, 140, 140);
				$pdf->Cell(0,4, $RegisteredInTxt ,0,1,'l');
				$pdf->Cell(0,4,'Keemia 4, Kristiine linnaosa, Tallinn, 10616 Estonia',0,1,'l');
			}
			else{
				$pdf->SetAutoPageBreak(false);
				$pdf->SetY(283);
				$pdf->SetFont('Arial','I',8);
				$pdf->SetTextColor(140, 140, 140);
				$pdf->Cell(0,4,$RegisteredInTxt,0,1,'C');
				$pdf->Cell(0,4,'Keemia 4, Kristiine linnaosa, Tallinn, 10616 Estonia',0,1,'C');
			}

		}
	}else{
		wp_redirect( site_url() );
		exit();
	}
}
$pdf->Output();
?>