<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Csrf;
use App\Core\Request;
use App\Services\CampaignSender;

final class TrackingController
{
    public function open(Request $request): void
    {
        $token = (string) $request->param('token');
        CampaignSender::recordOpen($token);
        header('Content-Type: image/gif');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        exit;
    }

    public function click(Request $request): void
    {
        $token = (string) $request->param('token');
        $url = CampaignSender::recordClick($token);
        header('Location: ' . ($url ?: url('login')), true, 302);
        exit;
    }

    public function unsubscribeForm(Request $request): void
    {
        $token = (string) $request->param('token');
        view('marketing/unsubscribe', [
            'title' => 'Unsubscribe',
            'token' => $token,
            'done' => false,
        ], 'layouts/auth');
    }

    public function unsubscribeSave(Request $request): void
    {
        if (!Csrf::verify(Csrf::fromRequest())) {
            http_response_code(419);
            echo 'Session expired. Refresh and try again.';
            return;
        }
        $token = (string) $request->param('token');
        $ok = CampaignSender::unsubscribe($token);
        view('marketing/unsubscribe', [
            'title' => 'Unsubscribe',
            'token' => $token,
            'done' => $ok,
        ], 'layouts/auth');
    }
}
