<?php

namespace App\GooglePlugins;

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

class GoogleTagManager extends BaseGooglePlugin
{
    public function getCode(): string
    {
        return 'google_tag_manager';
    }

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

    public function getDescription(): string
    {
        return 'Google Tag Manager container. Manage marketing tags, tracking pixels, and analytics scripts from a single interface.';
    }

    public function getConfigFields(): array
    {
        return [
            [
                'key' => 'gtm_id',
                'label' => 'GTM Container ID',
                'type' => 'text',
                'placeholder' => 'GTM-XXXXXXX',
                'required' => true,
            ],
        ];
    }

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

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

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

        return <<<HTML
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{$id}');</script>
HTML;
    }

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

        return <<<HTML
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={$id}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
HTML;
    }
}
