<?php

namespace WeDevs\AppBridge\Integrations\Dokan\REST;

use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class ModuleController extends WP_REST_Controller {

    /**
     * Endpoint namespace
     *
     * @var string
     */
    protected $namespace = 'app-bridge/v1';

    /**
     * Route name
     *
     * @var string
     */
    protected $base = 'dokan/modules';

    /**
     * Register all routes releated with stores
     *
     * @return void
     */
    public function register_routes() {
        register_rest_route(
            $this->namespace, '/' . $this->base, array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => '__return_true',
				),
            )
        );
    }

    /**
     * Get modules
     *
     * @since 1.0.0
     *
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response|WP_Error
     */
    public function get_items( $request ) {
        // check if Dokan Pro plugin is active
        if ( ! function_exists( 'dokan_pro' ) ) {
            return rest_ensure_response( new WP_Error( 'dokan-pro-is-not-installed', __( 'You need to install and activate Dokan Pro plugin in order to use this feature.', 'app-bridge' ) ) );
        }

        $data = array();

        $modules      = dokan_pro()->module->get_all_modules();
        $actives      = dokan_pro()->module->get_active_modules();
        $result       = array();
        $active_count = 0;

        foreach ( $modules as $module_file => $module ) {
            $is_active = in_array( $module_file, $actives, true );

            if ( $is_active ) {
                ++$active_count;
            }

            $data[] = array(
                'name'      => $module['name'],
                'slug'      => $module_file,
                'thumbnail' => $module['thumbnail'],
                'active'    => $is_active,
            );
        }

        $response = rest_ensure_response( $data );

        $response->header( 'X-WP-Total', count( $modules ) );
        $response->header( 'X-WP-Active', $active_count );

        return $response;
    }
}
