<?php

namespace ScfPriceUpdater\Pages\Admin;

use ScfPriceUpdater\Assets;
use ScfPriceUpdater\Options;
use ScfPriceUpdater\Pages\AdminPage;
use ScfPriceUpdater\Utils;

class DescriptionPage extends AdminPage
{

    private const MENU_SLUG = 'scf-description';

    public function __construct()
    {
        $this->menuSlug = self::MENU_SLUG;
        parent::__construct('description', 'admin');
    }

    public function init()
    {
        if (isset($_POST['description_text'])) {
            if (wp_verify_nonce($_POST['_wpnonce'], 'scf-price-updater')) {
                $descriptionBody = sanitize_text_field($_POST['description_text']);
                $limit = (int) $_POST['count_limit'];
                $skipDescription = isset($_POST['skip_description']);
                Options::updateOption('description_text', $descriptionBody);
                Options::updateOption('skip_description', $skipDescription);
                Options::updateOption('count_limit', $limit);

                $products = wc_get_products([
                    'visibility' => 'catalog',
                    'status' => 'publish',
                    'limit' => -1
                ]);

                $updateAmount = 0;
                foreach ($products as $product) {
                    if ($product->get_price() && $product->get_description()) {
                        $description = $product->get_description();
                        $productName = $product->get_name();
                        $productBrand = $product->get_attribute('pa_merk');
                        $preDescription = $descriptionBody;

                        if (!empty($description) && !empty($productBrand) && strpos(strtolower($description), strtolower($productBrand)) !== false && $skipDescription) {
                            // Skip
                            continue;
                        }

                        if (strpos($preDescription, '%PRODUCT_NAME%') !== false && empty($productName)) {
                            continue;
                        }

                        if (strpos($preDescription, '%PRODUCT_BRAND%') !== false && empty($productBrand)) {
                            continue;
                        }

                        $preDescription = !empty($productName) ?
                            str_replace('%PRODUCT_NAME%', $productName, $preDescription) : $preDescription;
                        $preDescription = !empty($productBrand) ?
                            str_replace('%PRODUCT_BRAND%', $productBrand, $preDescription) : $preDescription;

                        $previousBody = Utils::getBetweenStr(
                            $description,
                            '<span id="scf-custom-description">',
                            '</span><br />'
                        );
                        if ($previousBody) {
                            $description = str_replace(
                                '<span id="scf-custom-description">' . $previousBody . '</span><br />',
                                '',
                                $description
                            );
                        }

                        if (!empty($preDescription)) {
                            $description = '<span id="scf-custom-description">' . $preDescription . '</span><br />' . $description;
                        }
                        $product->set_description($description);

                        $product->save();
                        $updateAmount++;
                    }
                    if ($updateAmount === $limit) {
                        break;
                    }
                }
                add_action('admin_notices', function () use ($updateAmount) {
                    echo '<div class="notice notice-success is-dismissible">
                            <p><strong>Secoff Updater:</strong> Descriptions have been updated! (Amount changed: ' . $updateAmount . ')</p>
                          </div>';
                });
            } else {
                add_action('admin_notices', function () {
                    echo '<div class="notice notice-error is-dismissible">
                        <p><strong>Secoff Updater:</strong> Invalid NONCE!</p>
                      </div>';
                });
            }
        }
    }

    /**
     * @inheritDoc
     */
    public function buildTwigContext(array $context = [])
    {
        $context['skipDescription'] = Options::getOption('skip_description');
        $context['descriptionBody'] = Options::getOption('description_text');
        $context['countLimit'] = Options::getOption('count_limit');
        return $context;
    }

    /**
     * @inheritDoc
     */
    public function enqueuePageScripts()
    {
        Assets::enqueueCompiledScript('description');
    }

    public function addAdminMenuItem()
    {
        add_submenu_page(
            'updater',
            __('Description Updater'),
            __('Description Updater'),
            'administrator',
            self::MENU_SLUG,
            [$this, 'renderPage'],
        );
    }
}
