<?php

use Kirby\Cms\Page;
use Kirby\Data\Yaml;

require_once __DIR__ . '/helpers.php';

class ChapterPage extends Page
{

    public function update(array|null $input = null, string|null $languageCode = null, bool $validate = false): static
    {
        if (isset($input['sections'])) {
            $sections = $input['sections'];

            if (is_string($sections)) {
                $sections = Yaml::decode($sections);
            }
            if (is_array($sections)) {
                $textContent = '';

                foreach ($sections as $blockData) {
                    $type = $blockData['type'] ?? '';

                    switch ($type) {
                    case 'prose':
                        $textContent .= writerToPlainText($blockData['content']['text'] ?? '') . "\n\n";
                        break;
                    case 'pull':
                        $textContent .= writerToPlainText($blockData['content']['text'] ?? '') . "\n\n";
                        break;
                    case 'note':
                        $textContent .= writerToPlainText($blockData['content']['text'] ?? '') . "\n\n";
                        break;
                    case 'texture':
                        $textContent .= ($blockData['content']['caption'] ?? '') . "\n\n";
                        break;
                    case 'pinned-text':
                        $textContent .= writerToPlainText($blockData['content']['heading'] ?? '') . "\n\n";
                        $textContent .= writerToPlainText($blockData['content']['body'] ?? '') . "\n\n";
                        break;
                    case 'pinned-image':
                        $textContent .= writerToPlainText($blockData['content']['text'] ?? '') . "\n\n";
                        break;
                    }
                }
            }

            $input['text_content'] = trim($textContent);
        }

        return parent::update($input, $languageCode, $validate);
    }
}
