<?php

namespace App\Providers;

use App\Models\Module;
use App\Models\Page;
use App\Models\Setting;
use App\Models\Language;;
use App\Models\User;
use Illuminate\Pagination\Paginator;
use App\Services\Repositories\PageRepository;
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;

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');

        Paginator::useBootstrapFive();

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

        // CMS Supported Languages
        $languages= Language::where('status', 1)->cursor();
        View::share('languages', $languages);

        View::composer('*', function($view) {
            // Current Lang
            $show_popup = false;
            if(!isset($_COOKIE['token']))
            {
                $show_popup = true;
            }


            $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

                $view->with('show_popup', $show_popup);
                // Main Info
                $settings = settings([
                    'website_logo',
                    'website_name',
                    'keywords',
                    'meta_description',
                    'site_email',
                    'site_phone',
                    'instagram',
                    'facebook',
                    'tiktok',
                    'whatsapp',
                    'opining_time',
                ]);
                $settings['opining_time'] = getCurrentLocale() == 'en' ? settings('opining_time_en') : settings('opining_time_ar');
                $settings['site_address'] = getCurrentLocale() == 'en' ? settings('site_address_en') : settings('site_address_ar');

                $view->with('settings', $settings);
                $page = Page::find(9);
                $footer = (new PageRepository())->getItem($page);
                $view->with('footer', $footer);

            }

            // Current User Info
            if(Auth::user())
            {
            $userInfo= (object) ['photo'=> 'uploads/avatar.png'];
            if(Auth::check() && !in_array(Auth::user()->role , ['user','company'])){
                $userInfo= User::where('id', Auth::id())->whereIn('role', ['super_admin', 'admin', 'sub_admin','user','provider'])->first();
                if (!is_file(public_path(Auth::user()->photo))) {
                    $userInfo->photo= 'uploads/avatar.png';
                }

                // Get Modules Current User can access
                if (in_array(Auth::user()->role, ['super_admin', 'admin']) || Auth::user()->admin_token) {
                    $userInfo->modules = Module::where('deleted_at', null)->cursor();
                }

                if (Auth::user()->role == 'sub_admin') {
                    Auth::user()->modules = Module::where('deleted_at', null)
                        ->join('user_modules as um', 'um.module_id', 'modules.id')
                        ->where('um.user_id', Auth::user()->id)
                        ->select(['modules.*', 'um.*'])->cursor();
                }

            }
            $view->with('currentUserInfo', $userInfo);

            }
            // 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,
                ]);

            }
        }

    }
}
