<?php

namespace Modules\ClinicSite\Providers;

use Illuminate\Support\ServiceProvider;
use Modules\ClinicSite\Http\Middleware\ResolveTenantSite;

class ClinicSiteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerConfig();
        $this->registerViews();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->registerTranslations();
        $this->registerTenantMiddleware();
    }

    public function register()
    {
        $this->app->register(RouteServiceProvider::class);
    }

    /**
     * The public clinic website is served on any host that is NOT an ERP/admin
     * host. The resolver runs as GLOBAL middleware (before the router) so a
     * clinic site can own the root "/" of its own host without colliding with
     * the ERP's root routes. On admin hosts it is a fast no-op.
     */
    protected function registerTenantMiddleware()
    {
        $this->app['router']->aliasMiddleware('site.resolve', ResolveTenantSite::class);

        $kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);
        if (method_exists($kernel, 'prependMiddleware')) {
            $kernel->prependMiddleware(ResolveTenantSite::class);
        }
    }

    protected function registerConfig()
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('clinicsite.php'),
        ], 'config');
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'clinicsite');
    }

    public function registerViews()
    {
        $viewPath   = resource_path('views/modules/ClinicSite');
        $sourcePath = __DIR__ . '/../Resources/views';

        $this->publishes([$sourcePath => $viewPath], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/clinicSite';
        }, \Config::get('view.paths')), [$sourcePath]), 'clinicSite');
    }

    public function registerTranslations()
    {
        $langPath = resource_path('lang/modules/ClinicSite');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'clinicSite');
        } else {
            $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'clinicSite');
        }
    }

    public function provides()
    {
        return [];
    }
}
