<?php

namespace $PLUGIN_NAMESPACE$;

use Route;
use Illuminate\Database\Eloquent\Factory;
use Vanguard\Plugins\Plugin;
use App\Support\Sidebar\Item;

class $STUDLY_NAME$ extends Plugin
{
    /**
     * A sidebar item for the plugin.
     */
    public function sidebar(): ?Item
    {
        return null;
    }

    /**
     * Register plugin services required.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function boot(): void
    {
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        $this->loadViewsFrom(__DIR__ . '/../resources/views', '$SNAKE_NAME$');
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        $this->mapRoutes();

        $this->registerFactories();
    }

    /**
     * Register plugin configuration files.
     */
    protected function registerConfig(): void
    {
        $configPath = __DIR__.'/../config/config.php';

        $this->publishes([$configPath => config_path('$SNAKE_NAME$.php')], 'config');

        $this->mergeConfigFrom($configPath, '$SNAKE_NAME$');
    }

    /**
     * Register plugin views.
     *
     * @return void
     */
    protected function registerViews(): void
    {
        $viewsPath = __DIR__.'/../resources/views';

        $this->publishes([
            $viewsPath => resource_path('views/plugins/$SNAKE_NAME$')
        ], 'views');

        $this->loadViewsFrom($viewsPath, '$SNAKE_NAME$');
    }

    /**
     * Map all plugin related routes.
     */
    protected function mapRoutes(): void
    {
        $this->mapWebRoutes();

        if ($this->app['config']->get('auth.expose_api')) {
            $this->mapApiRoutes();
        }
    }

    /**
     * Map web plugin related routes.
     */
    protected function mapWebRoutes(): void
    {
        Route::group([
            'namespace' => '$PLUGIN_NAMESPACE$\Http\Controllers\Web',
            'middleware' => 'web',
        ], function () {
            $this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
        });
    }

    /**
     * Map API plugin related routes.
     */
    protected function mapApiRoutes(): void
    {
        Route::group([
            'namespace' => '$PLUGIN_NAMESPACE$\Http\Controllers\Api',
            'middleware' => 'api',
            'prefix' => 'api',
        ], function () {
            $this->loadRoutesFrom(__DIR__ . '/../routes/api.php');
        });
    }

    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    private function registerFactories(): void
    {
        if (! $this->app->environment('production') && $this->app->runningInConsole()) {
            $this->app->make(Factory::class)->load(__DIR__ . '/../database/factories');
        }
    }
}
