<?php
// Load Composer's autoloader (for PHPMailer)
require '../vendor/autoload.php';
include '../db_connect.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Get form data safely
$name = $_POST['name'] ?? '';
$email = $_POST['Email'] ?? '';
$phone = $_POST['Phone'] ?? '';
$service_type = $_POST['service_type'] ?? '';
$message = $_POST['message'] ?? '';

if (empty($name) || empty($email) || empty($message)) {
    echo "<script>alert('Please fill in all required fields.'); window.history.back();</script>";
    exit;
}

// Save to database
$sql = "INSERT INTO contact_form (name, email, phone, service_type, message)
        VALUES ('$name', '$email', '$phone', '$service_type', '$message')";

if ($conn->query($sql) === TRUE) {
    // Send email
    $mail = new PHPMailer(true);
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'benjamindanieljr11@gmail.com'; // 🔹 your Gmail
        $mail->Password = 'tvvvkzlylfgdmcys';   // 🔹 your Gmail app password
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        // Recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('benjamindanieljr11@gmail.com', 'Admin'); // 🔹 your receiving email

        // Content
        $mail->isHTML(true);
        $mail->Subject = "New Contact Message from $name";
        $mail->Body = "
            <h2>New Contact Message</h2>
            <p><strong>Name:</strong> $name</p>
            <p><strong>Email:</strong> $email</p>
            <p><strong>Phone:</strong> $phone</p>
            <p><strong>Service Type:</strong> $service_type</p>
            <p><strong>Message:</strong><br>$message</p>
        ";

        $mail->send();
        echo "<script>alert('Message sent successfully!'); window.location.href='../frontend/index.php';</script>";

    } catch (Exception $e) {
        echo "<script>alert('Message saved, but email not sent: {$mail->ErrorInfo}'); window.location.href='../frontend/index.php';</script>";
    }

} else {
    echo "<script>alert('Database error: {$conn->error}'); window.history.back();</script>";
}

$conn->close();
?>
