<?php
App::uses('AppApiController', 'Controller');

require ROOT . '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT . '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT . '/vendor/phpmailer/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class ApiController extends AppApiController {

	// const BCCEMAIL = 'zudic@intellex.rs';
	/**
	 * Contact form
	 **/
	
	public function contact() {
		# Validate and save
		$model = ClassRegistry::init('ContactForm');
		$mail = new PHPMailer(false);
		// echo '<pre>';
		// print_r($_POST);
		// echo '</pre>';
		$data = $this->validatePost($model, [ 'name', 'email', 'phone', 'message']);
		$success = $model->save($data);

		$name = $_POST['data']['name'];
		$phone = $_POST['data']['phone'];    
		$email = $_POST['data']['email'];
		$message = $_POST['data']['message'];
		$dateOffer = date('d.m.Y. H:i');

		$from_title = "$name $email";
		$subject_title = "Zahtev za kontakt | $phone";

		$htmlBody = '<!DOCTYPE html>
		<html lang="sr">
		<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>*|MC:SUBJECT|*</title>
		<style>
		*,::after,::before{box-sizing:border-box;}
		body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff;}
		h4{margin-top:0;margin-bottom:.5rem;}
		b{font-weight:bolder;}
		a{color:#007bff;text-decoration:none;background-color:transparent;}
		a:hover{color:#0056b3;text-decoration:underline;}
		img{vertical-align:middle;border-style:none;}
		table{border-collapse:collapse;}
		th{text-align:inherit;}
		h4{margin-bottom:.5rem;font-weight:500;line-height:1.2;}
		h4{font-size:1.5rem;}
		.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto;}
		@media only screen and (max-width: 480px){
		table,td,a{-webkit-text-size-adjust:none!important;}
		.footerContent{font-size:14px!important;line-height:115%!important;}
		.footerContent a{display:block!important;}
		}
		@media (min-width:576px){
		.container{max-width:540px;}
		}
		@media (min-width:768px){
		.container{max-width:720px;}
		}
		@media (min-width:992px){
		.container{max-width:960px;}
		}
		@media (min-width:1200px){
		.container{max-width:1140px;}
		}
		.table{width:100%;margin-bottom:1rem;color:#212529;}
		.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6;}
		.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6;}
		.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;}
		.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125);}
		.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0;}
		.my-2{margin-top:.5rem!important;}
		.my-2{margin-bottom:.5rem!important;}
		.my-4{margin-top:1.5rem!important;}
		.my-4{margin-bottom:1.5rem!important;}
		.mb-5{margin-bottom:3rem!important;}
		@media print{
		*,::after,::before{text-shadow:none!important;box-shadow:none!important;}
		a:not(.btn){text-decoration:underline;}
		thead{display:table-header-group;}
		img,tr{page-break-inside:avoid;}
		body{min-width:992px!important;}
		.container{min-width:992px!important;}
		.table{border-collapse:collapse!important;}
		.table th{background-color:#fff!important;}
		}
		</style>    
		</head>
		<body>   
		<div class="container">
		<div class="card my-4">
		<div class="card-header">
		<h4>Zahtev za kontakt</h4>
		</div>
		</div>
		<table class="table">
		<thead>
		<tr>
		<th scope="col">Ime Prezime:</th>
		<th scope="col">'. $name . '</th>
		</tr>
		<tr>
		<th scope="col">Kontakt telefon:</th>
		<th scope="col"><a href="tel:'. $phone .'">'. $phone .'</a></th>
		</tr>
		<tr>
		<th scope="col">Email adresa:</th>
		<th scope="col"><a href="mailto:'. $email .'">'. $email .'</a></th>
		</tr>		
		<tr>
		<th scope="col">Poruka:</th>
		<th scope="col">'. $message .'</th>
		</tr>
		<tr>
		<th scope="col">Datum i vreme prijema:</th>
		<th scope="col">'. $dateOffer .'</th>
		</tr>		
		</thead>
		</table>
		<p>Poslato pomoću forme - Kontakt</p>

		<td valign="top" class="footerContent" style="padding-top:0;">
		<p>Copyright © '. date('Y') .' EuroAudit All rights reserved.</p>
		</td>
		</div>
		</body>
		</html>
		';
		$altBodyText = "Zahtev za kontakt<br>Ime Prezime: $name<br>Kontakt telefon: $phone<br>Email adresa: $email<br>Poruka: $message<br>Datum i vreme prijema: $dateOffer<br>";

		try {    
			//Server settings
			$mail->SMTPDebug = SMTP::DEBUG_OFF ;                      // Enable verbose debug output
			// $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
			$mail->isSMTP();                                            // Send using SMTP
			$mail->Host       = 'mail.euaudit.com';                     // Set the SMTP server to send through
			$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
			$mail->Username   = 'zahtevi@euaudit.com';                  // SMTP username
			$mail->Password   = 'Q]rQ0TE[};O]GpLrA?';                            // SMTP password  
			$mail->SMTPSecure = 'ssl';                                  // $mail->SMTPSecure = 'ssl'; $mail->SMTPSecure = 'tls';
			$mail->SMTPAutoTLS = false;
			$mail->Port       = 465;                                    // TCP port to connect to
			
			//Recipients
			$mail->setFrom($email, $name);
			$mail->addAddress('zahtevi@euaudit.com', 'Zahtev za kontakt');     // Add a recipient
			// $mail->addAddress($email, $name);               // Name is optional
			$mail->addReplyTo($email, $name);
			// $mail->addCC('cc@example.com');
			// $mail->addBCC('bcc@example.com');
			// $mail->addBCC('pavle.dakic@euaudit.com');

			// Content
			$mail->isHTML(true);                                    // Set email format to HTML
			$mail->Encoding = 'base64';                             // $mail->Encoding = "16bit";    
			$mail->CharSet = "utf-8";
			$mail->Subject = $subject_title;    
			$mail->Body    = $htmlBody;                             // HTML body content
			$mail->AltBody = $altBodyText; // This is the body in plain text for non-HTML mail clients
			
			// echo $mail->Body;
			if ($success) {
			// Send Email
			$mail->send();

			$link = "//" . $_SERVER['HTTP_HOST'];
			$loc = $link . $_SERVER["REQUEST_URI"];

			$send_message = 'Message has been sent';
			if (!headers_sent()) {
				exit(header("Location: {$_REQUEST["destination"]}?sending=true"));				
			}
			else{
				die("Redirect failed. Please click on this link: <a href='{$_REQUEST["destination"]}'>{$_REQUEST["destination"]}</a>");
				// exit(header("Location: {$_REQUEST["destination"]}"));
				// header("Location: $loc");
				// die(0);
			}					

			echo "
			<script>
					// alert('Message sent succesfully');
					window.location.href('$loc');
					document.getElementById('success-message').innerHTML = $send_message;
			</script>";
		}
			# Send response
			$this->send(
				$success,
				$success
					? __('Thank you for your Message')
					: __('An error occurred, please try later')
			);
			exit;
		} catch (Exception $e) {
			echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
		}	
		// header ("Location: index.php");
		

		// if(isset($_SERVER['HTTP_REFERER'])) {
		// 	$previous = $_SERVER['HTTP_REFERER'];
		// }	
		// $success = array();
		// $this->send(
		// 	$success,
		// 	$success
		// 		? __('Thank you for your Message')
		// 		: __('An error occurred, please try later')
		// );
		// echo json_decode($success);
		// echo $success->message;

		// $success = array('message' => 'Thank you for your Message'); //etc

		// header('Content-type: text/html; charset=UTF-8');

		// header('HTTP/1.1 201 Created');
		// echo '<pre>';
		// echo print_r(json_encode($success));
		// echo '</pre>';
	}

	public function request() {
		$mail = new PHPMailer(true);
		# Validate and save
		$model = ClassRegistry::init('RequestForm');
		$data = $this->validatePost($model, [ 'name', 'email', 'registration_number', 'contact_person', 'phone', 'cms_service_id' ]);
		$success = $model->save($data);

		# On success, send an email
		if ($success) {
			# Get the email
			$contactEmail = ClassRegistry::init('Setting')->field('email', 1);

			# Send an email
			// $success = $this->sendEmail(__('Novi zahtev za ponudom - EuroAudit'), $data)
			// 	->emailFormat('html')
			// 	->to($contactEmail)
			// 	->send();
			if (!empty($_POST)) {
				if (!empty($_POST['data']['name'])) {
					$name = $_POST['data']['name'];
					echo $name;
				}
			}
			if (isset($_POST['data'])) {
			// Get $_POST['data']
			$name = $_POST['data']['name'];
			$registration_number = $_POST['data']['registration_number'];
			$contact_person = $_POST['data']['contact_person'];
			$phone = $_POST['data']['phone'];    
			$email = $_POST['data']['email'];
			$dateOffer = date('d.m.Y. H:i');
			
			switch ($_POST['data']['cms_service_id']) {
			case '1':
				$service = "Usluge revizije";
			break;
			case '2':
				$service = "Konsultantske usluge";
			break;
			case '3':
				$service = "Transferne cene";
			break;
			case '4':
				$service = "Ostale usluge";
			break;
			} 
			
			$from_title = "$name | MBR: $registration_number";
			$subject_title = "Zahtev za ponudom - $service - $contact_person | $phone";
			
			$htmlBody = '<!DOCTYPE html>
			<html lang="sr">
			<head>
			<meta charset="UTF-8">
			<meta name="viewport" content="width=device-width, initial-scale=1.0">
			<meta http-equiv="X-UA-Compatible" content="ie=edge">
			<title>*|MC:SUBJECT|*</title>
			<style>
			*,::after,::before{box-sizing:border-box;}
			body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff;}
			h4{margin-top:0;margin-bottom:.5rem;}
			b{font-weight:bolder;}
			a{color:#007bff;text-decoration:none;background-color:transparent;}
			a:hover{color:#0056b3;text-decoration:underline;}
			img{vertical-align:middle;border-style:none;}
			table{border-collapse:collapse;}
			th{text-align:inherit;}
			h4{margin-bottom:.5rem;font-weight:500;line-height:1.2;}
			h4{font-size:1.5rem;}
			.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto;}
			@media only screen and (max-width: 480px){
			table,td,a{-webkit-text-size-adjust:none!important;}
			.footerContent{font-size:14px!important;line-height:115%!important;}
			.footerContent a{display:block!important;}
			}
			@media (min-width:576px){
			.container{max-width:540px;}
			}
			@media (min-width:768px){
			.container{max-width:720px;}
			}
			@media (min-width:992px){
			.container{max-width:960px;}
			}
			@media (min-width:1200px){
			.container{max-width:1140px;}
			}
			.table{width:100%;margin-bottom:1rem;color:#212529;}
			.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6;}
			.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6;}
			.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem;}
			.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125);}
			.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0;}
			.my-2{margin-top:.5rem!important;}
			.my-2{margin-bottom:.5rem!important;}
			.my-4{margin-top:1.5rem!important;}
			.my-4{margin-bottom:1.5rem!important;}
			.mb-5{margin-bottom:3rem!important;}
			@media print{
			*,::after,::before{text-shadow:none!important;box-shadow:none!important;}
			a:not(.btn){text-decoration:underline;}
			thead{display:table-header-group;}
			img,tr{page-break-inside:avoid;}
			body{min-width:992px!important;}
			.container{min-width:992px!important;}
			.table{border-collapse:collapse!important;}
			.table th{background-color:#fff!important;}
			}
			</style>    
			</head>
			<body>   
			<div class="container">
			<div class="card my-4">
			<div class="card-header">
			<h4>Zahtev za ponudom</h4>
			</div>
			</div>
			<table class="table">
			<thead>
			<tr>
			<th scope="col">Naziv društva:</th>
			<th scope="col">'. $name . '</th>
			</tr>
			<tr>
			<th scope="col">Matični broj:</th>
			<th scope="col">'. $registration_number . '</th>
			</tr>
			<tr>
			<th scope="col">Kontakt osoba:</th>
			<th scope="col">'. $contact_person . '</th>
			</tr>
			<tr>
			<th scope="col">Kontakt telefon:</th>
			<th scope="col"><a href="tel:'. $phone .'">'. $phone .'</a></th>
			</tr>
			<tr>
			<th scope="col">Email adresa:</th>
			<th scope="col"><a href="mailto:'. $email .'">'. $email .'</a></th>
			</tr>
			<tr>
			<th scope="col">Izabrana usluga:</th>
			<th scope="col">
			'. $service .'
			</th>
			<tr>
			<th scope="col">Datum i vreme prijema:</th>
			<th scope="col">'. $dateOffer .'</th>
			</tr>
			</tr>
			</thead>
			</table>
			<p>Poslato pomoću forme - Zahtev za ponudom</p>
			
			<td valign="top" class="footerContent" style="padding-top:0;">
			<p>Copyright © '. date('Y') .' EuroAudit All rights reserved.</p>
			</td>
			</div>
			</body>
			</html>
			';
			$altBodyText = "Zahtev za ponudom<br>Naziv društva: $name<br>Matični broj: $registration_number<br>Kontakt osoba: $contact_person<br>Kontakt telefon: $phone<br>Email adresa: $email<br>Izabrana usluga: $service<br>Datum i vreme prijema: $dateOffer<br>";
			
			// echo (extension_loaded('openssl')?'SSL loaded':'SSL not loaded')."\n";
			try {    
				//Server settings
				$mail->SMTPDebug = SMTP::DEBUG_OFF;                      // Enable verbose debug output
				$mail->isSMTP();                                            // Send using SMTP
				$mail->Host       = 'mail.euaudit.com';                     // Set the SMTP server to send through
				$mail->SMTPAuth   = true;                                   // Enable SMTP authentication
				$mail->Username   = 'zahtevi@euaudit.com';                  // SMTP username
				$mail->Password   = 'Q]rQ0TE[};O]GpLrA?';                            // SMTP password  
				$mail->SMTPSecure = 'ssl';                                  // $mail->SMTPSecure = 'ssl'; $mail->SMTPSecure = 'tls';
				$mail->SMTPAutoTLS = false;
				$mail->Port       = 465;                                    // TCP port to connect to
				
				//Recipients
				$mail->setFrom($email, $name);
				$mail->addAddress('zahtevi@euaudit.com', 'Zahtev za ponudom');     // Add a recipient
				// $mail->addAddress($email, $contact_person);               // Name is optional
				$mail->addReplyTo($email, $contact_person);
				// $mail->addCC('cc@example.com');
				// $mail->addBCC('bcc@example.com');
				// $mail->addBCC('pavle.dakic@euaudit.com');
			
				// Content
				$mail->isHTML(true);                                    // Set email format to HTML
				$mail->Encoding = 'base64';                             // $mail->Encoding = "16bit";    
				$mail->CharSet = "utf-8";
				$mail->Subject = $subject_title;    
				$mail->Body    = $htmlBody;                             // HTML body content
				$mail->AltBody = $altBodyText; // This is the body in plain text for non-HTML mail clients
				
				// echo $mail->Body;
			
				// Send Email
				$mail->send();
				$link = "//" . $_SERVER['HTTP_HOST'];
			$loc = $link . $_SERVER["REQUEST_URI"];

			$send_message = 'Message has been sent';
			if (!headers_sent()) {
				exit(header("Location: {$_REQUEST["destination"]}?sending=true"));				
			}
			else{
				die("Redirect failed. Please click on this link: <a href='{$_REQUEST["destination"]}'>{$_REQUEST["destination"]}</a>");
				// exit(header("Location: {$_REQUEST["destination"]}"));
				// header("Location: $loc");
				// die(0);
			}					

			echo "
			<script>
					// alert('Message sent succesfully');
					window.location.href('$loc');
					document.getElementById('success-message').innerHTML = $send_message;
			</script>";
		
			# Send response
			$this->send(
				$success,
				$success
					? __('Thank you for your Message')
					: __('An error occurred, please try later')
			);
			exit;

			} catch (Exception $e) {
				echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
			} 
			}
		}
		
	}

	/**
	 * Validate that the post has only white-listed properties
	 * @param null  $model
	 * @param array $whitelist
	 *
	 * @return array
	 */
	public function validatePost($model = null, $whitelist = []) {
		# Handle validation errors
		if (is_array($model)) {
			$whitelist = $model;
			$model = null;
		} else if (is_string($model)) {
			$model = ClassRegistry::init($model);
		}

		# Extract data
		$data = array_intersect_key($this->request->data, array_flip($whitelist));

		# Validate
		if ($model) {
			$errors = $model->validateData($data);
			if (!empty($errors)) {
				$this->send(false, null, $errors);
			}
		}
		return $data;
	}

	/**
	 * Send response message and errors
	 * @param      $response
	 * @param      $message
	 * @param null $errors
	 */
	private function send($response, $message, $errors = null) {
		$this->Api->build(null, compact('response', 'message', 'errors'));
	}
}
