<?php
error_reporting(1);
define('INC_PATH',dirname(__FILE__));

// SMTP E-mail sending -------------------->
function sendMail($data=array())
{
    require (INC_PATH.DIRECTORY_SEPARATOR.'PHPMailer'.DIRECTORY_SEPARATOR.'Exception.php');
    require (INC_PATH.DIRECTORY_SEPARATOR.'PHPMailer'.DIRECTORY_SEPARATOR.'PHPMailer.php');
    require (INC_PATH.DIRECTORY_SEPARATOR.'PHPMailer'.DIRECTORY_SEPARATOR.'SMTP.php');

    $default = array(
        'to' => array('linesh@codeatech.com'),
        'sub' => '',
        'message' => '',
        'from_email' => '',
        'from_name' => '',
    );
    $data = array_merge($default,$data);
    $mail = new PHPMailer(true);

    try 
    {
        //Server settings                
        $mail->isSMTP();  
        $mail->isHTML(true);
        $mail->Subject = trim($data['sub']);
        $mail->Priority=1;
        //$mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Debugoutput = 'html'; 
        $mail->Host = 'mail.merchantproinc.com';
		 
        $mail->SMTPAutoTLS=false;
        $mail->SMTPAuth = true; 
        $mail->Port = 587;
        $mail->Username   = 'noreply@merchantproinc.com';
        $mail->Password   = 'Fk1Ys77UEx4m'; 
        $mail->setFrom('noreply@merchantproinc.com','Merchant Pro inc.');
                 
        //Recipients 
        if(is_array($data['to']) && (count($data['to'])>1) )
        {
            foreach($data['to'] as $to){
                $mail_parts=explode('@',$to);
                $mail->addAddress($to,$mail_parts[0]);
            }
        }else{
            $mail_parts=explode('@',$data['to'][0]);
            $mail->addAddress($data['to'][0],$mail_parts[0]);
        }
        $mail->addReplyTo(trim($data['from_email']),trim($data['from_name']));
  
        //Content                             
            $mail->Body    = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
            <html>
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                    <title>Merchant Service & Processing solutions.com</title>
                </head>
                <body>'.trim($data['message']).'</body>
            </html>';
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
        $mail->send();
        return true;

    }catch (Exception $e) {
        echo "{$mail->ErrorInfo}";
        exit;
        return false;
    }
}

// Get webpage content from a url ----------------->
function getSslPage($url) 
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function clean($str=''){
    return trim(htmlentities(htmlspecialchars(strip_tags($str))));
}

if( isset($_POST) && is_array($_POST) &&  (count($_POST)>0) )
{
	//
	if(!empty($_POST['emergency_number'])){
        echo "<p class='Error'>Something went wrong. Please try again later!.</p>";
		exit;
	}
	//
	
    $errors=array();

    if(empty($_POST['first_name'])){
        $errors['first_name'] = "First Name can not be blank.";
    }

    if(empty($_POST['last_name'])){
        $errors['last_name'] = "Last Name can not be blank.";
    }

    // Email Validation ---------------->
    $_POST['email'] = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
    if( empty($_POST['email']) ){
        $errors['email'] = "Email address can not be blank.";

    }elseif(!empty($_POST['email']) && !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
        $errors['email'] = "$email is an invalid email adddress.";
    }

    // Phone Validation ---------------->
    if( empty($_POST['phone']) ){
        $errors['phone'] = "Phone number can not be blank.";

    }elseif (!preg_match('/([0-9\s\-]{6,})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/', $_POST['phone'])) {
        $errors['phone'] = $_POST['phone']." is an invalid phone number.";

    }else if(strlen($_POST['phone'])>=20){
        $errors['phone'] = $_POST['phone']." is an invalid phone number.";
    }

    if(empty($_POST['country'])){
        $errors['country'] = "Country can not be blank.";
    }

    if(empty($_POST['type'])){
        $errors['type'] = "Account type can not be blank.";
    }

    if(empty($_POST['firm-location'])){
        $errors['firm-location'] = "Firm Location can not be blank.";
    } 



    //captcha Validation ---------------->
    if(isset($_POST['g-recaptcha-response']))
    {
        if( empty(clean($_POST['g-recaptcha-response']))){
            $errors['captcha'] = "Captcha is missing.";
        }else{
            $secret= '6LehQYQpAAAAAGx_DdIxEZWDNnaYHYXWwxWoBcGU';
            $recaptcha=clean($_POST['g-recaptcha-response']);
            $url="https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptcha."&remoteip=".$_SERVER['REMOTE_ADDR'];
            $response=(array)json_decode(getSslPage($url));
            if(isset($response['success']) &&  ($response['success']!='true') ){
                if( in_array('timeout-or-duplicate',$response['error-codes'])){
                     $errors['captcha'] = "Timeout or Duplicate captcha given.";
                }else{
                    $errors['captcha'] = "Invalid captcha given.";
                }
            }
        }
    }
        
    if(count($errors)==0)
    {     
        $type = (clean($_POST['type']) == "new") ? "New Merchant Account" : "Existing Merchant Account";

        $html = "<table border='1' cellpadding='10'>";
        $html .= "<tr><td><strong>Account Type:</strong> </td><td style='border: none;'>".$type."</td></tr>";
        $html .= "<tr><td>Name:</td><td>".clean($_POST['first_name'])." ".clean($_POST['last_name'])."</td></tr>";
        $html .= "<tr><td>Phone Number:</td><td>".clean($_POST['phone'])."</td></tr>";
        $html .= "<tr><td>Email address:</td><td>".clean($_POST['email'])."</td></tr>";
        $html .= "<tr><td>Country:</td><td>".clean($_POST['country'])."</td></tr>";
        $html .= "<tr><td>Firm Location:</td><td style='border:none;'>" . clean($_POST['firm-location']) . "</td></tr>";
        $html .= "<tr><td>Message:</td><td>".clean($_POST['message'])."</td></tr>";
        $html .= "<tr><td>IP Address:</td><td>".$_SERVER['REMOTE_ADDR']."</td></tr>";
        $html .= "</table><br /><br />";
        $html .= "Thank you,<br />";
        $html .= 'Merchantproinc.com';
        $data=array(
            'to'=>array('corpaccounts@merchantproinc.com'),
            'sub'=>'Quote Request - Merchantproinc.com',
            'message'=>$html,
            'from_email'=>clean($_POST['email']),
            'from_name'=>clean($_POST['name'])
        );
        if(sendMail($data)){           
            echo "<p class='success'>Thank you for contacting us. We’ll get back to you very soon!</p>";
        }else{
            echo "<p class='Error'>Something went wrong. Please try again later.</p>";
        }
    }else{
        echo '<p class="Error">'.implode('<br>',$errors).'</p>';
    }
}else{
    header('Location: ./'); 
} 
exit;
?>