<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Services\TrackingService;

/**
 * TrackingController
 *
 * Deliberately has NO auth/CSRF middleware — every route here is hit
 * by an anonymous recipient's email client or browser, not a logged-in
 * A&B Hub user. Nothing here can mutate anything beyond one specific
 * campaign_recipients row (found via an unguessable random token), so
 * this is safe to leave fully public. See routes/web.php's marketing
 * section for the exact routes.
 */
final class TrackingController extends BaseController
{
    private const TRANSPARENT_GIF = "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xFF\xFF\xFF\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B";

    public function pixel(Request $request, array $params): Response
    {
        (new TrackingService())->recordOpen($params['token']);

        return Response::html(self::TRANSPARENT_GIF)
            ->withHeader('Content-Type', 'image/gif')
            ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
    }

    public function click(Request $request, array $params): Response
    {
        (new TrackingService())->recordClick($params['token']);

        $destination = $request->query('url');
        $safeDestination = $destination && filter_var($destination, FILTER_VALIDATE_URL) ? $destination : base_url('');

        return Response::redirect($safeDestination);
    }

    public function showUnsubscribeForm(Request $request, array $params): Response
    {
        return $this->view('marketing/unsubscribe', ['title' => 'Unsubscribe', 'token' => $params['token']], useLayout: false);
    }

    public function confirmUnsubscribe(Request $request): Response
    {
        $token = (string) $request->input('token');
        $reason = $request->input('reason');

        $result = (new TrackingService())->recordUnsubscribe($token, is_string($reason) ? $reason : null);

        return \App\Helpers\AjaxResponse::success($result, $result['success']
            ? 'You have been unsubscribed and will not receive further marketing emails from us.'
            : 'This unsubscribe link is invalid or has already been used.');
    }
}
