<?php
declare(strict_types=1);
session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Method not allowed.');window.location.href='index-2.html#site-contact';</script></body></html>";
    exit;
}

$name = trim((string)($_POST['full_name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
if ($name === '' || $email === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Please provide valid name, email and message.');window.location.href='index-2.html#site-contact';</script></body></html>";
    exit;
}

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='index-2.html#site-contact';</script></body></html>";
    exit;
}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS contacts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        full_name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        user_id INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

$userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;

try {
    $st = $pdo->prepare('INSERT INTO contacts(full_name,email,message,user_id) VALUES(:n,:e,:m,:u)');
    $st->execute([':n'=>$name, ':e'=>$email, ':m'=>$message, ':u'=>$userId]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to submit message.');window.location.href='index-2.html#site-contact';</script></body></html>";
    exit;
}

echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Thanks! Your message was sent.');window.location.href='index-2.html#site-contact';</script></body></html>";
?>

