<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\Core\Admin\Pointers;

use Inpsyde\Assets\Asset;
use Inpsyde\Assets\AssetManager;
use Inpsyde\Assets\Script;
use Inpsyde\MultilingualPress\Framework\Http\Request;

class Pointers
{
    public const USER_META_KEY = '_dismissed_mlp_pointers';
    public const ACTION_AFTER_POINTERS_CREATED = 'multilingualpress.after_pointers_created';
    public const SCRIPTS_HANDLER_NAME = 'pointers';

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var Repository
     */
    protected $repository;

    /**
     * @var string
     */
    protected $urlToAssetsFolder;

    public function __construct(Request $request, Repository $repository, string $urlToAssetsFolder)
    {
        $this->request = $request;
        $this->repository = $repository;
        $this->urlToAssetsFolder = $urlToAssetsFolder;
    }

    /**
     * @return void
     */
    public function createPointers()
    {
        if (!current_user_can('create_sites')) {
            return;
        }

        $screen = get_current_screen();
        if (!$screen->id) {
            return;
        }

        list($pointers, $ajaxAction) = $this->repository->forScreen($screen->id);
        if (!$pointers) {
            return;
        }

        $dismissedPointers = explode(
            ',',
            (string)get_user_meta(get_current_user_id(), self::USER_META_KEY, true)
        );
        if ($this->currentPointersDismissed(array_keys($pointers), $dismissedPointers)) {
            return;
        }

        $this->enqueuePointers($pointers, $ajaxAction);

        do_action(self::ACTION_AFTER_POINTERS_CREATED, $screen);
    }

    /**
     * @param array $pointers
     * @param string $ajaxAction
     * @return void
     */
    public function enqueuePointers(array $pointers, string $ajaxAction)
    {
        wp_enqueue_style('wp-pointer');
        wp_enqueue_script('wp-pointer');
        $urlToAssetsFolder = $this->urlToAssetsFolder;

        add_action(
            AssetManager::ACTION_SETUP,
            static function (AssetManager $assetManager) use ($urlToAssetsFolder, $pointers, $ajaxAction) {
                $script = new Script(self::SCRIPTS_HANDLER_NAME, "{$urlToAssetsFolder}js/pointers.min.js");
                $script
                    ->withLocalize('multilingualPressPointersData', [
                        'pointers' => $pointers,
                        'dismissButtonText' => _x('Dismiss guide', 'pointers', 'multilingualpress'),
                        'okButtonText' => _x('OK', 'pointers', 'multilingualpress'),
                        'ajaxurl' => esc_url(admin_url('admin-ajax.php')),
                        'ajaxAction' => $ajaxAction,
                    ])
                    ->forLocation(Asset::BACKEND);

                $assetManager->register($script);
            }
        );
    }

    /**
     * @return void
     */
    public function dismiss()
    {
        $pointer = $this->request->bodyValue('pointer', INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
        if (!$pointer) {
            return;
        }

        $dismissedPointers = explode(
            ',',
            (string)get_user_meta(get_current_user_id(), self::USER_META_KEY, true)
        );

        if (in_array($pointer, $dismissedPointers, true)) {
            return;
        }

        $dismissedPointers[] = $pointer;
        $dismissed = implode(',', $dismissedPointers);

        update_user_meta(get_current_user_id(), self::USER_META_KEY, $dismissed);
    }

    /**
     * @param array $pointers
     * @param array $dismissedPointers
     * @return bool
     */
    private function currentPointersDismissed(array $pointers, array $dismissedPointers): bool
    {
        foreach ($pointers as $pointer) {
            if (in_array($pointer, $dismissedPointers, true)) {
                return true;
            }
        }

        return false;
    }
}
