<?php
require_once __DIR__ . "/db.php";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Sanitize and validate input
    $name = mysqli_real_escape_string($mysqli, trim($_POST['name'] ?? ''));
    $email = mysqli_real_escape_string($mysqli, trim($_POST['email'] ?? ''));
    $subject = mysqli_real_escape_string($mysqli, trim($_POST['subject'] ?? ''));
    $message = mysqli_real_escape_string($mysqli, trim($_POST['message'] ?? ''));
    
    // Check if all fields are filled
    if (empty($name) || empty($email) || empty($subject) || empty($message)) {
        header("Location: index.php?contact=error#contact");
        exit();
    }
    
    // Validate email
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: index.php?contact=invalid_email#contact");
        exit();
    }
    
    // Insert into database
    $query = "INSERT INTO contact_submissions (name, email, subject, message, submitted_at, status) 
              VALUES ('$name', '$email', '$subject', '$message', NOW(), 'new')";
    
    if ($mysqli->query($query)) {
        // Send email notification to admin
        $to = "abdulmajid1962@yahoo.co.in";
        $email_subject = "New Contact Form: " . $subject;
        $email_body = "New Contact Form Submission\n";
        $email_body .= "===========================\n\n";
        $email_body .= "Name: $name\n";
        $email_body .= "Email: $email\n";
        $email_body .= "Subject: $subject\n\n";
        $email_body .= "Message:\n$message\n\n";
        $email_body .= "---\n";
        $email_body .= "Submitted: " . date('Y-m-d H:i:s') . "\n";
        $email_body .= "From: Good Character OPC Website";
        
        $headers = "From: noreply@goodcharacteropc.com\r\n";
        $headers .= "Reply-To: $email\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        // Attempt to send email (may fail on localhost)
        @mail($to, $email_subject, $email_body, $headers);
        
        // Redirect with success (regardless of email status)
        header("Location: index.php?contact=success#contact");
        exit();
    } else {
        // Database error
        error_log("Contact form DB error: " . $mysqli->error);
        header("Location: index.php?contact=error#contact");
        exit();
    }
    
} else {
    // Not a POST request
    header("Location: index.php#contact");
    exit();
}
?>