<?php
session_start();
require "Admin/includes/config.php"; 

if($_SERVER["REQUEST_METHOD"] != "POST"){
    header("Location: contact-us.php");
    exit;
}

// CSRF token check
if(!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['form_token']){
    die("Invalid form request.");
}

// honeypot bot check
if(!empty($_POST['hp'])){
    die("Spam detected.");
}

unset($_SESSION['form_token']);

function clean($data){
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

$name    = clean($_POST['name']);
$email   = clean($_POST['email']);
$phone   = clean($_POST['phone']);
$subject = clean($_POST['subject']);
$message = clean($_POST['message']);

// Validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    header("Location: contact-us.php?error=1");
    exit;
}

// Validate required fields
if(empty($name) || empty($email) || empty($subject) || empty($message)){
    header("Location: contact-us.php?error=1");
    exit;
}
// check duplicate email
$check = $pdo->prepare("SELECT id FROM contact_messages WHERE email = ? LIMIT 1");
$check->execute([$email]);
if($check->rowCount() > 0){
    header("Location: contact-us.php?duplicate=1");
    exit;
}

// Insert into database (prepared)
$stmt = $pdo->prepare("
    INSERT INTO contact_messages 
    (name, email, phone, subject, message) 
    VALUES (?, ?, ?, ?, ?)
");

try{
    $stmt->execute([$name, $email, $phone, $subject, $message]);
    header("Location: contact-us.php?success=1");
} 
catch(Exception $e){
    header("Location: contact-us.php?error=1");
}
?>