<?php
/**
 * Magic Contact Form Handler
 * Receives POST from the contact form, emails to admin, returns JSON.
 * Deploy to HostGator alongside index.html.
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

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

// ── Config ──────────────────────────────────────
$ADMIN_EMAIL = 'spw1@spw1.com';
$SITE_NAME   = 'Magic Mesh Platform';

// ── Parse input ─────────────────────────────────
$input = json_decode(file_get_contents('php://input'), true);

$name    = isset($input['name'])    ? trim(strip_tags($input['name']))    : '';
$email   = isset($input['email'])   ? trim(strip_tags($input['email']))   : '';
$company = isset($input['company']) ? trim(strip_tags($input['company'])) : '';
$message = isset($input['message']) ? trim(strip_tags($input['message'])) : '';

// ── Validate ────────────────────────────────────
if ($name === '' || $email === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Name and email are required']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid email address']);
    exit;
}

// ── Build email ─────────────────────────────────
$subject = "[$SITE_NAME] New contact from $name";

$body  = "New contact form submission\n";
$body .= "================================\n\n";
$body .= "Name:    $name\n";
$body .= "Email:   $email\n";
$body .= "Company: " . ($company ?: '(not provided)') . "\n";
$body .= "Message: " . ($message ?: '(not provided)') . "\n\n";
$body .= "================================\n";
$body .= "Submitted: " . date('Y-m-d H:i:s T') . "\n";
$body .= "IP: " . $_SERVER['REMOTE_ADDR'] . "\n";

$headers  = "From: noreply@spw1.com\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "X-Mailer: Magic-Contact-Form/1.0\r\n";

// ── Send ────────────────────────────────────────
$sent = mail($ADMIN_EMAIL, $subject, $body, $headers);

if ($sent) {
    // Also log to CSV as backup
    $logFile = __DIR__ . '/contacts.csv';
    $isNew = !file_exists($logFile);
    $fp = fopen($logFile, 'a');
    if ($fp) {
        if ($isNew) {
            fputcsv($fp, ['date', 'name', 'email', 'company', 'message', 'ip']);
        }
        fputcsv($fp, [
            date('Y-m-d H:i:s'),
            $name,
            $email,
            $company,
            $message,
            $_SERVER['REMOTE_ADDR']
        ]);
        fclose($fp);
    }

    echo json_encode(['ok' => true]);
} else {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Mail delivery failed']);
}
