<?php
/**
 * hostingdelsur.net — Contact form endpoint
 *
 * Lee credenciales SMTP de ~/.smtp-credentials.json (fuera de public_html)
 * y envía el mail vía PHPMailer. Valida reCAPTCHA v3 (opcional si no hay token).
 *
 * Setup: ver src/forms/README.md
 */

declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header('X-Frame-Options: DENY');

require_once __DIR__ . '/../../private/PHPMailer/Exception.php';
require_once __DIR__ . '/../../private/PHPMailer/PHPMailer.php';
require_once __DIR__ . '/../../private/PHPMailer/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    echo json_encode(['ok' => false, 'error' => 'Método no permitido']);
    exit;
}

$reCAPTCHA_secret = getenv('RECAPTCHA_SECRET') ?: ($_SERVER['RECAPTCHA_SECRET'] ?? '');

$credsPath = (($_SERVER['HOME'] ?? '') ?: '/home/hostingdelsur') . '/.smtp-credentials.json';
if (!is_readable($credsPath)) {
    error_log('contact.php: credenciales no disponibles en ' . $credsPath);
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Configuración no disponible']);
    exit;
}

try {
    $credsRaw = file_get_contents($credsPath);
    if ($credsRaw === false) {
        throw new RuntimeException('No se pudo leer el archivo de credenciales');
    }
    $creds = json_decode($credsRaw, true, 8, JSON_THROW_ON_ERROR);
} catch (Throwable $e) {
    error_log('contact.php: credenciales inválidas — ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Configuración inválida']);
    exit;
}

if (!empty($_POST['website'])) {
    echo json_encode(['ok' => true]);
    exit;
}

$name = trim((string) filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS));
$email = trim((string) filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
$message = trim((string) filter_input(INPUT_POST, 'message', FILTER_SANITIZE_SPECIAL_CHARS));
$lang = in_array($_POST['lang'] ?? '', ['es', 'en'], true) ? $_POST['lang'] : 'es';
$recaptchaToken = trim((string) ($_POST['g-recaptcha-response'] ?? ''));

if ($name === '' || !$email || $message === '' || mb_strlen($message) > 5000) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Datos inválidos']);
    exit;
}

if ($reCAPTCHA_secret !== '' && $recaptchaToken !== '') {
    $verifyUrl = 'https://www.google.com/recaptcha/api/siteverify';
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $verifyUrl,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'secret' => $reCAPTCHA_secret,
            'response' => $recaptchaToken,
            'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response !== false && $httpCode === 200) {
        $verification = json_decode($response, true);
        if (!is_array($verification) || empty($verification['success']) || ($verification['score'] ?? 1) < 0.3) {
            error_log('contact.php: reCAPTCHA failed — ' . json_encode($verification));
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'Verificación de seguridad falló']);
            exit;
        }
    }
} elseif ($reCAPTCHA_secret !== '' && $recaptchaToken === '') {
    error_log('contact.php: reCAPTCHA token missing');
}

$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rateKey = "contact_rl_{$ip}";
if (function_exists('apcu_fetch')) {
    $hits = apcu_fetch($rateKey) ?: 0;
    if ($hits >= 3) {
        http_response_code(429);
        header('Retry-After: 3600');
        echo json_encode(['ok' => false, 'error' => 'Demasiados envíos. Probá más tarde.']);
        exit;
    }
    apcu_store($rateKey, $hits + 1, 3600);
}

$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = (string) $creds['host'];
    $mail->SMTPAuth = true;
    $mail->Username = (string) $creds['username'];
    $mail->Password = (string) $creds['password'];
    $mail->SMTPSecure = (string) ($creds['encryption'] ?? 'ssl');
    $mail->Port = (int) ($creds['port'] ?? 465);
    $mail->CharSet = 'UTF-8';
    $mail->Timeout = 10;

    $mail->setFrom((string) $creds['from'], (string) ($creds['fromName'] ?? 'Hosting del Sur'));
    $mail->addAddress((string) $creds['to']);
    $mail->addReplyTo($email, $name);

    $mail->Subject = "Contacto desde hostingdelsur.net: {$name}";
    $body = "Nombre: {$name}\nEmail: {$email}\nIdioma: {$lang}\nIP: {$ip}\n\nMensaje:\n{$message}";
    $mail->Body = $body;
    $mail->AltBody = $body;

    $mail->send();
    echo json_encode(['ok' => true]);
} catch (Exception $e) {
    error_log('contact.php: PHPMailer error — ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'No se pudo enviar el mensaje']);
}
