<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use Sethrey\SysvoteWebsite\EnvLoader;
use Sethrey\SysvoteWebsite\SmtpMailer;

header('Content-Type: application/json; charset=utf-8');

function respond(bool $success, string $message, int $httpCode = 200): void
{
    http_response_code($httpCode);
    echo json_encode(['success' => $success, 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(false, 'Méthode non autorisée.', 405);
}

try {
    EnvLoader::load(__DIR__ . '/../.env');
} catch (\Throwable $e) {
    error_log('[contact.php] ' . $e->getMessage());
    respond(false, "Erreur de configuration du serveur.", 500);
}

// --- Honeypot anti-spam (hidden field that bots tend to fill) ---
if (!empty($_POST['website'] ?? '')) {
    // Silently pretend success so bots don't learn anything.
    respond(true, 'Votre demande a été envoyée.');
}

// --- Collect & validate input ---
$name         = trim((string) ($_POST['name'] ?? ''));
$organization = trim((string) ($_POST['organization'] ?? ''));
$email        = trim((string) ($_POST['email'] ?? ''));
$message      = trim((string) ($_POST['message'] ?? ''));

$errors = [];

if ($name === '' || mb_strlen($name) > 150) {
    $errors[] = 'Le nom est requis.';
}
if ($organization === '' || mb_strlen($organization) > 150) {
    $errors[] = "L'organisation est requise.";
}
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "L'adresse courriel n'est pas valide.";
}
if (mb_strlen($message) > 5000) {
    $errors[] = 'Le message est trop long.';
}

if (!empty($errors)) {
    respond(false, implode(' ', $errors), 422);
}

// --- Build email body ---
$body = "Nouvelle demande de devis depuis le site SysVote\n";
$body .= str_repeat('-', 50) . "\n\n";
$body .= "Nom complet : {$name}\n";
$body .= "Organisation : {$organization}\n";
$body .= "Courriel : {$email}\n\n";
$body .= "Message :\n" . ($message !== '' ? $message : '(aucun message)') . "\n";

try {
    $mailer = new SmtpMailer(
        EnvLoader::get('MAIL_HOST', ''),
        (int) EnvLoader::get('MAIL_PORT', '465'),
        EnvLoader::get('MAIL_USER', ''),
        EnvLoader::get('MAIL_PASS', ''),
        EnvLoader::get('MAIL_FROM', ''),
        EnvLoader::get('MAIL_FROM_NAME', 'SysVote')
    );

    // Recipient: where the request lands (defaults to the same mailbox as the sender).
    $recipient = EnvLoader::get('MAIL_TO', EnvLoader::get('MAIL_USER', ''));

    $mailer->send(
        $recipient,
        'SysVote',
        "Nouvelle demande de devis — {$organization}",
        $body,
        $email,   // Reply-To = the visitor's email, so you can just hit "Reply"
        $name
    );
} catch (\Throwable $e) {
    error_log('[contact.php] Envoi échoué : ' . $e->getMessage());
    respond(false, "L'envoi a échoué. Merci de réessayer plus tard ou de nous écrire directement.", 502);
}

respond(true, 'Votre demande a été envoyée avec succès.');
