<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\View;
use Illuminate\Pagination\Paginator;
use Illuminate\Http\Request;
use App\Http\Traits\AgentTrait;
use App\Models\Config;

class AppServiceProvider extends ServiceProvider
{
    use AgentTrait;

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
        uopz_allow_exit(true);
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Request $request)
    {
        Paginator::useBootstrap(); // 페이지 네이션 부트스트랩 사용

        config((array)(new Config())->getAllMeta());

        $baseURL = env('APP_URL');
        $fullURL = currentURL();
        $adminURL = ($baseURL . DIRECTORY_SEPARATOR . ADMIN_PATH);
        $charset = config('app.locale');
        $date = date('Y-m-d');
        $datetime = date('H:i:s');

        $ipAddress = $request->ip();
        $referer = $request->headers->get('referer');
        $userAgent = $request->headers->get('user-agent');
        $deviceType = $this->deviceType();
        $device = $this->device();
        $platform = $this->platform();
        $browser = $this->browser();

        defined('BASE_URL') OR define('BASE_URL', $baseURL);
        defined('FULL_URL') OR define('FULL_URL', $fullURL);
        defined('ADMIN_URL') OR define('ADMIN_URL', $adminURL);
        defined('CHARSET') OR define('CHARSET', $charset);
        defined('DATE') OR define('DATE', $date);
        defined('DATETIME') OR define('DATETIME', $datetime);
        defined('IP_ADDRESS') OR define('IP_ADDRESS', $ipAddress);
        defined('REFERER') OR define('REFERER', $referer);
        defined('USER_AGENT') OR define('USER_AGENT', $userAgent);
        defined('DEVICE') OR define('DEVICE', $device);
        defined('DEVICE_TYPE') OR define('DEVICE_TYPE', $deviceType);
        defined('PLATFORM') OR define('PLATFORM', $platform);
        defined('BROWSER') OR define('BROWSER', $browser);
        defined('UID') OR define('UID', 0);
        defined('IS_USER') OR define('IS_USER', 0);
        defined('IS_ADMIN') OR define('IS_ADMIN', 0);

        View::composer('*', function ($view) {
            if (Auth::check()) {
                $view->with([
                    'user' => Auth::user()
                ]);
            }
        });

        // blade template 에서 admin 조건문 사용 가능
        Blade::if('admin', function () {
            return Auth::check() && Auth::user()->is_admin == 1;
        });

        /*
        DB::listen(function ($query) use ($request) {
            if (str_contains($query->sql, 'tb_general_log') || str_contains($query->sql, 'users')) {
                unset($query); return;
            }

            (new GeneralLog)->register($query, $request);
        });
        */
    }
}
