<?php
ini_set('display_errors', 1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


require 'phpmailer/src/Exception.php';

require 'phpmailer/src/PHPMailer.php';

require 'phpmailer/src/SMTP.php';
require 'smtp-config.php';

/* ==========================================
   ALLOW POST ONLY
========================================== */

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: ../");
    exit;
}


/* ==========================================
   SANITIZE DATA
========================================== */

$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone'] ?? '');
$interest_type = trim($_POST['interest_type'] ?? '');

$utm_source = trim($_POST['utm_source'] ?? '');
$utm_medium = trim($_POST['utm_medium'] ?? '');
$utm_campaign = trim($_POST['utm_campaign'] ?? '');

$ip_address = $_SERVER['REMOTE_ADDR'];
$date_time = date('d M Y h:i A');


/* ==========================================
   BASIC VALIDATION
========================================== */

if (
    empty($name) ||
    empty($email) ||
    empty($phone)
) {

    die("Required fields missing.");
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

    die("Invalid email address.");
}

if (!preg_match('/^[0-9]{10}$/', $phone)) {

    die("Invalid phone number.");
}


/* ==========================================
   GOOGLE RECAPTCHA VERIFY
========================================== */

$recaptcha_secret = RECAPTCHA_SECRET_KEY;

$recaptcha_response = $_POST['g-recaptcha-response'] ?? '';

if (empty($recaptcha_response)) {

    die("reCAPTCHA verification failed.");
}

$verify_url = "https://www.google.com/recaptcha/api/siteverify";

$response =
    file_get_contents(
        $verify_url . "?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response
    );

$response_data = json_decode($response);

if (!$response_data->success) {

    die("Invalid reCAPTCHA.");
}

/* ==========================================
   Anarock CRM integration
========================================== */

$current_time = time();

$message = (string)$current_time;

$hash = hash_hmac( 'sha256', $message, ANAROCK_AUTH_KEY );

$country_code = "IN";

$campaign_id = ANAROCK_CAMPAIGN_ID;

$postFields = http_build_query([

    'name' => $name,
    'email' => $email,
    'source' => $utm_source,
    'sub_source' => $utm_campaign,
    'purpose' => 'buy',
    'current_time' => $current_time,
    'phone' => $phone,
    'country_code' => $country_code,
    'hash' => $hash,
    'campaign_id' => $campaign_id

]);

$ch = curl_init();

curl_setopt_array($ch,[

    CURLOPT_URL => 'https://lead.anarock.com/api/v0/LandingPage/sync-lead',

    CURLOPT_POST => true,

    CURLOPT_POSTFIELDS => $postFields,

    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_SSL_VERIFYPEER => true

]);

$anarock_response = curl_exec($ch);

// echo '<pre>';
// print_r($anarock_response);
// die();

$http_code =
    curl_getinfo(
        $ch,
        CURLINFO_HTTP_CODE
    );

curl_close($ch);



/* ==========================================
   ADMIN EMAIL BODY
========================================== */

$admin_message = "

<h2>New Enquiry Received</h2>

<table border='1' cellpadding='10' cellspacing='0' width='100%'>

<tr>
<td><strong>Name</strong></td>
<td>{$name}</td>
</tr>

<tr>
<td><strong>Email</strong></td>
<td>{$email}</td>
</tr>

<tr>
<td><strong>Phone</strong></td>
<td>{$phone}</td>
</tr>

<tr>
<td><strong>Interest Type</strong></td>
<td>{$interest_type}</td>
</tr>

<tr>
<td><strong>UTM Source</strong></td>
<td>{$utm_source}</td>
</tr>

<tr>
<td><strong>UTM Medium</strong></td>
<td>{$utm_medium}</td>
</tr>

<tr>
<td><strong>UTM Campaign</strong></td>
<td>{$utm_campaign}</td>
</tr>

<tr>
<td><strong>IP Address</strong></td>
<td>{$ip_address}</td>
</tr>

<tr>
<td><strong>Date</strong></td>
<td>{$date_time}</td>
</tr>

</table>

";


/* ==========================================
   USER EMAIL BODY
========================================== */

$user_message = "

<h2>Thank You For Your Interest</h2>

<p>Dear {$name},</p>

<p>
Thank you for submitting your enquiry.
</p>

<p>
Our team has successfully received your details
and will contact you shortly.
</p>

<p>
We appreciate your interest.
</p>

<br>

<p>
Regards,<br>
Sales Team
</p>

";


/* ==========================================
   SEND MAILS
========================================== */

try {

    /* ==========================
       ADMIN MAIL
    ========================== */

    $mail = new PHPMailer(true);

    $mail->isSMTP();

    $mail->Host = SMTP_HOST;
    $mail->SMTPAuth = true;
    $mail->Username = SMTP_USERNAME;
    $mail->Password = SMTP_PASSWORD;

    $mail->SMTPSecure =
        PHPMailer::ENCRYPTION_STARTTLS;

    $mail->Port = SMTP_PORT;

    $mail->setFrom(
        FROM_EMAIL,
        FROM_NAME
    );

    $mail->addAddress(
        ADMIN_EMAIL
    );

    $mail->isHTML(true);

    $mail->Subject =
        "New Enquiry Received";

    $mail->Body =
        $admin_message;

    $mail->send();



    /* ==========================
       USER MAIL
    ========================== */

    $userMail = new PHPMailer(true);

    $userMail->isSMTP();

    $userMail->Host = SMTP_HOST;
    $userMail->SMTPAuth = true;

    $userMail->Username =
        SMTP_USERNAME;

    $userMail->Password =
        SMTP_PASSWORD;

    $userMail->SMTPSecure =
        PHPMailer::ENCRYPTION_STARTTLS;

    $userMail->Port =
        SMTP_PORT;

    $userMail->setFrom(
        FROM_EMAIL,
        FROM_NAME
    );

    $userMail->addAddress(
        $email,
        $name
    );

    $userMail->isHTML(true);

    $userMail->Subject =
        "Thank You For Your Interest";

    $userMail->Body =
        $user_message;

    $userMail->send();



    /* ==========================
       SUCCESS
    ========================== */

    header(
        "Location: ../thank-you.php"
    );

    exit;

} catch (Exception $e) {

    echo "Mailer Error: "
        . $e->getMessage();

    exit;
}