<?php 
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
require 'phpmailer/src/Exception.php';


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
   
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$name = htmlspecialchars($_POST['name']);
    $email = htmlspecialchars($_POST['email']);
     $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $product = $_POST['product'];
    $message = $_POST['message'];
    
    // save lead to db
$host = "localhost";
$username = "collinsg_camgtpu";
$password = "dh+z9*R*V0mR";
$database = "collinsg_camgtpu";
try {
    // Create a PDO database connection
    $pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);

    // Set the PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Retrieve form data
    $name = $_POST["name"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];
    $address = $_POST["address"];
    $product = $_POST["product"];
    

    // SQL query to insert the lead into the database
    $sql = "INSERT INTO campaignleads (customername, customeremail, customerphone,customercountry,customerproduct) VALUES (:name, :email, :phone,:address,:product)";

    // Prepare the SQL statement
    $stmt = $pdo->prepare($sql);

    // Bind parameters
    $stmt->bindParam(':name', $name, PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, PDO::PARAM_STR);
    $stmt->bindParam(':phone', $phone, PDO::PARAM_STR);
    $stmt->bindParam(':address', $address, PDO::PARAM_STR);
    $stmt->bindParam(':product', $product, PDO::PARAM_STR);

    // Execute the statement
    $stmt->execute();

    // echo "Lead inserted successfully.";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// Close the database connection
$pdo = null;

if(empty($_SERVER['HTTP_REFERER'])) {
            echo json_encode(['success' => false, 'message' => 'Error']);
}else{
    if(!empty($_POST['email'])) {
        $postData="";
		foreach ($_POST as $key => $value) {
			if(!empty($postData)) {
				$postData .="||";
			}
			$postData .= $key."~~".$value;
		}
		$data_string = json_encode($postData); 
		$headers = array ("Authorization:SG#^TP152K@NP#RG5R","Content-Type: application/json");  
		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_URL, "https://webdx.webixytools.com/catalog/contactus_inq.php");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
		$result = curl_exec($ch);
		curl_close ($ch);
    }
}

    // save lead to db
    
// 	if (empty($name) || empty($email) || empty($message)) {
//         echo json_encode(['success' => false, 'message' => 'All fields are required.']);
//         exit;
//     }

	$mail = new PHPMailer(true);
	try {
        // SMTP server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.hostinger.com'; // Your SMTP host (e.g., smtp.gmail.com)
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@gtplazacrm.com'; // SMTP username
        $mail->Password = '?0qL^A9*'; // SMTP password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Encryption (STARTTLS/SSL)
        $mail->Port = 587; // SMTP port (TLS typically uses 587)

        // Email settings
        $mail->setFrom('shrish@gtplazacrm.com', 'Campaigns Global Trade Plaza');
        $mail->addAddress($email, $name);
        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Global Trade Plaza!';
        $mail->Body = '<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to Global Trade Plaza!</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }
    .email-container {
      max-width: 800px;
      margin: 0 auto;
      background-color: #ffffff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0px 0px 1px 0px red, 0px 4px 0px -4px red;
    }
    .header {
      background-color: #004aad;
      padding: 10px;
      text-align: center;
      border-radius: 8px 8px 0 0;
      color: white;
    }
    .header h1 {
      margin: 0;
      font-size: 24px;
    }
    .content {
      padding: 20px;
      line-height: 1.6;
      color: #333;
    }
    .content h2 {
      font-size: 22px;
      color: #004aad;
    }
    .content p {
      margin: 10px 0;
    }
    .cta {
      background-color: #004aad;
      color: white;
      text-decoration: none;
      padding: 10px 20px;
      border-radius: 5px;
      display: inline-block;
      margin-top: 20px;
    }
    .footer {
      padding: 20px;
      font-size: 14px;
      color: #777;
    }
    .footer a {
      color: #004aad;
      text-decoration: none;
    }
  </style>
</head>
<body>
  <div class="email-container">
    <div class="header">
      <a href="https://globaltradeplaza.com/"><img src="https://globaltradeplaza.net/campgtp/image/email-GTP-logo-Trade-Mark.webp" width="180" height="40" alt="Global Trade Plaza" title="Global Trade Plaza
		"></a>
    </div>

    <div class="content">
      <h2>Dear '.$name.',</h2>
      <p>It is a pleasure to be at your service! We are thrilled to receive your message and are excited to have the opportunity to work with you.</p>
      
      <p>Our team is dedicated to providing you with exceptional service and cut-to-the-chase strategies for your business needs. We will get back to you shortly.</p>
      
      <p>However, if you have any immediate questions or requirements, feel free to contact us directly via WhatsApp.</p>
      
      <p style="font-weight:bold">We are looking forward to our future partnership.</p>
      
    </div>

    <div class="footer">
      <p>Best Regards,<br><b>Global Trade Plaza</b></p>
      <p><strong>WhatsApp:</strong> <a href="https://wa.me/+918303334614">https://wa.me/+918303334614</a></p>
      <p><strong>Phone:</strong> 8429088885, 9235297990</p>
      <p><strong>Email:</strong> <a href="mailto:support@globaltradeplaza.com">support@globaltradeplaza.com</a></p>
      <p><strong>Website:</strong> <a href="https://globaltradeplaza.com/">https://globaltradeplaza.com/</a></p>
      <p><strong>Address:</strong> Second Floor, 13/391, Green Park, Civil Lines, Kanpur, Uttar Pradesh, India 208001</p>
    </div>
  </div>
</body>
</html>';

        $mail->send();
        echo json_encode(['success' => true, 'message' => 'Email sent successfully.']);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Failed to send email. Error: ' . $mail->ErrorInfo]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>