<?php

defined('TYPO3') or die();

// Make CType field visible but read-only (prevents changing type after creation)
$GLOBALS['TCA']['tt_content']['columns']['CType']['config']['readOnly'] = true;

// Add the "Contextual Consent" field (erhaweb/klaro-consent-manager) to the
// existing "Access" palette (in the "Extended" tab) for every zab/* Content
// Block. Content Blocks generates its own showitem and does not include this
// by default, so it's applied globally here instead of via `basics:` in each
// block's config.yaml. Skipped entirely when klaro_consent_manager isn't installed.
(function (): void {
    if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('klaro_consent_manager')) {
        return;
    }

    $zabTypes = array_filter(
        array_keys($GLOBALS['TCA']['tt_content']['types'] ?? []),
        static fn(string $type): bool => str_starts_with($type, 'zab_')
    );

    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes(
        'tt_content',
        'tx_klaroconsentmanager_service',
        implode(',', $zabTypes),
        'after:palette:access'
    );
})();

// Reusable UUID field for Content Blocks (useExistingField: true).
$GLOBALS['TCA']['tt_content']['columns']['uuid'] = [
    'exclude' => 1,
    'label' => 'Block ID',
    'config' => [
        'type' => 'uuid',
    ],
];

// Reusable anchor field for Content Blocks (useExistingField: true).
$GLOBALS['TCA']['tt_content']['columns']['anchor'] = [
    'exclude' => 1,
    'label' => 'Readable URL #Anchor',
    'config' => [
        'type' => 'input',
        'size' => 50,
        'max' => 255,
        'eval' => 'trim',
    ],
];

// Set startingPoints for the Quick Check link field dynamically from the site config.
// Edit quickCheckPageId in config/sites/main/config.yaml for each environment.
(function (): void {
    try {
        $siteFinder = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
            \TYPO3\CMS\Core\Site\SiteFinder::class
        );
        foreach ($siteFinder->getAllSites() as $site) {
            $uid = $site->getConfiguration()['quickCheckPageId'] ?? null;
            if ($uid) {
                $GLOBALS['TCA']['zab_quickcheck_questions']['columns']['link']['config']['treeConfig']['startingPoints'] = (string)(int)$uid;
                break;
            }
        }
    } catch (\Throwable $e) {
        // Keep the ContentBlocks YAML default if site config is unavailable.
    }
})();
