<?php

namespace Booktics\Extensions\Controllers;

use Booktics\Abstracts\Base_Rest_Controller;
use Booktics\Extensions\Plugin_Manager;
use Arraytics\ToolsSdk\PluginManager as SdkPluginManager;
use WP_HTTP_Response;

class Extension_Controller extends Base_Rest_Controller {
    /**
     * Store namespace of api
     *
     * @var string
     */
    protected $namespace = 'booktics/v1';

    /**
     * Store base url
     *
     * @var string
     */
    protected $base = 'extensions';

    /**
     *
     *
     * @return void
     */
    public function register_routes(): void {
        register_rest_route(
            $this->namespace, $this->base, array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array(
						$this,
						'get_items_permissions_check',
					),
				),
            )
        );

        register_rest_route(
            $this->namespace, $this->base, array(
				array(
					'methods'             => \WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => array(
						$this,
						'update_item_permissions_check',
					),
				),
            )
        );
    }

    /**
     * Check if a given request has access to get items
     *
     * @param $request
     *
     * @return bool|\WP_Error
     */
    public function get_items_permissions_check( $request ) {
        return current_user_can( 'manage_options' );
    }

    /**
     * Get all extensions
     *
     * @param $request
     *
     * @return WP_HTTP_Response
     */
    public function get_items( $request ) {
        $type = ! empty( $request['type'] ) ? sanitize_key( $request['type'] ) : 'addon';

        $extensions = array_values(
            array_filter(
                Plugin_Manager::extensions(),
                function ( $extension ) use ( $type ) {
                    return $extension['type'] === $type;
                }
            )
        );

        $extensions = array_map(
            function ( $extension ) {
                $extension['status'] = 'install';
                if ( SdkPluginManager::is_installed( $extension['slug'] ) ) {
                    $extension['status'] = 'activate';
                }
                if ( SdkPluginManager::is_activated( $extension['slug'] ) ) {
                    $extension['status'] = 'deactivate';
                }

                return $extension;
            }, $extensions
        );

        return $this->response( $extensions );
    }

    /**
     * Check if a given request has access to get items
     *
     * @param $request
     *
     * @return bool|\WP_Error
     */
    public function update_item_permissions_check( $request ) {
        return current_user_can( 'manage_options' );
    }

    /**
     * Enable or disable extension
     *
     * @param $request
     *
     * @return  WP_HTTP_Response
     */
    public function update_item( $request ) {
        $input_data = json_decode( $request->get_body(), true );
        $name       = $input_data['name'];
        $status     = $input_data['status'];

        $statuses   = array( 'off', 'on', 'install', 'activate', 'deactivate' );
        $extensions = Plugin_Manager::extensions();
        if ( ! $name ) {
            return $this->error( __( 'Please enter extension name', 'booktics' ) );
        }

        if ( ! $status ) {
            return $this->error( __( 'Please enter status', 'booktics' ) );
        }

        if ( ! in_array( $status, $statuses ) ) {
            return $this->error( __( 'Please enter status on/off', 'booktics' ) );
        }

        if ( ! isset( $extensions[ $name ] ) ) {
            return $this->error( __( 'Invalid extension', 'booktics' ) );
        }
        $extension = $extensions[ $name ];
        if ( 'addon' === $extension['type'] ) {
            $result = null;

            if ( in_array( $status, array( 'install', 'activate' ) ) ) {
                $result = Plugin_Manager::install_plugin( $extension['slug'] );
                if ( $result ) {
                    $result = Plugin_Manager::activate_plugin( $extension['slug'] );
                }
            }

            if ( 'deactivate' === $status && Plugin_Manager::is_activated( $extension['slug'] ) ) {
                $result = Plugin_Manager::deactivate_plugin( $extension['slug'] );
            }

            if ( is_wp_error( $result ) ) {
                return $this->error( __( 'Extension installation error', 'booktics' ) );
            }

            if ( ! $result ) {
                 // translators: %s is the action performed on the extension (install, activate, deactivate, etc.)
                return $this->error( sprintf( __( 'Extension couldn\'t %s', 'booktics' ), $status ) );
            }
        }

        if ( 'plugin' === $extension['type'] ) {
            $result = null;

            if ( 'install' === $status ) {
                $result = SdkPluginManager::install_plugin( $extension['slug'] );
                if ( $result ) {
                    $result = SdkPluginManager::activate_plugin( $extension['slug'] );
                }
            } elseif ( 'activate' === $status ) {
                $result = SdkPluginManager::activate_plugin( $extension['slug'] );
            } elseif ( 'deactivate' === $status ) {
                $result = SdkPluginManager::deactivate_plugin( $extension['slug'] );
            }

            if ( is_wp_error( $result ) ) {
                return $this->error( __( 'Plugin operation error', 'booktics' ) );
            }

            if ( false === $result ) {
                // translators: %s is the action performed on the plugin (install, activate, deactivate, etc.)
                return $this->error( sprintf( __( 'Plugin couldn\'t %s', 'booktics' ), $status ) );
            }
        }

        $response = Plugin_Manager::extensions()[ $name ];
        $response['status'] = 'install';
        if ( SdkPluginManager::is_installed( $response['slug'] ) ) {
            $response['status'] = 'activate';
        }
        if ( SdkPluginManager::is_activated( $response['slug'] ) ) {
            $response['status'] = 'deactivate';
        }

        return $this->response( $response, __( 'Successfully updated', 'booktics' ) );
    }
}
