<?php
session_start();
include "../includes/connect.php";
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

require '../includes/Exception.php';
require '../includes/PHPMailer.php';
//require "PHPMailerAutoload.php";
require '../includes/SMTP.php';

require_once "../includes/Mobile_Detect.php";

function generateRandomString($length = 10) {
	return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}
$openFile = fopen("cdata.txt", "r") or die("Unable to open file!");
$campaignData = fread($openFile, filesize("cdata.txt"));
fclose($openFile);

$campaignInfo = explode(PHP_EOL, $campaignData);
$campaignid = $campaignInfo[0];

$datiCampagna = $connection->query("SELECT meta_key,meta_value FROM campaigns_meta a WHERE campaign_id = '$campaignid' UNION ALL select 'txtLang' as meta_key,left(code,2) as meta_value from languages where id=(select meta_value from campaigns_meta where campaign_id='$campaignid' and meta_key='language');");

$campaignData = $datiCampagna->fetchAll(PDO::FETCH_KEY_PAIR);

$tabellaLead = "campaign" . $campaignid . "_leads";
$ts = $_GET['sanit'];
$eid = $_GET['e'];

$linguaCorrenteCampagna = $campaignData['txtLang'];

$sqlVerifica = $connection->prepare("SELECT validata from $tabellaLead where externalid = ?");
$sqlVerifica->execute(["$eid"]);
$Validata = $sqlVerifica->fetchColumn();

$nValidata = $Validata;

if ($nValidata != 1) {

	$connection->query("UPDATE $tabellaLead SET validata='1' WHERE timestamp = '$ts' AND externalid = '$eid'");

	if ($campaignid >= 65) {

		// in questo caso, mandiamo le credenziali via posta all'indirizzo email

		$gatto = generateRandomString();
		$q = $connection->prepare("SELECT email FROM $tabellaLead WHERE externalid=?");
		$q->execute(["$eid"]);
		$topo = $q->fetchColumn();
		$q = $connection->prepare("SELECT nome FROM account_leads WHERE email=?");
		$q->execute(["$topo"]);
		$nome = $q->fetchColumn();
		$queryAccount = $connection->prepare("UPDATE account_leads SET motto=(md5(?)) where email=?");
		$queryAccount->execute(["$gatto", "$topo"]);
		$txtTitleComunicazione = "";
		if (($linguaCorrenteCampagna == "it")) {

			$mailHtml = "Grazie, confermiamo la tua iscrizione a labakeca.eu. Con il tuo account, avrai accesso a tante offerte e contenuti esclusivi!
             <br><br>Per accedere, <strong><a href='https://labakeca.eu" . $linguaCorrenteCampagna . "'>clicca qui!</a></strong> <br><br>
                Di seguito, ecco i tuoi dati di accesso: <br><strong>Username:</strong> " . $topo . "<br><strong>Password:</strong> " . $gatto . "<br>";

			$txtBtnConf = "ACCEDI";
			$txtoggetto = "$nome, ecco le tue credenziali per LaBakeca.eu";

			$setFrom = 'Dati di accesso LaBakeca.eu';

			$txtTitleComunicazione = "Indirizzo email confermato, grazie!";

			$txtBodyComunicazione = "Il tuo indirizzo e-mail è stato confermato correttamente! <br> Ti abbiamo inviato una mail con le credenziali di accesso al nostro portale! <br><em>Se non dovessi trovarla, verifica anche nello spam!</em> ";

		} elseif (($linguaCorrenteCampagna == "es")) {
			$mailHtml = "Hola $nome <br> <br>
            Gracias, confirmamos tu suscripción a labakeca.eu. ¡Con tu cuenta, tendrás acceso a muchas ofertas y contenido exclusivo!
             <br><br>Para visitarlo, <strong><a href='https://labakeca.eu" . $linguaCorrenteCampagna . "'>pulse aquí!</a></strong> <br><br>
                Aquí tienes tus datos de acceso: <br><strong>Username:</strong> " . $topo . "<br><strong>Password:</strong> " . $gatto . "<br>";

			$txtBtnConf = "ENTRAR";

			$txtoggetto = "$nome, aquí están sus credenciales para LaBakeca.eu";

			$setFrom = 'Datos de acceso a LaBakeca.eu';

			$txtTitleComunicazione = "Dirección de correo electrónico confirmada, ¡gracias!";

			$txtBodyComunicazione = "Su dirección de correo electrónico se ha confirmado correctamente. <br>Le hemos enviado un correo electrónico con las credenciales de acceso a nuestro portal<br><em>y si no lo encuentras, ¡por favor comprueba tu carpeta de spam!</em> ";

		} elseif (($linguaCorrenteCampagna == "en")) {
			$mailHtml = "Hi $nome! <br> <br>
           Thank you, we confirm your subscription to labakeca.eu. With your account, you will have access to many offers and exclusive content!
             <br><br>To visit it, <strong><a href='https://labakeca.eu" . $linguaCorrenteCampagna . "'>click here!</a></strong> <br><br>
               Here are your login details: <br><strong>Username:</strong> " . $topo . "<br><strong>Password:</strong> " . $gatto . "<br>";

			$txtBtnConf = "SIGN IN";

			$txtoggetto = "$nome, here are your credentials for LaBakeca.eu";

			$setFrom = ' LaBakeca.eu login details';

			$txtTitleComunicazione = "Email address confirmed, thank you!";

			$txtBodyComunicazione = "Your email address has been successfully confirmed! <br>We have sent you an e-mail with the login credentials for our portal<br><em>and if you don't find it, please check your spam folder!</em> ";
		}

		$dominio = "labakeca.eu";
		$mailHtml = '<!DOCTYPE html>
        <html>
        <head>

          <meta charset="utf-8">
          <meta http-equiv="x-ua-compatible" content="ie=edge">
          <title>Email Confirmation</title>
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <style type="text/css">
          /**
           * Google webfonts. Recommended to include the .woff version for cross-client compatibility.
           */
          @media screen {
            @font-face {
              font-family: \'Source Sans Pro\';
              font-style: normal;
              font-weight: 400;
              src: local(\'Source Sans Pro Regular\'), local(\'SourceSansPro-Regular\'), url(https://fonts.gstatic.com/s/sourcesanspro/v10/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format(\'woff\');
            }
            @font-face {
              font-family: \'Source Sans Pro\';
              font-style: normal;
              font-weight: 700;
              src: local(\'Source Sans Pro Bold\'), local(\'SourceSansPro-Bold\'), url(https://fonts.gstatic.com/s/sourcesanspro/v10/toadOcfmlt9b38dHJxOBGFkQc6VGVFSmCnC_l7QZG60.woff) format(\'woff\');
            }
          }
          /**
           * Avoid browser level font resizing.
           * 1. Windows Mobile
           * 2. iOS / OSX
           */
          body,
          table,
          td,
          a {
            -ms-text-size-adjust: 100%; /* 1 */
            -webkit-text-size-adjust: 100%; /* 2 */
          }
          /**
           * Remove extra space added to tables and cells in Outlook.
           */
          table,
          td {
            mso-table-rspace: 0pt;
            mso-table-lspace: 0pt;
          }
          /**
           * Better fluid images in Internet Explorer.
           */
          img {
            -ms-interpolation-mode: bicubic;
          }
          /**
           * Remove blue links for iOS devices.
           */
          a[x-apple-data-detectors] {
            font-family: inherit !important;
            font-size: inherit !important;
            font-weight: inherit !important;
            line-height: inherit !important;
            color: inherit !important;
            text-decoration: none !important;
          }
          /**
           * Fix centering issues in Android 4.4.
           */
          div[style*="margin: 16px 0;"] {
            margin: 0 !important;
          }
          body {
            width: 100% !important;
            height: 100% !important;
            padding: 0 !important;
            margin: 0 !important;
          }
          /**
           * Collapse table borders to avoid space between cells.
           */
          table {
            border-collapse: collapse !important;
          }
          a {
            color: #1a82e2;
          }
          img {
            height: auto;
            line-height: 100%;
            text-decoration: none;
            border: 0;
            outline: none;
          }
          </style>

        </head>
        <body style="background-color: #e9ecef;">

          <!-- start preheader -->
          <div class="preheader" style="display: none; max-width: 0; max-height: 0; overflow: hidden; font-size: 1px; line-height: 1px; color: #fff; opacity: 0;">
            ' . $txtTitleComunicazione . '
          </div>
          <!-- end preheader -->

          <!-- start body -->
          <table border="0" cellpadding="0" cellspacing="0" width="100%">

            <!-- start logo -->
            <tr>
              <td align="center" bgcolor="#e9ecef">
                <!--[if (gte mso 9)|(IE)]>
                <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
                <tr>
                <td align="center" valign="top" width="600">
                <![endif]-->
                <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                  <tr>
                    <td align="center" valign="top" style="padding: 36px 24px;">
                      <a href="https://labakeca.eu" target="_blank" style="display: inline-block;">
                       LaBakeca.eu
                      </a>
                    </td>
                  </tr>
                </table>
                <!--[if (gte mso 9)|(IE)]>
                </td>
                </tr>
                </table>
                <![endif]-->
              </td>
            </tr>
            <!-- end logo -->

            <!-- start hero -->
            <tr>
              <td align="center" bgcolor="#e9ecef">
                <!--[if (gte mso 9)|(IE)]>
                <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
                <tr>
                <td align="center" valign="top" width="600">
                <![endif]-->
                <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
                  <tr>
                    <td align="left" bgcolor="#ffffff" style="padding: 36px 24px 0; font-family: \'Source Sans Pro\', Helvetica, Arial, sans-serif; border-top: 3px solid #d4dadf;">
                      <h1 style="margin: 0; font-size: 32px; font-weight: 700; letter-spacing: -1px; line-height: 48px;">
                          ' . $txtTitleComunicazione . '
                      </h1>
                    </td>
                  </tr>
                </table>
                <!--[if (gte mso 9)|(IE)]>
                </td>
                </tr>
                </table>
                <![endif]-->
              </td>
            </tr>
            <!-- end hero -->

            <!-- start copy block -->
            <tr>
              <td align="center" bgcolor="#e9ecef">
                <!--[if (gte mso 9)|(IE)]>
                <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
                <tr>
                <td align="center" valign="top" width="600">
                <![endif]-->
                <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
         <!-- start copy -->
                  <tr>
                    <td align="left" bgcolor="#ffffff" style="padding: 24px; font-family: \'Source Sans Pro\', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px;">
                      <p style="margin: 0;"> ' . $mailHtml . '</p>
                    </td>
                  </tr>
                  <!-- end copy -->



                  <!-- start button -->
                  <tr>
                    <td align="left" bgcolor="#ffffff">
                      <table border="0" cellpadding="0" cellspacing="0" width="100%">
                        <tr>
                          <td align="center" bgcolor="#ffffff" style="padding: 12px;">
                            <table border="0" cellpadding="0" cellspacing="0">
                              <tr>
                                <td align="center" bgcolor="#1a82e2" style="border-radius: 6px;">
                                  <a href="https://' . $dominio . '/' . $linguaCorrenteCampagna . '/index" target="_blank" target="_blank" style="display: inline-block; padding: 16px 36px; font-family: \'Source Sans Pro\',Helvetica, Arial, sans-serif; font-size: 16px; color: #ffffff; text-decoration: none; border-radius: 6px;">' . $txtBtnConf . '</a>
                                </td>
                              </tr>
                            </table>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                  <!-- end button -->

                  <!-- start copy -->
                  <tr>
                    <td align="left" bgcolor="#ffffff" style="padding: 24px; font-family: \'Source Sans Pro\', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px; border-bottom: 3px solid #d4dadf">
                      <p style="margin: 0;"><br> LaBakeca.eu</p>
                    </td>
                  </tr>
                  <!-- end copy -->

                </table>
                <!--[if (gte mso 9)|(IE)]>
                </td>
                </tr>
                </table>
                <![endif]-->
              </td>
            </tr>
            <!-- end copy block -->

            <!-- start footer -->
            <tr>
              <td align="center" bgcolor="#e9ecef" style="padding: 24px;">
                <!--[if (gte mso 9)|(IE)]>
                <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
                <tr>
                <td align="center" valign="top" width="600">
                <![endif]-->
                <table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">

                  <!-- start permission -->
                  <tr>
                    <td align="center" bgcolor="#e9ecef" style="padding: 12px 24px; font-family: \'Source Sans Pro\', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px; color: #666;">
                          <p style="margin: 0;">WyamAdv LTD  -  Sofia 1000, blvd.Alexandar Stamboliyski 38, floor 2,apartment 7 (BG)</p>
                    </td>
                  </tr>
                  <!-- end permission -->


                </table>
                <!--[if (gte mso 9)|(IE)]>
                </td>
                </tr>
                </table>
                <![endif]-->
              </td>
            </tr>
            <!-- end footer -->

          </table>
          <!-- end body -->

        </body>
        </html>';

		$emailInviatore = 'back@labakeca.eu';

		#$emailBcc = "webmaster@elenchitelefonici.it";
		try {

			// configurazione invio email
			$mail = new PHPMailer(true);

			$mail->isSMTP();
			//$mail->SMTPDebug = 4;
			$mail->Mailer = "smtp";
			$mail->Host = 'mail.labakeca.eu'; // Set the SMTP server to send through
			$mail->SMTPAuth = true; // Enable SMTP authentication
			$mail->SMTPAutoTLS = true;
			$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
			#$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
			$mail->Username = 'back@labakeca.eu'; // SMTP username
			$mail->Password = 'MGX7W7UCFJL'; // SMTP password
			$mail->Port = 587; // or 465                                 // TCP port to connect to

			$mail->setFrom($emailInviatore, $setFrom);
			$mail->addReplyTo($emailInviatore, $setFrom);
			$mail->addAddress($topo);
			$mail->isHTML(true);
			$mail->charset = 'UTF-8';
			$mail->Subject = utf8_decode($txtoggetto);
			$mail->Body = utf8_decode($mailHtml);
			#$message->addBcc($emailBcc);
			$mail->send();
			// echo 'Message has been sent';
		} catch (Exception $e) {
			//echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
		}

	}
} else {

	if (($linguaCorrenteCampagna == "it")) {

		$txtTitleComunicazione = "Indirizzo email già confermato, grazie!";

		$txtBodyComunicazione = "Il tuo indirizzo e-mail è stato confermato correttamente! <br> Ti abbiamo inviato una mail con le credenziali di accesso al nostro portale! <br><em>Se non dovessi trovarla, verifica anche nello spam!</em> ";

	} elseif (($linguaCorrenteCampagna == "es")) {

		$txtTitleComunicazione = "Dirección de correo electrónico ya confirmada, ¡gracias!";

		$txtBodyComunicazione = "Su dirección de correo electrónico ya ha sido confirmada previamente. <br>Le hemos enviado un correo electrónico con las credenciales de acceso a nuestro portal<br><em>y si no lo encuentras, ¡por favor comprueba tu carpeta de spam!</em> ";

	} elseif (($linguaCorrenteCampagna == "en")) {

		$txtTitleComunicazione = "Email address already confirmed, thank you!";

		$txtBodyComunicazione = "Your email address has already been successfully confirmed! <br>We have sent you an e-mail with the login credentials for our portal<br><em>and if you don't find it, please check your spam folder!</em> ";
	}

}
?>
<!DOCTYPE html>
<html lang="<?php echo $campaignData['txtLang']; ?>">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="" />
    <meta name="description" content="<?php echo $campaignData['campaign_description']; ?>" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <!-- <link rel="shortcut icon" href="assets/1_66bce83c4ac77e50c0afcad5ee7bf433.ico?v=39884" />
        <link rel="apple-touch-icon" href="assets/1_66bce83c4ac77e50c0afcad5ee7bf433.ico?v=39884"> -->
    <title>
        <?php echo $campaignData['campaign_title']; ?>
    </title>
    <meta property="og:title" content="<?php echo $campaignData['campaign_title']; ?>" />
    <meta property="og:description" content="<?php echo $campaignData['campaign_description']; ?>" />
    <link href="../campaignsAssets/css/common.css" rel="stylesheet">
    <link href="../campaignsAssets/css/voucherzone_style.css" rel="stylesheet">
    <link href="../campaignsAssets/css/layout.css" rel="stylesheet">
    <link href="../campaignsAssets/css/white.css" rel="stylesheet">
    <link href="../campaignsAssets/css/branding.css" rel="stylesheet">
</head>

<body>
    <div class="body-wrap lang_it" style="background-image: url(assets/<?php echo $campaignData['bg']; ?>)">
        <!-- immagine grande di sfondo -->
        <div class="body-wrap-in">
            <div class="content">
                <div class="content-in">
                    <div class="panels">
                        <div class="panel" id="thanks">
                            <div class="container">
                                <div class="row content-row">
                                    <div class="position-info">
                                        <div class="position-text">
                                            <div class="position-title-wrap">
                                                <div class="title"></div>
                                                <div class="subtitle"></div>
                                            </div>
                                            <div class="position-image">
                                                <img src="assets/<?php echo $campaignData['front_desktop']; ?>" alt="" class="pure-pic packshot-large" /> <!-- immagine front desktop form -->
                                                <img src="assets/<?php echo $campaignData['front_mobile']; ?>" alt="" class="pure-pic packshot-small" /> <!-- immagine front mobile form -->
                                            </div>
                                        </div>
                                    </div>
                                    <div class="position-form">
                                        <div class="questions" id="question-container">
                                            <div class="questions-progress-wrap">
                                                <div class="questions-progress">
                                                    <div class="questions-almost ">
                                                        <div class="questions-almost-img">
                                                            <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="200px" height="141.406px" viewBox="100 29.297 200 141.406" enable-background="new 100 29.297 200 141.406" xml:space="preserve">
                                                                <path fill="#F30B0B" d="M137.578,37.578l-8.281-8.281C110.391,48.203,100,73.281,100,100s10.391,51.836,29.297,70.703l8.281-8.281
                                                    c-16.68-16.68-25.859-38.828-25.859-62.422S120.898,54.258,137.578,37.578z" />
                                                                <path fill="#F30B0B" d="M145.898,45.898C131.406,60.352,123.438,79.57,123.438,100s7.969,39.648,22.461,54.102l8.281-8.281
                                                    c-12.266-12.266-19.023-28.516-19.023-45.82s6.758-33.555,19.023-45.82L145.898,45.898z" />
                                                                <path fill="#F30B0B" d="M270.703,29.297l-8.281,8.281c16.68,16.68,25.859,38.867,25.859,62.422s-9.18,45.742-25.859,62.422
                                                    l8.281,8.281C289.609,151.797,300,126.719,300,100S289.609,48.203,270.703,29.297z" />
                                                                <path fill="#F30B0B" d="M254.102,45.898l-8.281,8.281c12.266,12.266,19.023,28.555,19.023,45.82c0,17.305-6.758,33.555-19.023,45.82
                                                    l8.281,8.281c14.492-14.453,22.461-33.672,22.461-54.102S268.594,60.352,254.102,45.898z" />
                                                                <path fill="#F30B0B" d="M163.945,119.922h72.07v9.18h-72.07V119.922z" />
                                                                <path fill="#F30B0B" d="M191.367,142.695c0,4.766,3.867,8.633,8.633,8.633s8.633-3.867,8.633-8.633v-1.875h-17.266V142.695z" />
                                                                <path fill="#F30B0B" d="M225.742,96.133V84.258c0-12.227-8.516-22.422-19.883-25.078V48.711h-11.719V59.18
                                                    c-11.406,2.656-19.883,12.891-19.883,25.078v11.875c0,4.258-1.094,8.398-3.047,12.031h57.656
                                                    C226.836,104.531,225.742,100.43,225.742,96.133z" />
                                                            </svg> </div>
                                                        <div class="questions-almost-text">
                                                            <div class="onLeadCreated">
                                                                <?echo $txtTitleComunicazione; ?>
                                                            </div>
                                                            <div class="question-progress-impulse" style="background-color:#cecece!important;height:14rem!important;align-content: center;font-size:1.2rem;">
                                                                <?
if (($campaignid >= 65)) {
	echo $txtBodyComunicazione;
}

?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <p class="hide"></p>
                                                    <div class="question-progress">
                                                        <div id="question-progress-bar"></div>
                                                        <span class="question-progress-num"></span>
                                                    </div>
                                                </div>
                                                <div class="question-progress-impulse " style="background-color:#cecece!important;height:14rem!important;align-content: center;font-size:1.2rem;">
                                                    <?

if (($campaignid >= 65)) {

	echo $txtBodyComunicazione;
}

?>
                                                </div>
                                            </div>
                                            <div class="questions-in">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>