<?php
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
    //your site secret key
    $secret = '6LcNdTUUAAAAAL5VYxoCX2itVnaooUjEN-XFJ_iq';
    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $_POST['g-recaptcha-response']);
    $responseData = json_decode($verifyResponse);
    if ($responseData->success) {
        session_start();
        $conn = mysql_connect("localhost", "skynetuser", "SkynetUserBlog2017$");
        mysql_select_db("skynet_blog", $conn);
        require("class.phpmailer.php");
        include("class.smtp.php");
        $redirect_url = '../supportthanks.html';
//$your_email ='rajesh@skynetindia.info';// <<=== update to your email address
        $your_email = 'rajesh@skynetindia.info';// <<=== update to your email address
//$your_email ='developer4@skynetindia.info';// <<=== update to your email address
        $attachment_enabled = 1;
        $autoresponder_enabled = 1;

        $fileallow = array('png', 'jpeg', 'jpg', 'gif', 'doc', 'docx', 'xlsx', 'xls', 'csv', 'rtf', 'pdf', 'zip', 'gzip', 'rar');

//***
# the response from reCAPTCHA
        $resp = null;
# the error code from reCAPTCHA, if any
        $error = null;

        if ($_POST["g-recaptcha-response"]) {
            $_POST['IP'] = $_SERVER["REMOTE_ADDR"];
            $_POST['Date'] = date('d-m-Y H:i:s');
//********SMS TO US
            $reg_no = rand(0, 9999);
            $ch = curl_init();
            $reseller = "rajesh@skynetindia.info";
            $user = "admin@wealthadvisory.in:R3M3L";
            $receipientno = "9824407292";

//$senderID="WEALTH";
            $senderID = "SKYNET";
            $msgtxt = "New Query with Ref. No. " . $reg_no . " , Phone: " . $_POST['PhoneNo'] . " , Email: " . $_POST['email_from'];
            curl_setopt($ch, CURLOPT_URL, "59.162.167.52/api/MessageCompose");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, "reseller=$reseller&user=$user&senderID=$senderID&receipientno=$receipientno&msgtxt=$msgtxt&state=0");
            $buffer = curl_exec($ch);
            if (empty ($buffer)) {
// echo " buffer is empty "; 
            } else {
// echo $buffer; 
            }
            curl_close($ch);


//**********SMS TO USER

            $ch = curl_init();
            $reseller = "rajesh@skynetindia.info";
            $user = "admin@wealthadvisory.in:R3M3L";
            $receipientno = $_POST['PhoneNo'];
            $senderID = "SKYNET";
            $msgtxt = "Hello " . $_POST['Contact_Person'] . " , Thank You for your Query, Your Reference Number is " . $reg_no . " .";
            curl_setopt($ch, CURLOPT_URL, "59.162.167.52/api/MessageCompose");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, "reseller=$reseller&user=$user&senderID=$senderID&receipientno=$receipientno&msgtxt=$msgtxt&state=0");
            $buffer = curl_exec($ch);
            if (empty ($buffer)) {
//echo " buffer is empty "; 
            } else {
//echo $buffer;
            }
            curl_close($ch);
            function crmcall($method, $parameters, $url)
            {
                ob_start();
                $curl_request = curl_init();

                curl_setopt($curl_request, CURLOPT_URL, $url);
                curl_setopt($curl_request, CURLOPT_POST, 1);
                curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
                curl_setopt($curl_request, CURLOPT_HEADER, 1);
                curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);

                $jsonEncodedData = json_encode($parameters);

                $post = array(
                    "method" => $method,
                    "input_type" => "JSON",
                    "response_type" => "JSON",
                    "rest_data" => $jsonEncodedData
                );

                curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post);
                $result = curl_exec($curl_request);
                curl_close($curl_request);

                $result = explode("\r\n\r\n", $result, 2);
                $response = json_decode($result[1]);
                ob_end_flush();

                return $response;
            }
            function get_form_data()
            {

                global $REQUEST_METHOD;

                global $_POST;

                global $_GET;

                global $reg_no;


                $vars = ($REQUEST_METHOD == 'GET') ? $_GET : $_POST;
                //echo "<pre>";
                //print_r($vars);
                //die();

                ///insert to database
                $insert = "INSERT INTO `request_quote_data` (`reg_no`, `company_name`, `contact_person`, `email_from`, `phoneno`, `city_state`, `country`, `tell_us`, `new_website`, `weburl`, `have_a_logo`, `website_upgrades1`, `website_upgrades2`, `website_upgrades3`, `website_upgrades4`, `website_upgrades5`, `website_upgrades6`, `website_upgrades7`, `website_upgrades8`, `anything`, `referenceurl`, `date`) VALUES ('" . $reg_no . "','" . mysql_real_escape_string($vars['Company_Name']) . "','" . mysql_real_escape_string($vars['Contact_Person']) . "','" . mysql_real_escape_string($vars['email_from']) . "','" . mysql_real_escape_string($vars['PhoneNo']) . "','" . mysql_real_escape_string($vars['City-State']) . "','" . mysql_real_escape_string($vars['Country']) . "','" . mysql_real_escape_string($vars['Tell_us']) . "','" . mysql_real_escape_string($vars['New_Website']) . "','" . mysql_real_escape_string($vars['weburl']) . "','" . mysql_real_escape_string($vars['have_a_logo']) . "','" . mysql_real_escape_string($vars['Website_Upgrades1']) . "','" . mysql_real_escape_string($vars['Website_Upgrades2']) . "','" . mysql_real_escape_string($vars['Website_Upgrades3']) . "','" . mysql_real_escape_string($vars['Website_Upgrades4']) . "','" . mysql_real_escape_string($vars['Website_Upgrades5']) . "','" . mysql_real_escape_string($vars['Website_Upgrades6']) . "','" . mysql_real_escape_string($vars['Website_Upgrades7']) . "','" . mysql_real_escape_string($vars['Website_Upgrades8']) . "','" . mysql_real_escape_string($vars['Anything_else_we_should_know_about_project']) . "','" . mysql_real_escape_string($vars['ReferenceUrl']) . "','" . mysql_real_escape_string($vars['Date']) . "');";

                $res = mysql_query($insert);
                $url = "http://suitecrm.bcabook.com/service/v4_1/rest.php";
                $username = "admin";
                $password = "Skynet@007";  $upgrade="";
                //function to make cURL request

                if(empty($upgrade)){
                    for($i=1;$i<=9;$i++){
                        $upgrade.=!empty($vars['Website_Upgrades'.$i])?$vars['Website_Upgrades'.$i].", ":null;
                    }
                    $upgrade=trim($upgrade,", ");
                }
                //login ---------------------------------------------
                $login_parameters = array(
                    "user_auth" => array(
                        "user_name" => $username,
                        "password" => md5($password),
                        "version" => "1"
                    ),
                    "application_name" => "suitecrm",
                    "name_value_list" => array(),
                );

                $login_result = crmcall("login", $login_parameters, $url);
                $customerName=mysql_real_escape_string($vars['Contact_Person']);
                $customerarr=explode(" ",$customerName);
                if(count($customerarr)>0){
                    $last_name=end($customerarr);
                    $first_name=str_replace($last_name,'',$customerName);
                }else{
                    $last_name=$customerName;
                    $first_name='';
                }
                //get session id
                $session_id = $login_result->id;
                $description = "Company name:  " . mysql_real_escape_string($vars['Company_Name']) . "\r\n\r\n Business Summary:  " . mysql_real_escape_string($vars['Tell_us']) . "\r\n\r\n Website Type: " .  mysql_real_escape_string($vars['New_Website']);
                if (!empty(mysql_real_escape_string($vars['weburl']))) {
                    $description .= "\r\n\r\n Existing Website: " . mysql_real_escape_string($vars['weburl']);
                }
                $description .= "\r\n\r\n Website Upgrade: " . $upgrade . "\r\n\r\n Additional Comment: " . mysql_real_escape_string($vars['Anything_else_we_should_know_about_project']) . "\r\n\r\n Reference URL: " . mysql_real_escape_string($vars['ReferenceUrl']);
                //create account -------------------------------------
                $set_entry_parameters = [
                    //session id
                    "session" => $session_id,
                    //The name of the module from which to retrieve records.
                    "module_name" => "Leads",
                    //Record attributes
                    "name_value_list" => [

                        ['name' => 'first_name', 'value' => $first_name],
                        ['name' => 'last_name', 'value' => $last_name],
                        ['name' => 'status', 'value' => 'New'],
                        ['name' => 'phone_work', 'value' => mysql_real_escape_string($vars['PhoneNo'])],
                        ['name' => 'email1', 'value' => mysql_real_escape_string($vars['email_from'])],
                        ['name' => 'account_name', 'value' => mysql_real_escape_string($vars['Company_Name'])],
                        ['name' => 'lead_source', 'value' => 'Web Site'],
                        ["name" => "lead_source_description", "value" => "Lead Generated from https://www.skynetindia.info"],
                        ["name" => "primary_address_country", "value" => mysql_real_escape_string($vars['Country'])],
                        ["name" => "primary_address_state", "value" => mysql_real_escape_string($vars['City-State'])],
                        ['name' => 'description', 'value' => $description]
                    ],
                ];

                $set_entry_result = crmcall("set_entry", $set_entry_parameters, $url);


                //strip spaces from all fields

                foreach ($vars as $k => $v) $vars[$k] = trim($v);

                return $vars;

            }


            function _build_fields($vars)
            {

                $skip_fields = array(
                    'Submit',
                    'recaptcha_challenge_field', 'recaptcha_response_field');

                // order by numeric begin, if it exists

                $is_ordered = 0;

                foreach ($vars as $k => $v)

                    if (in_array($k, $skip_fields)) unset($vars[$k]);


                $new_vars = array();

                foreach ($vars as $k => $v) {

                    // remove _num, _reqnum, _req from end of field names

                    $k = preg_replace('/_(req|num|reqnum)$/', '', $k);

                    // check if the fields is ordered

                    //if (preg_match('/^\d+[ \:_-]/', $k)) $is_ordered++;

                    //remove number from begin of fields

                    $k = preg_replace('/^\d+[ \:_-]/', '', $k);

                    $new_vars[$k] = $v;

                }

                $vars = $new_vars;


                $max_length = 10; // max length of key field

                foreach ($vars as $k => $v) {

                    $klen = strlen($k);

                    if (($klen > $max_length) && ($klen < 40))

                        $max_length = $klen;

                }


                if ($is_ordered)

                    ksort($vars);


                // make output text

                $out = "";

                foreach ($vars as $k => $v) {
                    if (is_array($v)) {
                        foreach ($v as $kk => $vv) {
                            $kk = str_replace('_', ' ', $kk);
                            $kk = ucfirst($kk);
                            $len_diff = $max_length - strlen($kk);
                            if ($len_diff > 0)
                                $fill = str_repeat('.', $len_diff);
                            else
                                $fill = '';
                            $out .= $kk . "$fill...: $vv\n\n";
                        }
                    } else {
                        $k = str_replace('_', ' ', $k);
                        $k = ucfirst($k);
                        $len_diff = $max_length - strlen($k);
                        if ($len_diff > 0)
                            $fill = str_repeat('.', $len_diff);
                        else
                            $fill = '';
                        $out .= $k . "$fill...: $v\n\n";
                    }
                }

                return $out;

            }


            $vars = get_form_data();
            $out = _build_fields($vars);
            $body = "A user  $name submitted the form:\n\n" . $out;
//Auto Responser Function To Send Auto Respond


            $autoresponder_from = $your_email;

            $subject = "site feedback from skynetindia.info";

            $autoresponder_subject = "%subject% (autoresponse) from skynetindia.info";

            $autoresponder_message = <<<MSG

Hi %Contact Person%,



Thank you for submitting the form.

--

MSG;


            function auto_respond($vars)
            {

                global $autoresponder_from, $autoresponder_message, $autoresponder_subject;

                /// replace all vars in message

                $msg = $autoresponder_message;

                preg_match_all('/%(.+?)%/', $msg, $out);

                $s_vars = $out[1]; //field list to substitute

                foreach ($s_vars as $k)

                    $msg = str_replace("%$k%", $vars[$k], $msg);

                /// replace all vars in subject

                $subj = $autoresponder_subject;

                preg_match_all('/%(.+?)%/', $subj, $out);

                $s_vars = $out[1]; //field list to substitute

                foreach ($s_vars as $k)

                    $subj = str_replace("%$k%", $vars[$k], $subj);

                //

                $_send_to = "$vars[name] <" . $vars[email_from] . ">";

                $_send_from = $autoresponder_from;

                mail($_send_to, $subj, $msg, "From: $_send_from");

            }

            if (empty($errors)) {
                $mail_php = new PHPMailer();
                $files = array(); //files (field names) to attach in mail
                if ($HTTP_POST_FILES['Company_Document']['name'] != '') {
                    if (count($HTTP_POST_FILES) && $attachment_enabled) {
                        $files = array_keys($HTTP_POST_FILES);
                    }
                    if (count($files)) {

                        foreach ($files as $file) {

                            $file_name = $HTTP_POST_FILES[$file]['name'];
                            $ext = end(explode('.', $file_name));

                            $file_type = $HTTP_POST_FILES[$file]['type'];

                            $file_tmp_name = $HTTP_POST_FILES[$file]['tmp_name'];
                            if ($HTTP_POST_FILES[$file]['size'] > 4000000) {
                                echo "<script type='text/javascript'>alert('file size cannot be greater than 4mb');history.go(-1);</script>";
                                exit;
                            } elseif (!in_array($ext, $fileallow)) {
                                $fileformat = implode(',', $fileallow);
                                echo "<script type='text/javascript'>alert('Please use only $fileformat format');history.go(-1);</script>";
                                exit;
                            }


                            $file_cnt = "";
                            if ($file_name != '') {
                                if (!is_dir('file_inqury'))
                                    mkdir('file_inqury');
                                $file_name = 'file_inqury/' . $file_name;
                                move_uploaded_file($file_tmp_name, $file_name);
                                $mail_php->AddAttachment($file_name);

                            }
                        }

                        //  $mail .= "\n--$mime_delimiter--";

                    }
                } else {
                    $mail = $body;
                }
                //$headers = "Mime-Version: 1.0\r\nFrom: $from \r\nContent-Type: multipart/mixed;\n boundary=\"$mime_delimiter\"\r\nContent-Disposition: inline";
                //$headers .= "Reply-To: $visitor_email \r\n";

                // add attachments
                //$mail->AddAttachment("tmp/image.jpg", "new.jpg");    // optional name

                //send the email
                $to = $your_email;
                $subject = "Enquiry From Skynet Technologies";
                $from = $_POST['email_from'];
                $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

                //SMTP format begin

                $mail_php->IsSMTP();
                $mail_php->CharSet = 'UTF-8';
                // 2 = messages only
                $mail_php->SMTPAuth = true;                  // enable SMTP authentication
                $mail_php->SMTPSecure = "ssl";                 // sets the prefix to the servier
                $mail_php->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
                $mail_php->Port = '465';                   // set the SMTP port for the GMAIL server
                $mail_php->Username = "hr@skynetindia.info";  // GMAIL username
                $mail_php->Password = "sd&*(&*$&#";            // GMAIL password


                $mail_php->From = strip_tags($your_email);
                $mail_php->FromName = "skynet";

                $mail_php->AddAddress($your_email);//


                $mail_php->IsHTML(true);                                  // set email format to HTML

                $vars = get_form_data();
                $database_file = 'email.csv';
                $database_fields = '*';

                $str = _build_fields($vars);
                $mail_php->Subject = "Enquiry From Skynet Technologies";
                $mail_php->Body = nl2br($body);
                //echo $mail->Body;
                $mail_php->AltBody = "test";


                //mail($to,'Enquiry From Skynet Technologies', $mail,$headers);


                // echo "<pre>";//echo $file_name;
                //  echo (htmlentities($mail->Body));exit();
                if (!$mail_php->send()) {
                    echo "Message could not be sent. <p>";
                    echo "Mailer Error: " . $mail_php->ErrorInfo;
                    echo("<SCRIPT LANGUAGE='JavaScript'>
						alert('Someting went wrong.Please contact web-master');
						history.go(-1);
						</SCRIPT>");
                    //header("location:".$_SERVER['HTTP_REFERER']);
                    exit;
                } else {

                    if ($autoresponder_enabled)
                        auto_respond($vars);
                    //echo "Message has been sent";
                    if (count($files)) {
                        foreach ($files as $file) {
                            $file_name = $HTTP_POST_FILES[$file]['name'];
                            $file_name = 'file_inqury/' . $file_name;
                            unlink($file_name);
                        }
                    }


                    header("Location: $redirect_url");
                }

                //header("Location: $redirect_url");
            }


// Function to validate against any email injection attempts
            function IsInjected($str)
            {
                $injections = array('(\n+)',
                    '(\r+)',
                    '(\t+)',
                    '(%0A+)',
                    '(%0D+)',
                    '(%08+)',
                    '(%09+)'
                );
                $inject = join('|', $injections);
                $inject = "/$inject/i";
                if (preg_match($inject, $str)) {
                    return true;
                } else {
                    return false;
                }
            }


        }


    }//end if
    else {
        # set the error code so that we can display it
        $error = $resp->error;
        echo "<script type='text/javascript'>alert('Captcha verify failed');history.go(-1);</script>";
        exit;
    }
}//end if
else {
    # set the error code so that we can display it
    $error = $resp->error;
    echo "<script type='text/javascript'>alert('Captcha verify failed');history.go(-1);</script>";
    exit;
}
?>