<?php

namespace PublishPress\FuturePro\Modules\Workflows\Controllers;

use PublishPress\Future\Core\HookableInterface;
use PublishPress\Future\Framework\InitializableInterface;
use PublishPress\Future\Core\HooksAbstract as FutureCoreHooksAbstract;
use PublishPress\Future\Framework\Logger\LoggerInterface;
use PublishPress\Future\Framework\WordPress\Facade\RequestFacade;
use PublishPress\Future\Modules\Expirator\Models\CurrentUserModel;
use PublishPress\Future\Modules\Workflows\Domain\Steps\Triggers\Runners\OnPostRowActionRunner;
use PublishPress\FuturePro\Core\Utils;
use PublishPress\FuturePro\Modules\Workflows\HooksAbstract;

class PostRowActionTrigger implements InitializableInterface
{
    /**
     * @var HookableInterface
     */
    private $hooks;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var RequestFacade
     */
    private $request;

    /**
     * @var CurrentUserModel
     */
    private $currentUserModel;

    public function __construct(
        HookableInterface $hooks,
        LoggerInterface $logger,
        RequestFacade $request,
        CurrentUserModel $currentUserModel
    ) {
        $this->hooks = $hooks;
        $this->logger = $logger;
        $this->request = $request;
        $this->currentUserModel = $currentUserModel;
    }

    public function initialize()
    {
        $this->hooks->addAction(
            FutureCoreHooksAbstract::ACTION_ADMIN_INIT,
            [$this, 'processPostRowAction'],
            10,
            2
        );

        $this->hooks->addAction(
            FutureCoreHooksAbstract::ACTION_ADMIN_ENQUEUE_SCRIPTS,
            [$this, 'enqueueScripts']
        );
    }


    public function processPostRowAction()
    {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        if (! isset($_GET['action']) || $_GET['action'] !== 'ppfuture-run-post-row-action') {
            return;
        }

        $this->request->checkAdminReferer(OnPostRowActionRunner::NONCE_RUN_POST_ROW_ACTION);

        if (! isset($_GET['stepId']) || ! isset($_GET['workflowId']) || ! isset($_GET['postId'])) {
            return;
        }

        $stepId = sanitize_text_field($_GET['stepId']);
        $workflowId = (int)$_GET['workflowId'];
        $postId = (int)$_GET['postId'];

        if (empty($stepId) || empty($workflowId) || empty($postId)) {
            $this->logger->debug(
                sprintf(
                    'Invalid input: step ID: %1$s, workflow ID: %2$s, post ID: %3$s',
                    $stepId,
                    $workflowId,
                    $postId
                )
            );

            return;
        }

        $this->logger->debug(
            sprintf(
                'Start running post row action | Step ID: %1$s | Workflow ID: %2$s | Post ID: %3$s',
                $stepId,
                $workflowId,
                $postId
            )
        );

        $this->hooks->doAction(HooksAbstract::ACTION_RUN_POST_ROW_ACTION, $stepId, $workflowId, $postId);

        $this->logger->debug(
            sprintf(
                'Finish running post row action. Redirecting to post edit page | Step ID: %1$s | Workflow ID: %2$s | Post ID: %3$s', // phpcs:ignore Generic.Files.LineLength.TooLong
                $stepId,
                $workflowId,
                $postId
            )
        );

        $postType = get_post_type($postId);

        // Redirect to the post edit page
        wp_redirect(admin_url('edit.php?post_type=' . $postType));
        exit;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
    }

    public function enqueueScripts()
    {
        wp_enqueue_script(
            'ppfuture-post-row-actions',
            Utils::getScriptUrl('postRowActions'),
            [
                'wp-element',
                'wp-components',
                'wp-i18n',
            ],
            PUBLISHPRESS_FUTURE_PRO_PLUGIN_VERSION,
            true
        );
    }
}
