<?php
/*
Adapted from the old site's mailer/contact-2.php (same library, same
recipient, same behavior) — sends the Registration page form to
DNA of Excellence Group.
*/

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

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

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

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

// form field names and their translations.
$fields = array(
    'Name' => 'Name',
    'dob' => 'Date Of Birth',
    'institution' => 'Institution/Company',
    'course1' => 'Name of the course(s) you preferred to join',
    'course12' => 'Course 2',
    'Phone' => 'Phone',
    'mobile' => 'Mobile',
    'email' => 'Email',
    'alternate' => 'Alternate Email',
    'mailing' => 'Mailing Address',
    'fname' => "Friend's Name",
    'email1' => "Friend's Email",
    'remarks' => 'Remarks',
    'contact' => 'Contact Number',
);

$okMessage = 'Registration 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 Registration from DNA</h1><hr>";
    $emailTextHtml .= "<table>";
    foreach ($_POST as $key => $value) {
        if (isset($fields[$key]) && $value !== '') {
            $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);
