<?php
// unsubscribe.php — suport One-Click si GET
header('Content-Type: application/json; charset=utf-8');

$now  = time();
$ip   = $_SERVER['REMOTE_ADDR'] ?? '';
$ua   = $_SERVER['HTTP_USER_AGENT'] ?? '';
$qs   = $_GET ?? [];
$email = isset($qs['email']) ? trim($qs['email']) : '';

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$oneClick = false;

if ($method === 'POST') {
  // RFC 8058 — One-Click
  $raw = file_get_contents('php://input');
  // De obicei corpul este "List-Unsubscribe=One-Click"
  if (stripos($raw, 'List-Unsubscribe=One-Click') !== false) $oneClick = true;
}

$ok = false;
$reason = '';
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $reason = 'bad_email';
} else {
  $ok = true;
}

$log = [
  'ts' => $now,
  'ip' => $ip,
  'ua' => $ua,
  'email' => $email,
  'method' => $method,
  'one_click' => $oneClick,
  'ok' => $ok,
  'reason' => $reason,
];

@file_put_contents(__DIR__ . '/unsubscribes.log', json_encode($log, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . PHP_EOL, FILE_APPEND);

http_response_code(200);
echo json_encode(['ok'=>$ok, 'message'=>$ok ? 'Unsubscribed' : 'Invalid email']);
exit;
