<?php

namespace Edoobox\Base;

use Edoobox\Api\ShortcodeApi;
use Edoobox\Helpers\Arr;
use Edoobox\Requests\Page;
use Edoobox\Requests\Template;

class DocumentHead {

    private Template $template;

    public function register() {
        $postIsNotBeingEdited = ! (isset($_REQUEST["context"]) && $_REQUEST["context"] === "edit");
        $settings = new Settings();
        $preventSEO = $settings->get(BaseController::SETTINGS_PREVENT_SEO);
        if ( Auth::isGuest() && $postIsNotBeingEdited && ! $preventSEO ) {
            add_action('wp_head', [$this, 'startBuffering'], $settings->get(BaseController::SETTINGS_SEO_PRIORITY) ?? 10);
        }
    }

    public function startBuffering() {
        global $post;
        if (ShortcodeApi::hasShortcode($post) || isset($_GET['edref'])) {
            // If not run with buffer, then existing og tags are not replaced,
            // and you end up with duplicated og tags.
            ob_start([$this, 'addDocumentHead']);
        }
    }

    public function addDocumentHead($buffer) {
        $buffer = $this->removeOgTags($buffer);
        $metaValues = $this->getMetaValues();

        // Add custom edoobox tags
        // note: when adding new tags, also check removeOgTags()-method below.
        $customTags = '<!-- edoobox (start) -->';
        $customTags .= '<meta name="generator" content="edoobox" />';
        // Open Graph Protocol
        $customTags .= '<meta property="og:description" content="' . $metaValues['description'] . '" />' . "\n";
        $customTags .= '<meta property="og:locale" content="' . $metaValues['language'] . '" />' . "\n";
        $customTags .= '<meta property="og:site_name" content="' . $metaValues['site_name'] . '" />' . "\n";
        $customTags .= '<meta property="og:sitename" content="' . $metaValues['site_name'] . '" />' . "\n";
        $customTags .= '<meta property="og:title" content="' . $metaValues['title'] . '" />' . "\n";
        $customTags .= '<meta property="og:type" content="' . $metaValues['type'] . '" />' . "\n";
        $customTags .= '<meta property="og:url" content="' . $metaValues['url'] . '" />' . "\n";

        $customTags .= '<meta property="og:image" content="' . $metaValues['image300'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:alt" content="' . $metaValues['title'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:secure_url" content="' . $metaValues['image300'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:height" content="200" />' . "\n";
        $customTags .= '<meta property="og:image:width" content="300" />' . "\n";

        $customTags .= '<meta property="og:image" content="' . $metaValues['image600'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:alt" content="' . $metaValues['title'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:secure_url" content="' . $metaValues['image600'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:height" content="400" />' . "\n";
        $customTags .= '<meta property="og:image:width" content="600" />' . "\n";

        $customTags .= '<meta property="og:image" content="' . $metaValues['image900'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:alt" content="' . $metaValues['title'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:secure_url" content="' . $metaValues['image900'] . '" />' . "\n";
        $customTags .= '<meta property="og:image:height" content="600" />' . "\n";
        $customTags .= '<meta property="og:image:width" content="900" />' . "\n";

        // Twitter Protocol
        $customTags .= '<meta property="twitter:card" content="' . $metaValues['twitter:card'] . '" />' . "\n";
        $customTags .= '<meta property="twitter:title" content="' . $metaValues['title'] . '" />' . "\n";
        $customTags .= '<meta property="twitter:description" content="' . $metaValues['description'] . '" />' . "\n";
        // Other Tags
        $customTags .= "<style>" . $metaValues['css'] . "</style>";
        $customTags .= '<!-- edoobox (end) -->';

        return str_replace('</head>', $customTags . '</head>', $buffer); // return edited buffer
    }

    private function getMetaValues(): array {
        global $post;

        $attributes = ShortcodeApi::getAttributes($post);
        $this->template = new Template($attributes);
        $data = $this->template->fetch();
        $title = Arr::get($data, 'api.data.header.title') ?: get_the_title($post);
        $description = Arr::get($data, 'api.data.header.shortdescrip') ?: get_the_excerpt($post);
        $url = Page::get_current_url() ?: get_permalink($post);
        $fallbackImage = plugin_dir_url(dirname(__DIR__)) . 'assets/og-fallback-offer-image-compressed.png';
        $image300 = Arr::get($data, 'api.data.header.image_url.300') ?:
            get_the_post_thumbnail_url($post, 'full') ?: $fallbackImage;
        $image600 = Arr::get($data, 'api.data.header.image_url.600') ?:
            get_the_post_thumbnail_url($post, 'full') ?: $fallbackImage;
        $image900 = Arr::get($data, 'api.data.header.image_url.900') ?:
            get_the_post_thumbnail_url($post, 'full') ?: $fallbackImage;
        $cssHeight = "<style>" . (Arr::get($data, 'api.data.header.css_height') ?: '') . "</style>";

        return [
            'css' => $cssHeight,
            'description' => esc_attr($description),
            'image300' => esc_url($image300),
            'image600' => esc_url($image600),
            'image900' => esc_url($image900),
            'language' => Arr::get($this->template->attributes, 'language'),
            'site_name' => get_bloginfo('name'),
            'title' => esc_attr($title),
            'type' => 'website',
            'url' => esc_url($url),
            'twitter:card' => 'summary_large_image'
        ];
    }

    private function removeOgTags(string $buffer): string {
        $buffer = preg_replace('/<meta name="generator"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:description"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:locale"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:site_name"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:title"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:type"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:url"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:image"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:image:alt"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta property="og:image:secure_url"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta name="twitter:card"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta name="twitter:title"[^>]+>/i', '', $buffer);
        $buffer = preg_replace('/<meta name="twitter:description"[^>]+>/i', '', $buffer);
        return $buffer;
    }

    public function removeOgTagsFromMainContent($content) {
        $content = preg_replace('/<meta name="generator"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:description"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:locale"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:site_name"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:title"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:type"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:url"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:image"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:image:alt"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta property="og:image:secure_url"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta name="twitter:card"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta name="twitter:title"[^>]+>/i', '', $content);
        $content = preg_replace('/<meta name="twitter:description"[^>]+>/i', '', $content);
        return $content;
    }

}