<?php
declare(strict_types=1);

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

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(400);
  echo json_encode(['type' => 'error', 'text' => 'Requisição inválida']);
  exit;
}

// Honeypot
if (!empty($_POST['website'] ?? '')) {
  echo json_encode(['type' => 'error', 'text' => 'Spam detectado']);
  exit;
}

// Rate-limit por sessão
$now = time();
$minSecondsBetweenSubmits = 20;
$last = (int)($_SESSION['last_submit'] ?? 0);
if ($now - $last < $minSecondsBetweenSubmits) {
  echo json_encode(['type' => 'error', 'text' => "Aguarde {$minSecondsBetweenSubmits} segundos entre envios."]);
  exit;
}

$raw = static function (string $k): string {
  return isset($_POST[$k]) ? trim((string)$_POST[$k]) : '';
};

$firstNonEmpty = static function (array $keys) use ($raw): string {
  foreach ($keys as $k) {
    $v = $raw($k);
    if ($v !== '') return $v;
  }
  return '';
};

// Campos (tolerante a variações no front-end)
$name  = $firstNonEmpty(['name', 'nome', 'full_name']);
$email = $firstNonEmpty(['email', 'mail']);
$phone = $firstNonEmpty(['phone', 'telefone', 'tel']);

$service = $firstNonEmpty(['service_type', 'service', 'servico']);
$appointment_time = $firstNonEmpty(['appointment_time', 'appointment', 'datetime', 'data_hora', 'date']);

$message = $firstNonEmpty(['message', 'mensagem']);
$privacy = $firstNonEmpty(['privacy', 'privacy_policy', 'consent', 'rgpd']);

// Validações
if (mb_strlen($name, 'UTF-8') < 3) {
  echo json_encode(['type' => 'error', 'text' => 'Nome demasiado curto']);
  exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo json_encode(['type' => 'error', 'text' => 'Email inválido']);
  exit;
}
if (mb_strlen($message, 'UTF-8') < 5) {
  echo json_encode(['type' => 'error', 'text' => 'Mensagem demasiado curta']);
  exit;
}
if ($privacy === '') {
  echo json_encode(['type' => 'error', 'text' => 'É necessário aceitar a Política de Privacidade.']);
  exit;
}

// Data/hora (opcional)
$appointment_display = '';
if ($appointment_time !== '') {
  $t = strtotime($appointment_time);
  $appointment_display = ($t !== false)
    ? date('Y-m-d H:i', $t)
    : htmlspecialchars($appointment_time, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

// Corpo do email
$esc = static function (string $s): string {
  return nl2br(htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));
};

$emailBody  = "<div style=\"font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#222;\">";
$emailBody .= "<h3 style=\"margin-bottom:0.4em;\">Novo contacto do website (alexsophie.pt)</h3>";
$emailBody .= "<p><strong>Nome:</strong> {$esc($name)}</p>";
$emailBody .= "<p><strong>Email:</strong> {$esc($email)}</p>";
if ($phone !== '') $emailBody .= "<p><strong>Telefone:</strong> {$esc($phone)}</p>";
if ($service !== '') $emailBody .= "<p><strong>Serviço:</strong> {$esc($service)}</p>";
if ($appointment_display !== '') $emailBody .= "<p><strong>Hora pretendida:</strong> {$esc($appointment_display)}</p>";
$emailBody .= "<hr>";
$emailBody .= "<p><strong>Mensagem:</strong><br>" . $esc($message) . "</p>";
$emailBody .= "<hr>";
$emailBody .= "<p style=\"font-size:12px;color:#666\">Enviado em: " . date('Y-m-d H:i:s') . "</p>";
$emailBody .= "</div>";

// =============================
// PHPMailer (do core)
// =============================
$phpmailer_dir = dirname(__DIR__) . '/core/PHPMailer';

$needed = [
  $phpmailer_dir . '/PHPMailer.php',
  $phpmailer_dir . '/SMTP.php',
  $phpmailer_dir . '/Exception.php',
];

foreach ($needed as $p) {
  if (!file_exists($p)) {
    echo json_encode(['type' => 'error', 'text' => "PHPMailer não encontrado: {$p}"]);
    exit;
  }
}

require_once $phpmailer_dir . '/PHPMailer.php';
require_once $phpmailer_dir . '/SMTP.php';
require_once $phpmailer_dir . '/Exception.php';

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

$mail = new PHPMailer(true);

try {
  // =============================
  // SMTP OVH (geral@alexsophie.pt)
  // =============================
  $smtpHost = 'ssl0.ovh.net';  // se no teu painel aparecer outro host, troca aqui
  $smtpPort = 587;             // STARTTLS
  $smtpUser = 'geral@alexsophie.pt';
  $smtpPass = 'Passwordprovisoria2026*'; // <- password real da mailbox

  $mail->isSMTP();
  $mail->Host = $smtpHost;
  $mail->SMTPAuth = true;
  $mail->Username = $smtpUser;
  $mail->Password = $smtpPass;

  $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
  $mail->Port = $smtpPort;

  // Opcional: evita alguns problemas de certificado em hosts partilhados
  // (se não precisares, podes remover)
  $mail->SMTPOptions = [
    'ssl' => [
      'verify_peer' => false,
      'verify_peer_name' => false,
      'allow_self_signed' => true,
    ],
  ];

  // From deve ser a mailbox autenticada (OVH normalmente exige isto)
  $mail->setFrom($smtpUser, 'Website AlexSophie');

  // Destino: o próprio email do cliente (ou podes meter também o teu)
  $mail->addAddress('geral@alexsophie.pt');

  // Para responder diretamente ao cliente que preencheu o formulário
  $mail->addReplyTo($email, $name);

  $safeService = ($service !== '') ? $service : 'Pedido via formulário';

  $mail->CharSet  = 'UTF-8';
  $mail->Encoding = 'base64';

  $mail->isHTML(true);
  $subject = "Contacto: {$name}";
  if ($service !== '') {
      $subject .= " - {$safeService}";
  }
  $mail->Subject = $subject;
  $mail->Body = $emailBody;
  $mail->AltBody = trim(strip_tags(str_replace(["<br>", "<br/>", "<br />"], "\n", $emailBody)));

  $mail->send();

  $_SESSION['last_submit'] = $now;

  echo json_encode(['type' => 'success', 'text' => 'Obrigado — mensagem enviada com sucesso!']);
  exit;

} catch (Exception $ex) {
  echo json_encode(['type' => 'error', 'text' => 'Erro ao enviar: ' . $mail->ErrorInfo]);
  exit;
}
