<?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';

function generateRandomString($length = 10) {
	return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

$pwd = generateRandomString();

//$dominio = "www.concorso-per-te.com"; // modificare per variare il link di conferma email

$valori = filter_input(INPUT_GET, 'values', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

//var_dump($valori);
$email = $valori['email'];
$email = strtolower($email);
$ip = $_SERVER['REMOTE_ADDR'];
$timestamp = time();

/* FINE ADDON Giugno 2021 */

$_SESSION["sale"] = $timestamp;
$_SESSION["indir"] = $email;

$sqlVerifica = $connection->prepare("SELECT count(*) as qta from account_leads where email=? and validata=0;");
$sqlVerifica->execute(["$email"]);
$countEmail = $sqlVerifica->fetchColumn();

$count = $countEmail;

if ($count === 1) {

	$sqlUser = $connection->query("SELECT campaignId as cid,externalid as eid,email FROM `campaign84_leads` WHERE email=? UNION ALL SELECT campaignId,externalid,email FROM `campaign83_leads` WHERE email=? UNION ALL SELECT campaignId,externalid,email FROM `campaign77_leads` WHERE email=? LIMIT 1;");

	$sqlUser->execute(["$email", "$email", "$email"]);
	$datiUser = $sqlUser->fetchAll(PDO::FETCH_KEY_PAIR);

	$cid = $datiUser["cid"];
	$eid = $datiUser["eid"];

	//echo "YYIIIS";

	$datiCampagna = $connection->query("SELECT meta_key,meta_value FROM campaigns_meta WHERE campaign_id = '$cid' AND meta_key = 'campaign_folder' 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='$cid' and meta_key='language');");

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

	$cFolder = $campaignData['campaign_folder'];

	$topo = $email;

	$dominio = "labakeca.eu";

	$linkConferma = 'https://' . $dominio . '/signup/' . $cFolder . '/conferma_mail.php?sanit=' . $timestamp . '&e=' . $eid;

	$linguaCorrenteCampagna = $campaignData['txtLang'];

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

		$mailHtmlTitle = "Conferma il tuo indirizzo email";

		$altMailCiao = "Ciao ";

		$txtoggetto = "Iscrizione ";

		$setFrom = 'Ciao ' . $nome . ', grazie per esserti iscritto!';

		$txtTitleComunicazione = "grazie per esserti iscritto su labakeca.eu!";

		$txtBodyComunicazione = "Per confermare la tua iscrizione";

		$txtBtnConf = "Clicca sul seguente link ";

		$txtCancelEmail = "Se non hai creato un account con <a href=\'https://labakeca.eu\'>LaBakeca.eu</a>, puoi tranquillamente cancellare questa e-mail.";

		$txtCopyPasteDirectly = "Se non dovesse funzionare, puoi copiare e incollare il seguente link nel browser: ";

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

		$mailHtmlTitle = "Confirme su dirección de correo electrónico";

		$altMailCiao = "&iexcl;Hola ";

		$txtoggetto = "Inscripciòn ";

		$setFrom = 'Hola  ' . $nome . ', ¡gracias por unirte!';

		$txtTitleComunicazione = "gracias por inscribirte en labakeca.eu!";

		$txtBodyComunicazione = "Para confirmar tu inscripción";

		$txtBtnConf = "Phaz clic en el siguiente enlace";

		$txtCancelEmail = "Si no ha creado una cuenta en <a href=\'https://labakeca.eu\'>LaBakeca.eu</a>, puede eliminar este correo electrónico con total seguridad.";

		$txtCopyPasteDirectly = "Si eso no funciona, copie y pegue el siguiente enlace en su navegador: ";

	} elseif (($linguaCorrenteCampagna == "en")) {
		$mailHtmlTitle = "Confirm your email address";

		$altMailCiao = "Hello ";

		$txtoggetto = "Subscribe ";

		$setFrom = 'Hi ' . $nome . ', thanks for joining!';

		$txtTitleComunicazione = "thank you for signing up on labakeca.eu!";

		$txtBodyComunicazione = "To confirm your subscription";

		$txtBtnConf = "Click on the following link";

		$txtCancelEmail = "If you didn't create an account with <a href=\'https://labakeca.eu\'>LaBakeca.eu</a>, you can safely delete this email.";

		$txtCopyPasteDirectly = "If that doesn't work, you can copy and paste the following link in your browser: ";
	} else {

		$mailHtmlTitle = "Confirm your email address";

		$altMailCiao = "Hello!  ";

		$txtoggetto = "Subscribe";

		$setFrom = 'Hi ' . $nome . ', thanks for joining!';

		$txtTitleComunicazione = "Thank you for signing up on labakeca.eu!";

		$txtBodyComunicazione = "To confirm your subscription,  ";

		$txtBtnConf = "Click on the following link";

		$txtCancelEmail = "If you didn\'t create an account with <a href=\'https://labakeca.eu\'>LaBakeca.eu</a>, you can safely delete this email.";

		$txtCopyPasteDirectly = "If that doesn\'t work, copy and paste the following link in your browser: ";

	}

	if (isset($_SESSION["indir"]) && !empty($_SESSION["indir"]) && !empty($_SESSION["motto"]) && isset($_SESSION["isRegist"]) && !empty($_SESSION["isRegist"]) && $_SESSION["isRegist"] === "no") {

		$topo = $email;
		$gatto = $pwd;

		$webcose = "LaBakeca.eu";

		$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;">
          ' . $mailHtmlTitle . '
        </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;">
                        ' . $mailHtmlTitle . '
                    </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;"><strong> ' . $altMailCiao . $nome . ', ' . $txtTitleComunicazione . '</strong></p>
                  </td>
                </tr>
                <!-- end copy -->
                 <!-- 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;align-content:center;">' . $txtBodyComunicazione . '</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="' . $linkConferma . '" 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;">
                    <p style="margin: 0;">' . $txtCopyPasteDirectly . '</p>
                    <p style="margin: 0;"><a href="' . $linkConferma . '" target="_blank">' . $linkConferma . '</a></p>
                  </td>
                </tr>
                <!-- end copy -->
       <!-- 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;">' . $txtCancelEmail . '</p>
                  </td>
                </tr>
                <!-- end copy -->
                <!-- 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, utf8_decode($txtoggetto) . $webcose);
			$mail->addReplyTo($emailInviatore, utf8_decode($txtoggetto) . $webcose);
			$mail->addAddress($topo);
			$mail->isHTML(true);
			$mail->charset = 'UTF-8';
			$mail->Subject = utf8_decode($setFrom);
			$mail->Body = utf8_decode($mailHtml);
			$mail->altBody = $altMailCiao;
			#$message->addBcc($emailBcc);
			$mail->send();
			// echo 'Message has been sent';
		} catch (Exception $e) {
			//echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
		}

	}

}

?>