<?php
require 'PHPMailerAutoload.php';

if($_POST) {
  $captcha = '';
  $error = array();

  $name = trim(stripslashes($_POST['contactName']));
  $email = trim(stripslashes($_POST['contactEmail']));
  $subject = trim(stripslashes($_POST['contactSubject']));
  $contact_message = trim(stripslashes($_POST['contactMessage']));
  if(isset($_POST['contactCaptcha'])){
    $captcha = $_POST['contactCaptcha'];
  }

  // Check Name
  if (strlen($name) < 2) {
    $error['name'] = "Please enter your name.";
  }
  // Check Email
  if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
    $error['email'] = "Please enter a valid email address.";
  }
  // Check Message
  if (strlen($contact_message) < 10) {
    $error['message'] = "Please enter your message. It should have at least 10 characters.";
  }
  // Captcha
  if (!$captcha){
    $error['captcha'] = "Please check the CAPTCHA field.";
  } else {
    $captchaResponse = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6Le1wRcTAAAAADbdnvPLKQ_hupTI4jzaGGXFQhQA&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
    if($captchaResponse['success'] == false) {
      $error['captcha'] = "You are a robot.";
    }
  }

  $mail = new PHPMailer;

  //$mail->SMTPDebug = 3;                               // Enable verbose debug output

  $mail->isSMTP();                                      // Set mailer to use SMTP
  $mail->Host = 'smtp.zoho.com;';                       // Specify main and backup SMTP servers
  $mail->SMTPAuth = true;                               // Enable SMTP authentication
  $mail->Username = 'contact@delkappa.com';             // SMTP username
  $mail->Password = '2MR4J&R674b1';                     // SMTP password
  $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
  $mail->Port = 465;                                    // TCP port to connect to

  $mail->setFrom('contact@delkappa.com', $name);
  $mail->addAddress('manos@delkappa.com', 'Manos Katsomallos');     // Add a recipient
  $mail->addReplyTo($email, $name);

  $mail->Subject = $subject;
  $mail->Body    = $contact_message;

  if (!$error) {

    if (!$mail->send()) {
      echo "Something went wrong. Please try again.";
    } else {
      echo "OK";
    }

  } # end if - no validation error

  else {

    $response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
    $response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
    $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
    $response .= (isset($error['captcha'])) ? $error['captcha'] . "<br />" : null;

    echo $response;

  } # end if - there was a validation error

}

?>