<?php
require_once __DIR__ . '/../src/bootstrap.php';
$token = $_GET['t'] ?? '';
if ($token !== '') {
    $pdo = db();
    $stmt = $pdo->prepare('UPDATE sends SET open_count = open_count + 1, opened_at = COALESCE(opened_at, :opened_at) WHERE token = :token');
    $stmt->execute([
        'opened_at' => date('Y-m-d H:i:s'),
        'token' => $token,
    ]);

    $campaignIdStmt = $pdo->prepare('SELECT campaign_id FROM sends WHERE token = :token LIMIT 1');
    $campaignIdStmt->execute(['token' => $token]);
    $campaignId = (int)$campaignIdStmt->fetchColumn();
    if ($campaignId > 0) {
        $opened = (int)$pdo->query("SELECT COUNT(*) FROM sends WHERE campaign_id = {$campaignId} AND opened_at IS NOT NULL")->fetchColumn();
        $stmt = $pdo->prepare('UPDATE campaigns SET total_opened = :opened WHERE id = :id');
        $stmt->execute(['opened' => $opened, 'id' => $campaignId]);
    }
}
header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
