<?php
/*
Adapted from the old site's mailerhome/contact-2.php (same library, same
recipient, same behavior) — sends the homepage "Request Quote" / Contact Us
enquiry form to DNA of Excellence Group.
*/

require __DIR__ . '/PHPMailer-master/PHPMailerAutoload.php';

$fromEmail = 'dnaconsultanceys@gmail.com';
$fromName = 'Enquiry';

$sendToEmail = 'dnaconsultanceys@gmail.com';
$sendToName = 'DNA of Excellence - Enquiry';

$subject = 'New message from DNA - Enquiry';

// form field names and their translations.
$fields = array(
    'name' => 'Name',
    'email' => 'Email',
    'number' => 'Phone',
    'cmpny' => 'Company Name',
    'msg' => 'Message',
);

$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';

error_reporting(E_ALL & ~E_NOTICE);
header('Content-Type: application/json');

try {
    if (count($_POST) == 0) {
        throw new \Exception('Form is empty');
    }

    $replyToEmail = isset($_POST['email']) ? $_POST['email'] : $fromEmail;

    $emailTextHtml = "<h1>You have a new Enquiry from DNA Website</h1><hr>";
    $emailTextHtml .= "<table>";
    foreach ($_POST as $key => $value) {
        if (isset($fields[$key])) {
            $safeValue = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
            $emailTextHtml .= "<tr><th style='text-align:left;'>{$fields[$key]}</th><td> : $safeValue</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a nice day,<br>Best Regards,<br>DNA</p>";

    $mail = new PHPMailer;
    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($replyToEmail);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->msgHTML($emailTextHtml);

    if (!$mail->send()) {
        throw new \Exception('Could not send the email: ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
    http_response_code(500);
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

echo json_encode($responseArray);
