<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "adminpanel/config.php"; // PDO connection

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!empty($_POST["company"])) {
        exit("Spam detected!");
    }

    // Collect inputs
    $name    = trim($_POST["name"]);
    $email   = trim($_POST["email"]);
    $phone   = trim($_POST["phone"]);
    $subject = trim($_POST["subject"]);
    $message = trim($_POST["message"]);

    if (empty($name) || empty($email) || empty($phone) || empty($subject) || empty($message)) {
        die("All fields are required.");
    }

    $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

    try {
        $sql = "INSERT INTO contact_messages 
                (name, email, phone, subject, message, ip_address, user_agent, submitted_at) 
                VALUES (:name, :email, :phone, :subject, :message, :ip_address, :user_agent, NOW())";

        $stmt = $conn->prepare($sql);
        $stmt->execute([
            ':name'       => $name,
            ':email'      => $email,
            ':phone'      => $phone,
            ':subject'    => $subject,
            ':message'    => $message,
            ':ip_address' => $ip_address,
            ':user_agent' => $user_agent
        ]);

        // Send email
        $to      = "yourgmail@gmail.com";
        $mail_subject = "New Contact Message: " . $subject;
        $mail_body    = "
        You have received a new contact message:

        Name: $name
        Email: $email
        Phone: $phone
        Subject: $subject
        Message: $message

        IP Address: $ip_address
        User Agent: $user_agent
        ";

        $headers  = "From: no-reply@yourdomain.com\r\n";
        $headers .= "Reply-To: $email\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        mail($to, $mail_subject, $mail_body, $headers);

        // ✅ Redirect back to index.php with success query param
        header("Location: index.php?success=1");
        exit();

    } catch (PDOException $e) {
        echo "Database error: " . $e->getMessage();
    }
} else {
    echo "Invalid request.";
}
?>
