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

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

class PluginsHandler
{
    /**
     * @var PluginApi
     */
    private $api;

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

    public function __construct(PluginApi $dep, FileManager $fileManager)
    {
        $this->api         = $dep;
        $this->fileManager = $fileManager;
    }

    /**
     * Run bulk or single action
     *
     * @return void
     */
    public function runAction()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'premmerce')), 403);
        }

        $option = isset($_REQUEST['option']) ? sanitize_text_field($_REQUEST['option']) : null;
        $plugin = isset($_REQUEST['value']) ? sanitize_text_field($_REQUEST['value']) : null;
        $nonce  = isset($_REQUEST['nonce']) ? $_REQUEST['nonce'] : null;

        if (false === wp_verify_nonce($nonce, 'premmerce_plugins_actions')) {
            wp_send_json_error(array(
                'message' => sprintf(
                    __('Sorry, You are not allowed to %s this plugin.', 'premmerce'),
                    $option && in_array(strtolower($option), array( 'activate', 'install' )) ? $option : 'operate'
                ),
            ), 403);
        }


        if ($option && $plugin) {

            $plugin = urldecode($plugin);

            switch ($option) {
                case 'activate':
                    $callback = array($this->api, 'activatePlugin');
                    break;
                case 'install':
                    $callback = array($this->api, 'installPlugin');
                    break;
                case 'deactivate':
                    $callback = array($this->api, 'deactivatePlugin');
                    break;
                case 'activate_theme':
                    $callback = array($this->api, 'activateTheme');
                    break;
                default:
                    $callback = array();
            }

            if (is_callable($callback)) {
                $result = call_user_func($callback, $plugin);

                if (!$result) {
                    wp_send_json(array('success' => false, 'errorMessage' => __('Plugin installation failed.')));
                } elseif ($result instanceof \WP_Error) {
                    wp_send_json(array('success' => false, 'errorMessage' => $result->get_error_message()));
                } else {
                    wp_send_json(array('success' => true));
                }
            }


        }

    }
}
