<?php

// Silence may be golden, but sometimes words paint the canvas of understanding.
namespace Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers\Post\Editors;

use Linksy\SearchAndReplace\Plugli\Linksy\Common\Helpers\Utils;
class Bricks extends Editors
{
    const META_KEY = '_bricks_page_content_2';
    const SUPPORTED_BLOCKS = ['text-basic', 'text', 'icon-box', 'accordion', 'tabs'];
    const CONTENT_LOCATIONS = ['text', 'content', 'accordions', 'tabs'];
    private $unsupported_ids = [];
    private $extracted_data = '';
    public function __construct($post_id)
    {
        $this->post_id = $post_id;
        $this->content = get_post_meta($post_id, self::META_KEY, \true);
    }
    public static function is_active($post_id): bool
    {
        return get_post_meta($post_id, '_bricks_editor_mode', \true) === 'bricks';
    }
    public function handle_block_ops(&$block_content, $op_code)
    {
        switch ($op_code) {
            case self::OP_CODES['EXTRACT_CONTENT']:
                $this->extracted_data .= wpautop($block_content) . "\n";
                break;
            case self::OP_CODES['ADD_LINK']:
                $this->add_link_to_block($block_content);
                break;
            case self::OP_CODES['REMOVE_LINK']:
                $this->remove_link_from_block($block_content);
                break;
            case self::OP_CODES['REPLACE_LINK']:
                Utils::error_log(['content', $block_content]);
                $this->replace_link_in_block($block_content);
                break;
            default:
                break;
        }
        return $this->link_processed;
    }
    private function extract_content($block, $op_code = self::OP_CODES['EXTRACT_CONTENT'])
    {
        $block_name = $block['name'];
        // name of the block
        if ($block['name'] === 'div' && isset($block['settings'])) {
            if (isset($block['settings']['_hidden']) && isset($block['settings']['_hidden']['_cssClasses'])) {
                if (in_array($block['settings']['_hidden']['_cssClasses'], ['tab-title'])) {
                    $this->unsupported_ids = array_merge($this->unsupported_ids, $block['children']);
                }
            }
        }
        if (!in_array($block['id'], $this->unsupported_ids) && in_array($block_name, self::SUPPORTED_BLOCKS)) {
            foreach (self::CONTENT_LOCATIONS as $prop) {
                if (isset($block['settings'][$prop])) {
                    if (is_array($block['settings'][$prop])) {
                        foreach ($block['settings'][$prop] as $sub_block) {
                            if (isset($block['settings'][$prop]['content'])) {
                                $this->handle_block_ops($block['settings'][$prop]['content'], $op_code);
                            }
                        }
                    } else {
                        $this->handle_block_ops($block['settings'][$prop], $op_code);
                    }
                    break;
                }
            }
        }
        return $block;
    }
    public function get_content($post_id): string
    {
        $this->extracted_data = '';
        if (is_array($this->content)) {
            // extract content from supported blocks
            foreach ($this->content as $block) {
                $this->extract_content($block);
            }
        }
        return $this->extracted_data;
    }
    public function add_link($source, $phrase, $phrase_replacement): bool
    {
        $this->link_processed = \false;
        // set the params for link addition
        $this->params = ['source' => $source, 'phrase' => $phrase, 'replacement' => $phrase_replacement];
        if (is_array($this->content)) {
            foreach ($this->content as &$block) {
                // add link to the block if source found
                $block = $this->extract_content($block, self::OP_CODES['ADD_LINK']);
            }
            if ($this->link_processed) {
                $this->has_unsaved_changes = \true;
                return \true;
            }
        }
        return \false;
    }
    public function update_post($suggestions = null): bool
    {
        if ($this->has_unsaved_changes) {
            $success = update_post_meta($this->post_id, self::META_KEY, $this->content) !== \false;
            if ($success) {
                $this->has_unsaved_changes = \false;
                // sync with wp post content
                $this->after_update_post($suggestions);
                return \true;
            }
        }
        return \false;
    }
    public function remove_link(string $link, string $anchor, $save = \true): bool
    {
        $this->link_processed = \false;
        // set the params for link removal
        $this->params = ['link' => $link, 'anchor' => $anchor];
        if (is_array($this->content)) {
            foreach ($this->content as &$block) {
                // remove link from the block if anchor found
                $block = $this->extract_content($block, self::OP_CODES['REMOVE_LINK']);
            }
            if ($this->link_processed) {
                $this->has_unsaved_changes = \true;
                if ($save) {
                    return $this->update_post();
                }
                return \true;
            }
        }
        return \false;
    }
    public function replace_phrase(string $link, string $phrase, string $replacement, bool $save): bool
    {
        $this->link_processed = \false;
        // set the params that will be used to replace the link
        $this->params = ['link' => $link, 'anchor' => $phrase, 'link_replacement' => $replacement];
        if (is_array($this->content)) {
            foreach ($this->content as &$block) {
                // replace link in the block
                $block = $this->extract_content($block, self::OP_CODES['REPLACE_LINK']);
            }
            if ($this->link_processed) {
                $this->has_unsaved_changes = \true;
                if ($save) {
                    return $this->update_post();
                }
                return \true;
            }
        }
        return \false;
    }
}
