<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);

require __DIR__ . '/PHPMailer-master/src/Exception.php';
require __DIR__ . '/PHPMailer-master/src/PHPMailer.php';
require __DIR__ . '/PHPMailer-master/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// ----------------------
// Form Data Receive
// ----------------------
$name       = trim($_POST['name'] ?? '');
$email      = trim($_POST['email'] ?? '');
$phone      = trim($_POST['phone'] ?? '');
$service    = trim($_POST['service'] ?? '');
$message    = trim($_POST['message'] ?? '');
$honeypot   = trim($_POST['website_url'] ?? '');   // Honeypot field

// ----------------------
// HONEYPOT CHECK
// ----------------------
if (!empty($honeypot)) {
    die("Spam detected.");
}

// ----------------------
// VALIDATIONS
// ----------------------

// Name validation
if (!preg_match("/^[A-Za-z ]{2,50}$/", $name)) {
    die("Invalid name.");
}

// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Invalid email.");
}

// Phone validation (exact 10 digits)
if (!preg_match("/^[0-9]{10}$/", $phone)) {
    die("Invalid phone number.");
}

$gmailUser  = 'gaytrisolaruk@gmail.com';
$gmailAppPw = 'lguzifyxavpgyolq';

$mail = new PHPMailer(true);

try {
    // SMTP Settings
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = $gmailUser;
    $mail->Password   = $gmailAppPw;
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // Sender & Receiver
    $mail->setFrom($gmailUser, 'Website Contact Form');
    $mail->addAddress('gaytrisolaruk@gmail.com', 'Gayatri Solar Power');

    // Email Content
    $mail->isHTML(true);
    $mail->Subject = "New Inquiry from Website - $name";

    $mail->Body = "
        <h3>New Inquiry Received</h3>
        <p><strong>Name:</strong> $name</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Phone:</strong> $phone</p>
        <p><strong>Service:</strong> $service</p>
        <p><strong>Message:</strong> $message</p>
    ";

    $mail->AltBody = "New Inquiry:
    Name: $name
    Email: $email
    Phone: $phone
    Service: $service
    Message: $message";

    // Send email
    $mail->send();
    header("Location: thanku.php");
    exit();

} catch (Exception $e) {
    echo "error: {$mail->ErrorInfo}";
}
?>
