<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use App\Listeners\LogUserLoginActivity;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //Schema::defaultStringLength(191);

        // register login even
        Event::listen(
            [Login::class, Logout::class],
            [LogUserLoginActivity::class, 'handle']
        );

         // Check if the user is authenticated
        View::composer('*', function ($view) {
            // get app settings
            $settings_views = [
                'layouts.app',
                'tools.images_manager',
                'auth.login',
                'auth.passwords.email',
                'auth.passwords.reset',
                'errors::404'
            ];

            $view_name = $view->getName();
            // No need to execute the queries for all views
            if($view_name == 'layouts.login') {
                if(!file_exists(storage_path('app/installed'))) {
                  header('Location: '. url('/').'/install/setup.php');
                  exit;
                }
            }

            if(in_array($view_name, $settings_views)) {
                try {
                    $app_name = \App\Models\Setting::where('id', config('custom.app_id'))->value('app_name');
                    // Share the app name with all views
                    View::share('app_name', $app_name);
                } catch(\Exception $e) {}
            }

            if($view_name == 'layouts.app') {
                try {
                    // get notifications inside if due to Auth not availabe outside
                    $notifications = \App\Models\Notification::notifications();
                    View::share('notifications', $notifications);
                    if(Auth::user()) {
                      View::share('time_zone', Auth::user()->timezone);
                    }
                } catch(\Exception $e) {}
            }
        });
        
    }
}
