<?php

namespace App\Hooks\Tracking;

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

class FirebaseHook extends AbstractHook
{
    public function boot(HookManager $hooks): void
    {
        $hooks->listen('ClientAreaHeadOutput', function () {
            $measurementId = setting('firebase_measurement_id');
            $apiKey = setting('firebase_api_key');
            if (empty($measurementId) || empty($apiKey)) {
                return '';
            }
            return view('hooks.tracking.firebase', [
                'apiKey' => $apiKey,
                'projectId' => setting('firebase_project_id') ?: '',
                'appId' => setting('firebase_app_id') ?: '',
                'measurementId' => $measurementId,
                '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;
    }
}
