<?php
/**
 * SkyFly Travel - Contact Form Backend (PHP mail() for Static Export)
 */

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

// --- CONFIGURATION ---
$secretKey = "6LfqD1osAAAAAEbpEApPkiQUbyjdKYx2OvhY2XTk"; // reCAPTCHA v3 Secret Key
$toEmail = "bognar.szilard83@gmail.com";
$minScore = 0.5;
$expectedAction = "contact_form";
// ---------------------

function json_error($message, $code = 400, $details = null) {
    http_response_code($code);
    $response = ["error" => $message];
    if (!empty($_GET["debug"]) && $details) {
        $response["details"] = $details;
    }
    echo json_encode($response);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);

    $name = strip_tags($data["name"] ?? "");
    $email = filter_var($data["email"] ?? "", FILTER_SANITIZE_EMAIL);
    $phone = strip_tags($data["phone"] ?? "");
    $service = strip_tags($data["service"] ?? "");
    $message = strip_tags($data["message"] ?? "");
    $language = $data["language"] ?? "hu";
    $recaptchaToken = $data["recaptchaToken"] ?? "";
    $recaptchaAction = $data["recaptchaAction"] ?? "";

    if (!$recaptchaToken) {
        json_error("Missing reCaptcha token");
    }

    // 1. Verify reCaptcha v3
    $verifyResponse = null;
    if (function_exists("curl_init")) {
        $ch = curl_init("https://www.google.com/recaptcha/api/siteverify");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            "secret" => $secretKey,
            "response" => $recaptchaToken,
        ]));
        $verifyResponse = curl_exec($ch);
        curl_close($ch);
    } else {
        $verifyResponse = file_get_contents(
            "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$recaptchaToken"
        );
    }

    if ($verifyResponse === false || !$verifyResponse) {
        $last = error_get_last();
        json_error("reCaptcha verification failed", 400, $last ? $last["message"] : "No response");
    }

    $responseData = json_decode($verifyResponse);
    if (!$responseData) {
        json_error("reCaptcha verification failed", 400, "Invalid JSON response");
    }

    if (
        !$responseData->success ||
        $responseData->action !== $expectedAction ||
        $responseData->score < $minScore
    ) {
        json_error("reCaptcha verification failed", 400, json_encode($responseData));
    }

    $isEnglish = $language === "en";
    $subject = $isEnglish
        ? "Website message: $name ($service)"
        : "Weboldal uzenet: $name ($service)";

    $title = $isEnglish ? "New message" : "Uj uzenet";
    $labelName = $isEnglish ? "Name" : "Nev";
    $labelEmail = $isEnglish ? "Email" : "Email";
    $labelPhone = $isEnglish ? "Phone" : "Telefonszam";
    $labelService = $isEnglish ? "Service type" : "Szolgaltatas tipusa";
    $labelMessage = $isEnglish ? "Message" : "Uzenet";

    $htmlEmail = "
    <html>
    <head>
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    </head>
    <body style='font-family: sans-serif; color: #333;'>
        <div style='max-width: 600px; margin: 20px auto; border: 1px solid #ddd; border-radius: 15px; overflow: hidden;'>
            <div style='background: #D9A321; color: #111827; padding: 20px 24px; font-weight: 700;'>
                SkyFly Travel - $title
            </div>
            <div style='padding: 20px 24px; border-top: 1px solid #eee;'>
                <p><strong>$labelName:</strong> $name</p>
                <p><strong>$labelEmail:</strong> $email</p>
                <p><strong>$labelPhone:</strong> $phone</p>
                <p><strong>$labelService:</strong> $service</p>
                <p><strong>$labelMessage:</strong></p>
                <p style='white-space: pre-wrap; background: #f9f9f9; padding: 12px; border-radius: 8px;'>$message</p>
            </div>
        </div>
    </body>
    </html>
    ";

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: <noreply@skyflytravel.hu>" . "\r\n";
    if ($email) {
        $headers .= "Reply-To: $email" . "\r\n";
    }

    // 3. Send Email
    if (mail($toEmail, $subject, $htmlEmail, $headers)) {
        echo json_encode(["success" => true]);
    } else {
        $last = error_get_last();
        json_error("Failed to send email", 500, $last ? $last["message"] : "mail() returned false");
    }
}
?>
