<?php
require_once('includes/config.php');
require_once('includes/PHPMailer/class.phpmailer.php');
require_once('includes/PHPMailer/class.smtp.php');

function sanitize($text) {
    $text = trim($text);
    
    if (get_magic_quotes_gpc()) {
        $text = stripslashes($text);
    }
    return $text;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    $entries = array();
    $errors = array();
    
    // Escape and extract all the post values
    foreach ($_POST as $key => $value) {
        $entries[$key] = sanitize($value);
    }
    
    // Get a set of variable variables for easier use
    foreach ($entries as $key => $value) {
        ${$key} = $value;
    }
    
    // Validate each form field
    if (empty($name)) {
        $errors['name'] = 'Nombre inválido.';
    }
    if (empty($email)) {
        $errors['email'] = 'Email inválido.';
    }
    elseif (!(filter_var($email, FILTER_VALIDATE_EMAIL))) {
        $errors['email'] = 'Escribío mal su email.';
    }
	if (empty($phone)) {
        $errors['phone'] = 'Número de teléfono.';
    }
       
    if (empty($errors)) {
        
        $formOK = true;        
        // Passing true causes PHPMailer to throw exceptions
        $mail = new PHPMailer(true);
        
        try {
            $mail->IsSMTP();
            $mail->SMTPDebug = 0;
            $mail->SMTPAuth = true;
            $mail->SMTPSecure = "ssl";
            $mail->Host = "mail.ampara.com.ar";
            $mail->Port = 465;
            $mail->Username = "comercial@ampara.com.ar";
            $mail->Password = "AmparaCom1210";
			$mail->IsHTML(true);
            $mail->SetFrom($email, $name);
            $mail->Subject = "Contacto Form de AMPARA";
            $mail->Body = "Recibes un mensaje de: <b>$name</b> <p> email: <b>$email</b> <p> Telefono: <b>$phone</b><br><hr><br> <p>Mensaje: <br> <b>$message</b>";
            $mail->AddAddress( 'comercial@ampara.com.ar');
            $mail->Send();
        }
        catch (phpmailerException $e) {
            header("HTTP/1.1 500 Internal Server Error");
            echo "Error inesperado: ".$e->errorMessage();
            exit();
        }
    }
    else {
        $formOK = false;
    }
    
    //if this is not an ajax request  
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){  
        session_start();  
        $return_data = array(
            'formOK'  => $formOK,
            'errors'  => $errors,
            'entries' => $entries
        );
        $_SESSION['return_data']  = $return_data;
        header('Location: ' . BASE_URL);
        exit();
    } 
}
else {
    header('Location: ' . BASE_URL);
    exit();
}