<?php

namespace App\Providers;

use App\Models\Cart;
use App\Models\Way;
use App\Models\Category;
use App\Models\Country;
use App\Models\Favorite;
use App\Models\Module;
use App\Models\Notification;
use App\Models\Page;
use App\Models\Setting;
use App\Models\Language;;
use App\Models\User;
use App\Services\Auth\User\AccountService;
use App\Services\Currency\CurrencyService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
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 services.
     *
     * @return void
     */

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

    public function register()
    {

    }

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

        // 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;
            }
            
            $account = (new AccountService())->getAccount();
            if(!$account)
            {
                $account = (new AccountService())->setAccount();
            }
            
        
            $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_address',
                    'site_phone',
                    'login_status',
                    'resetpassword_status',
                    'verification_pdf',
                    'tax_valid',
                    'tax_value',
                    'seller_percentage',
                    'map_link',
                    'telegram',
                    'instagram',
                    'twitter',
                    'facebook',
                ]);
                $view->with('settings', $settings);
                $footer = Page::withDescription(4)->first();
                $view->with('footer', $footer);
                $newsletter = Page::withDescription(3)->first();
                $view->with('newsletter', $newsletter);
                
                $waysFooter = Way::cursor();
                $view->with('waysFooter', $waysFooter);
                
                $popup = Page::withDescription(26)->first();
                $view->with('popup', $popup);
                

                $account =(new AccountService())->getAccount();
                $view->with('account', $account);
                $status = $account['status'];
                $user = $account['user'];
                if($user)
                {
                    $count_cart  = Cart::where('status',$status)->where('user_id',$user->id)->sum('count');
                    $count_fav  = Favorite::where('status',$status)->where('user_id',$user->id)->count();
                }
                else
                {
                    $count_cart  = 0;
                    $count_fav  = 0;
                }
                $view->with('count_cart', $count_cart);
                $view->with('count_fav', $count_fav);
                if($status == 'visitor')
                {
                    $count_notifications  = 0;
                }
                else
                {
                    $count_notifications  = Notification::where('user_id',$user->id)->where('read_at',null)->count();
                }
                $view->with('count_notifications', $count_notifications);
                $nav_categories = Category::withDescription()->where('categories.category_id',null)->cursor();
                $view->with('nav_categories', $nav_categories);
                $header_countries = Country::withDescription()->cursor();
                $view->with('header_countries', $header_countries);
                $currency =(new CurrencyService())->getCurrency();
                $view->with('currency', $currency);
            }

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

            }
        }

    }
}
