<?php
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/cors.php';
require_once __DIR__ . '/send_mail.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
    $data = $_POST; // fallback if form-encoded
}

$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');
$company = trim($data['company'] ?? '');
$position = trim($data['position'] ?? '');
$location = trim($data['location'] ?? '');
$interest = trim($data['interest'] ?? '');
$message = trim($data['message'] ?? '');

if ($name === '' || $email === '' || $message === '') {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'Name, email and message are required.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'Invalid email address.']);
    exit;
}

$to = $config['contact_email'] ?? ($config['smtp_from'] ?? 'noreply@localhost');
$subject = 'New Website Inquiry';
$body = '<h3>New inquiry from Viz Venture Group website</h3>' .
        '<p><strong>Name:</strong> ' . htmlspecialchars($name) . '</p>' .
        '<p><strong>Email:</strong> ' . htmlspecialchars($email) . '</p>' .
        '<p><strong>Phone:</strong> ' . htmlspecialchars($phone) . '</p>' .
        '<p><strong>Company:</strong> ' . htmlspecialchars($company) . '</p>' .
        '<p><strong>Position:</strong> ' . htmlspecialchars($position) . '</p>' .
        '<p><strong>Location:</strong> ' . htmlspecialchars($location) . '</p>' .
        '<p><strong>Area of interest:</strong> ' . htmlspecialchars($interest) . '</p>' .
        '<p><strong>Message:</strong><br>' . nl2br(htmlspecialchars($message)) . '</p>';

$result = send_mail($to, $subject, $body);
if ($result === true) {
    echo json_encode(['success' => true, 'message' => 'Thanks! We will get back to you shortly.']);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Unable to send message: ' . $result]);
}
