<?php

namespace App\Services;

use Illuminate\Http\Request;

class AttributionService
{
    public const SESSION_KEY = 'marketing.first_touch';

    public function capture(Request $request): void
    {
        if ($request->session()->has(self::SESSION_KEY)) {
            return;
        }

        $data = $this->extract($request);

        $request->session()->put(self::SESSION_KEY, $data);
    }

    public function current(Request $request): array
    {
        if ($request->session()->has(self::SESSION_KEY)) {
            return $request->session()->get(self::SESSION_KEY, []);
        }

        return $this->extract($request);
    }

    public function extract(Request $request): array
    {
        $landingPage = $request->fullUrl();
        $referrerUrl = (string) $request->headers->get('referer', '');
        $referrerHost = $referrerUrl ? parse_url($referrerUrl, PHP_URL_HOST) : null;
        $ownHost = parse_url(url('/'), PHP_URL_HOST);

        $utmSource = $this->clean($request->query('utm_source'));
        $utmMedium = $this->clean($request->query('utm_medium'));
        $utmCampaign = $this->clean($request->query('utm_campaign'));
        $utmContent = $this->clean($request->query('utm_content'));
        $utmTerm = $this->clean($request->query('utm_term'));
        $fbclid = $this->clean($request->query('fbclid'));
        $gclid = $this->clean($request->query('gclid'));

        $source = $utmSource;
        if (! $source && $fbclid) {
            $source = 'facebook';
        }
        if (! $source && $gclid) {
            $source = 'google';
        }
        if (! $source && $referrerHost && $referrerHost !== $ownHost) {
            $source = $referrerHost;
        }
        if (! $source) {
            $source = 'direct';
        }

        return [
            'source' => $source,
            'utm_source' => $utmSource,
            'utm_medium' => $utmMedium,
            'utm_campaign' => $utmCampaign,
            'utm_content' => $utmContent,
            'utm_term' => $utmTerm,
            'fbclid' => $fbclid,
            'gclid' => $gclid,
            'referrer_url' => $referrerUrl ?: null,
            'landing_page' => $landingPage,
        ];
    }

    private function clean(mixed $value): ?string
    {
        $value = trim((string) $value);

        return $value !== '' ? mb_substr($value, 0, 500) : null;
    }
}
