<?php

if (!defined('TYPO3_COMPOSER_MODE')) {
    define('TYPO3_COMPOSER_MODE', true);
}

$classLoader = require __DIR__ . '/../vendor/autoload.php';

\TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::run(
    1,
    \TYPO3\CMS\Core\Core\SystemEnvironmentBuilder::REQUESTTYPE_CLI
);

\TYPO3\CMS\Core\Core\Bootstrap::init($classLoader);

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;

$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('tt_content');
$queryBuilder = $connection->createQueryBuilder();

$result = $queryBuilder
    ->select('uid', 'pi_flexform')
    ->from('tt_content')
    ->where($queryBuilder->expr()->eq('CType', $queryBuilder->createNamedParameter('ods_osm_pi1')))
    ->executeQuery();

$rows = $result->fetchAllAssociative();

$count = 0;

foreach ($rows as $row) {
    if (empty($row['pi_flexform'])) {
        continue;
    }

    $xml = simplexml_load_string($row['pi_flexform']);
    if (!$xml || !isset($xml->data->sheet)) {
        continue;
    }

    $targetSheet = null;
    foreach ($xml->data->sheet as $sheet) {
        if ((string)$sheet['index'] === 'sDEF') {
            $targetSheet = $sheet;
            break;
        }
    }
    if (!$targetSheet) {
        continue;
    }

    $targetLang = null;
    foreach ($targetSheet->language as $lang) {
        if ((string)$lang['index'] === 'lDEF') {
            $targetLang = $lang;
            break;
        }
    }
    if (!$targetLang) {
        continue;
    }

    $updateField = function($langNode, $fieldName, $newValue) {
        $fieldFound = null;
        foreach ($langNode->field as $field) {
            if ((string)$field['index'] === $fieldName) {
                $fieldFound = $field;
                break;
            }
        }

        if ($fieldFound) {
            $fieldFound->value[0] = $newValue;
        }
    };

    $updateField($targetLang, 'show_popups', '1');
    $updateField($targetLang, 'show_layerswitcher', '-1');

    // DB save
    $connection->update(
        'tt_content',
        ['pi_flexform' => $xml->asXML()],
        ['uid' => $row['uid']]
    );

    echo "Updated UID: " . $row['uid'] . "\n";
    $count++;
}

echo "OK. Total updated: $count\n";