<?php namespace Premmerce\Premmerce\Admin\Handlers;

use Premmerce\Premmerce\Api\WizardApi;
use Premmerce\SDK\V2\FileManager\FileManager;

class WizardHandler
{
    /**
     * @var WizardApi
     */
    private $helper;

    /**
     * @var FileManager
     */
    private $fileManager;

    /**
     * @param WizardApi $helper
     * @param FileManager $fileManager
     */
    public function __construct(WizardApi $helper, FileManager $fileManager)
    {
        $this->helper      = $helper;
        $this->fileManager = $fileManager;
    }

    /**
     * Handle action
     */
    public function runAction()
    {

        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(wp_unslash($_POST['_wpnonce']), 'premmerce_wizard_actions')) {
            wp_send_json_error(array('message' => __('Security check failed.', 'premmerce')), 403);
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'premmerce')), 403);
        }

        if (isset($_POST['update'])) {
            $update = sanitize_text_field($_POST['update']);
            switch ($update) {
                case 'position':
                    $positions = isset($_POST['positions']) && is_array($_POST['positions']) ? array_map('sanitize_text_field', $_POST['positions']) : array();
                    $this->helper->updatePositions($positions);
                    break;
                case 'state':
                    $task  = isset($_POST['task']) ? sanitize_text_field($_POST['task']) : '';
                    $state = isset($_POST['state']) ? sanitize_text_field($_POST['state']) : '';
                    $this->helper->updateState($task, $state);
                    break;
                case 'container-state':
                    $this->handleContainerState();
                    break;

            }
        }

    }

    public function handleContainerState()
    {
        $state = isset($_POST['state']) ? sanitize_text_field($_POST['state']) : '';
        $this->helper->updateContainerState($state);

        wp_send_json($this->fileManager->renderTemplate('admin/tabs/wizard.php', array(
            'wizard' => $this->helper,
        )));
    }
}
