<?php

namespace App\Hooks\Tracking;

use App\Core\Hook\AbstractHook;
use App\Core\Hook\HookManager;

class SegmentHook extends AbstractHook
{
    public function boot(HookManager $hooks): void
    {
        $hooks->listen('ClientAreaHeadOutput', function () {
            $writeKey = setting('segment_write_key');
            if (empty($writeKey)) {
                return '';
            }
            return view('hooks.tracking.segment', [
                'writeKey' => $writeKey,
                'userEmailHash' => $this->userEmailHash(),
            ])->render();
        }, priority: 20, category: 'marketing');
    }

    private function userEmailHash(): ?string
    {
        $client = auth('client')->user();
        return $client?->email ? hash('sha256', strtolower(trim($client->email))) : null;
    }
}
