<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'smtp/vendor/autoload.php';

if(isset($_POST['data']))
{
    parse_str($_POST['data'], $data);
    $name = $data['first_name'];
    $surename = $data['last_name'];
    $email = $data['emailadd'];
    $phone = $data['phone'];
    $location = $data['studio1'];

    $conn = new mysqli("localhost", "f45_form","f45_form", "f45_form");
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
 
    $sql = "INSERT INTO event4 (name, surename, email,phone,location)
    VALUES ('$name','$surename','$email','$phone','$location')";

    if ($conn->query($sql) === TRUE) {
        send_mail($email,$location);
      echo 1;
    } else {
      echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
}

function send_mail($email,$loc)
{
    	$mail = new PHPMailer(true);
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'infof45@ahg.af';                     // SMTP username
    $mail->Password   = 'lsaonsuhvwclualr';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 465;   
	$mail->SMTPSecure = 'ssl';
	$mail->CharSet = 'UTF-8';
	$mail->Encoding = 'quoted-printable';    	// TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom('event@f45.af', 'F45 Event');
    $mail->addAddress($email);     // Add a recipient
    if($loc == "north")
    {
        $mail->addCC('obaidullah.raheal@ahg.af');
        $mail->addCC('reshad.walizada@ahg.af');
        $mail->addCC('shahram.ahmadyaan@ahg.af');
        $mail->addCC('samir.zohab@ahg.af ');
    }
    else
    {
        $mail->addCC('obaidullah.raheal@ahg.af');
        $mail->addCC('sabria.daqiq@ahg.af');
        $mail->addCC('pasoon.sediqi@ahg.af');
        $mail->addCC('samir.zohab@ahg.af ');
    }

    // Attachments
    //$mail->addAttachment('card.jpg');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = "کارت دعوت به برنامه  F45";
    $mail->Body    = "<p style='direction:rtl;text-align:right;font-size:19px;font-weight:bold'>تشکر از علاقمندی تان به برنامه F45 ، منتظر دیدار شما هستیم.</p><br><img width='100%' src='https://f45.af/event/smtp/event3.png'>";

    $mail->send();
}