<?php
// track/open.php - Tracking pixel (open)

$cid   = $_GET['cid']   ?? '';
$token = $_GET['token'] ?? '';

if ($cid && $token && preg_match('/^camp_[a-z0-9]+$/', $cid)) {
    $file = __DIR__ . "/../tracking/$cid.json";
    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true);
        if (isset($data['recipients'][$token]) && $data['recipients'][$token]['opened'] === 0) {
            $data['recipients'][$token]['opened'] = time();
            $data['opened'] = ($data['opened'] ?? 0) + 1;
            file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
        }
    }
}

// Return 1x1 pixel transparan
header('Content-Type: image/gif');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
exit;