<?php
require("sendgrid-php/sendgrid-php.php");
include("use.php");

$Email = Trim(stripslashes($_POST['Email'])); // Collecting the users email
$EmailTo = "jmcruzd@gmail.com"; // Your email address to receive the message.
$Subject = "Contacto"; // Subject of the email
$Name = Trim(stripslashes($_POST['Name'])); // Collecting the users Name

// If statement checking whether the users email is valid
if (strpos($Email, '@') === false && strpos($Email, '.') === false) {
header("Location: https://happygo.cl/contacto/sender/contact-form/"); // Web address of your contact page
exit();
}

$Message = Trim(stripslashes($_POST['Message'])); // Collecting users message

// Validation
$validationOK=true;
if (!$validationOK) {
//print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
header("Location: https://happygo.cl/contacto/sender/contact-form/enviado.php");
exit;
}

// Prepare email body text.
// Can be concatenated but this is easier to read.
$Body = "";
$Body .= "Hello";
$Body .= "/n";
$Body .= "Thank you for contacting us. We have received your message and we aim to get back to you as soon as possible.";
$Body .= "Your enquiry: ";
$Body .= "\n";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";

// Function to send the email.
// Attached to a variable so it can it can be checked in an if statement later.
//$success = mail($EmailTo, $Subject, $Body, "From: <$Email>");

$from = new SendGrid\Email('IOT', "noreply@happygo.cl");
$subject = "Confirmacion Cuenta";
$to = new SendGrid\Email(null, $EmailTo);
$content = new SendGrid\Content("text/html", $Body);
$mail = new SendGrid\Mail($from, $Subject, $to, $content);

//$apiKey = getenv($key);
$apiKey = $key;
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);


   
   /*if($response->statusCode()==202){

   }*/

// If statement to check if the email was sent.
// Redirect to the url you will enter on line 47 instead of the #.
if($response->statusCode()==202){
//print "<meta http-equiv=\"refresh\" content=\"0;URL=#.php\">";
header("Location: https://happygo.cl/contacto/sender/contact-form/enviado.php"); // Web address of your contact page
exit();
}
else{
//print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
header("Location: https://happygo.cl/contacto/sender/contact-form/enviado.php");
}

?>
