<?php
// r.php — Redirect sigur cu HMAC + expirare + LOG click-uri
// Parametri: ?url=<dest>&ts=<unix>&usg=<b64url(hmac(url|ts))>&cid=<id>
header('Referrer-Policy: no-referrer');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');

define('WINDOW_SECONDS', 48 * 60 * 60);

$secretFile = __DIR__ . '/secret.txt';
if (!is_file($secretFile)) { http_response_code(500); echo 'secret.txt missing'; exit; }
$SECRET = trim(file_get_contents($secretFile));
if ($SECRET === '') { http_response_code(500); echo 'empty secret'; exit; }

function b64url_decode($s) {
  $s = strtr($s, '-_', '+/');
  $pad = strlen($s) % 4;
  if ($pad) $s .= str_repeat('=', 4 - $pad);
  return base64_decode($s, true);
}
function log_click($data) {
  $line = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  @file_put_contents(__DIR__ . '/clicks.log', $line . PHP_EOL, FILE_APPEND);
}

$url = isset($_GET['url']) ? trim($_GET['url']) : '';
$ts  = isset($_GET['ts'])  ? (int)$_GET['ts'] : 0;
$usg = isset($_GET['usg']) ? trim($_GET['usg']) : '';
$cid = isset($_GET['cid']) ? trim($_GET['cid']) : '';

$now = time();
$ip  = $_SERVER['REMOTE_ADDR'] ?? '';
$ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';

$log = [
  'ts_server' => $now,
  'ip'        => $ip,
  'ua'        => $ua,
  'url'       => $url,
  'cid'       => $cid,
  'ok'        => false,
  'reason'    => '',
];

if ($url === '' || $ts <= 0 || $usg === '') {
  $log['reason'] = 'bad_request';
  log_click($log);
  http_response_code(400); echo 'Bad request'; exit;
}
if (abs($now - $ts) > WINDOW_SECONDS) {
  $log['reason'] = 'expired';
  log_click($log);
  http_response_code(410); echo 'Link expired'; exit;
}

$data = $url . '|' . $ts;
$mac  = hash_hmac('sha256', $data, $SECRET, true);
$usg_raw = b64url_decode($usg);
if (!$usg_raw || !hash_equals($mac, $usg_raw)) {
  $log['reason'] = 'bad_signature';
  log_click($log);
  http_response_code(403); echo 'Invalid signature'; exit;
}

// Validare URL minima
$u = parse_url($url);
if (empty($u['scheme']) || empty($u['host'])) {
  $log['reason'] = 'invalid_url';
  log_click($log);
  http_response_code(400); echo 'Invalid URL'; exit;
}

// Extrage email (daca exista) pentru log
parse_str($u['query'] ?? '', $q);
$log['email']  = $q['email'] ?? '';
$log['ok']     = true;
$log['reason'] = 'ok';
log_click($log);

// Redirect
header('Cache-Control: no-store');
header('Location: ' . $url, true, 302);
exit;
