<?php
// /api/towlens/share_open.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) { http_response_code(500); echo json_encode(['error' => 'Server error']); exit; }

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';

if (!($pdo instanceof PDO)) { http_response_code(500); echo json_encode(['error' => 'DB unavailable']); exit; }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function jresp($d,$s=200){ http_response_code($s); echo json_encode($d,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

$token = $_GET['token'] ?? '';
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
    jresp(['error' => 'Invalid'], 400);
}

$stmt = $pdo->prepare("
  SELECT id, request_id, expires_at, status
  FROM request_shares
  WHERE token = ?
  LIMIT 1
");
$stmt->execute([$token]);
$share = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$share) {
    // Don't leak existence
    jresp(['status' => 'invalid'], 200);
}

// Check expiry
if (!empty($share['expires_at']) && $share['expires_at'] < date('Y-m-d H:i:s')) {
    $pdo->prepare("UPDATE request_shares SET status = 'expired' WHERE id = ?")
        ->execute([$share['id']]);
    jresp(['status' => 'expired'], 200);
}

// Update counters
$pdo->prepare("
  UPDATE request_shares
  SET open_count = open_count + 1,
      first_open_at = IF(first_open_at IS NULL, NOW(), first_open_at),
      status = IF(status = 'pending' OR status = 'sent', 'opened', status)
  WHERE id = ?
")->execute([$share['id']]);

// Log event
$ev = $pdo->prepare("
  INSERT INTO towlens_events (request_id, share_id, event_type, ip, user_agent)
  VALUES (?, ?, 'OPENED', ?, ?)
");
$ev->execute([
    $share['request_id'],
    $share['id'],
    $_SERVER['REMOTE_ADDR'] ?? null,
    substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 250)
]);

jresp(['status' => 'ok']);
