<?php

namespace App\Providers;

use App\Models\Module;
use App\Models\Setting;
use App\Models\Language;
;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Schema;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\User\Enums\UserRoleEnum;
use Modules\User\Services\ModuleService;

class AppServiceProvider extends ServiceProvider
{
    protected static $meta = null;

    /**
     * Register any application orders.
     *
     * @return void
     */

    /**
     * @return null
     */
    public static function getMeta()
    {
        return self::$meta;
    }

    public function register()
    {

    }

    /**
     * Bootstrap any application orders.
     *
     * @return void
     */
    public function boot()
    {
        date_default_timezone_set('Asia/Riyadh');

        // Fix migrate issue associated with index key length
        Schema::defaultStringLength(191);


        View::composer('*', function ($view) {
            // Current Lang
            $languages = Language::cursor();
            $view->with('languages', $languages);

            $view->with('lang', LaravelLocalization::getCurrentLocale());

            $isNotAdminRoute = request()->route() ? (strpos(request()->route()->getPrefix(), 'admin') === false) : true;
            $routePath = $this->app->request->getRequestUri();
            $routePath = explode('/', trim($routePath, '/'));
            // dd($isNotAdminRoute, count($routePath), request()->path());

            $activeMenu = [];
            if (!$isNotAdminRoute) {
                if ('admin' == $routePath[0]) {
                    // dd($routePath);
                    $activeMenu[$routePath[1] ?? ""] = 'active';
                    $view->with('activeMenu', $activeMenu);
                } elseif (isset($routePath[1]) && 'admin' == $routePath[1]) {
                    $activeMenu[$routePath[2] ?? ""] = 'active';
                    $view->with('activeMenu', $activeMenu);
                }
            } else {
                // Web


            }
            $modules = [];
            $userInfo = (object) ['photo' => 'uploads/avatar.png'];
            // Current User Info
            if (Auth::user()) {
                if (Auth::check() && in_array(Auth::user()->role, UserRoleEnum::admins())) {
                    $userInfo = User::where('id', Auth::id())->whereIn('role', UserRoleEnum::admins())->first();
                    if (!is_file(public_path(Auth::user()->photo))) {
                        $userInfo->photo = 'uploads/avatar.png';
                    }
                    $moduleService = $this->app->make(ModuleService::class);
                    $modules = $moduleService->get(['user_id' => Auth::id()]);
                }
                $view->with('currentUserInfo', $userInfo);
            }
            $view->with('modules', $modules);

            $exceptedModules = ['settings', 'orders', 'banners', 'brands', 'newsletters', 'pages', 'suppliers',];
            $view->with('exceptedModules', $exceptedModules);

            // Share meta for Modules instead of language orders
            if (Schema::hasTable('Modules')) {

                if (preg_match('/admin/', URL::current())) {
                    $path = explode('.', Route::currentRouteName());
                    if (preg_match('/_/', $path[0])) {
                        $path = explode('_', $path[0]);
                        $path = $path[0] . ucfirst($path[0]);
                    } else {
                        $path = $path[0];
                    }

                    $module = Module::where('path', $path)->pluck('meta')->toArray();

                    $meta = array_first($module);
                    static::$meta = $meta;
                    $view->with('meta', $meta);
                }
            }

        });

        // Email configuration Got from settings

        if (Schema::hasTable('settings')) {
            $settings = Setting::cursor();

            if (count($settings) > 0) {
                foreach ($settings as $setting) {
                    $settings->{$setting['key']} = $setting['value'];
                }

                Config::set('app.name', $settings->website_name);
                Config::set('mail.name', $settings->website_name);
                Config::set('mail.driver', $settings->mail_driver);
                Config::set('mail.host', $settings->mail_host);
                Config::set('mail.port', $settings->mail_port);
                Config::set('mail.username', $settings->mail_username);
                Config::set('mail.password', $settings->mail_password);
                Config::set('mail.from', [
                    'address' => $settings->mail_from_address,
                    'name' => $settings->mail_from_name,
                ]);

            }
        }

    }
}
