<?php
// Include DB config (PDO connection)
include("adminpanel/config.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data safely
    $name    = trim($_POST['name']);
    $email   = trim($_POST['email']);
    $subject = trim($_POST['subject']);
    $message = trim($_POST['message']);

    // Get user details
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $submitted_at = date("Y-m-d H:i:s");

    try {
        // Insert query with prepared statement (PDO)
        $sql = "INSERT INTO contact_form (name, email, subject, message, ip_address, user_agent, submitted_at) 
                VALUES (:name, :email, :subject, :message, :ip_address, :user_agent, :submitted_at)";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            ':name'        => $name,
            ':email'       => $email,
            ':subject'     => $subject,
            ':message'     => $message,
            ':ip_address'  => $ip_address,
            ':user_agent'  => $user_agent,
            ':submitted_at'=> $submitted_at
        ]);

        // Send email to admin
        $to = "yourgmail@gmail.com"; // change to your Gmail
        $headers  = "From: $email\r\n";
        $headers .= "Reply-To: $email\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

        $body = "
        <h2>New Contact Form Submission</h2>
        <p><strong>Name:</strong> $name</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Subject:</strong> $subject</p>
        <p><strong>Message:</strong><br>$message</p>
        <p><strong>IP:</strong> $ip_address</p>
        <p><strong>User Agent:</strong> $user_agent</p>
        <p><strong>Submitted At:</strong> $submitted_at</p>
        ";

        mail($to, "New Contact: $subject", $body, $headers);

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

    } catch (PDOException $e) {
        echo "Error saving data: " . $e->getMessage();
    }
}
?>
