<?php

namespace App\GooglePlugins;

use App\Models\GooglePlugin;
use App\GooglePlugins\Contracts\BaseGooglePlugin;

class GoogleAnalytics extends BaseGooglePlugin
{
    public function getCode(): string
    {
        return 'google_analytics';
    }

    public function getName(): string
    {
        return 'Google Analytics';
    }

    public function getDescription(): string
    {
        return 'Google Analytics 4 (GA4) measurement and tracking. Provides insights into website traffic, user behavior, and conversion data.';
    }

    public function getConfigFields(): array
    {
        return [
            [
                'key' => 'measurement_id',
                'label' => 'Measurement ID',
                'type' => 'text',
                'placeholder' => 'G-XXXXXXXXXX',
                'required' => true,
            ],
        ];
    }

    public function validateConfig(array $config): array
    {
        $measurementId = $config['measurement_id'] ?? '';
        $measurementId = trim($measurementId);
        return ['measurement_id' => $measurementId];
    }

    public function isConfigured(GooglePlugin $plugin): bool
    {
        $config = $plugin->config ?? [];
        return !empty($config['measurement_id']);
    }

    public function renderHead(GooglePlugin $plugin): string
    {
        $id = $plugin->config['measurement_id'] ?? '';
        if (!$id) return '';

        return <<<HTML
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={$id}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{$id}');
</script>
HTML;
    }

    public function renderBody(GooglePlugin $plugin): string
    {
        return '';
    }
}
