<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use GuzzleHttp\Client;
use App\Models\Setting;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Schema\Builder;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Auth;
use App\Models\AllTransactions;

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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Builder::defaultStringLength(255);

        if (file_exists(storage_path('installed'))) {
            config(['websockets.dashboard.port' => setting('liveChatPort')]);
            config(['broadcasting.connections.pusher.options.port' => setting('liveChatPort')]);
            config(['websockets.dashboard.port' => Setting::where('key', 'livechatport')->value('value')]);
            config(['broadcasting.connections.pusher.options.port' => Setting::where('key', 'livechatport')->value('value')]);
            config(['broadcasting.connections.pusher.options.host' => parse_url(url('/'))["host"]]);
        }

        View::share('clientpath', 'client/');

        // if(!File::exists(__DIR__ . '/../../vendor/laravel-lara/infoinst/src/Providers/InstallationServiceProvider.php')){exit();}
        Validator::extend('recaptcha', function ($attribute, $value, $parameters, $validator) {

            if (setting('RECAPTCH_TYPE') != 'GOOGLE')
                return true;

            $client = new Client();

            $response = $client->post(
                'https://www.google.com/recaptcha/api/siteverify',
                [
                    'form_params' =>
                    [
                        'secret' => setting('GOOGLE_RECAPTCHA_SECRET'),
                        'response' => $value
                    ]
                ]
            );

            $body = json_decode((string)$response->getBody());

            return $body->success;
        });

        Validator::extend('no_script_tags', function ($attribute, $value, $parameters, $validator) {
            $pattern = '/<\s*script(?:\s+[\w\-\d]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|[^>\s]+))?)*\s*>(.*?)<\s*\/script\s*>/is';
            return !preg_match($pattern, $value);
        });
        View::composer('*', function ($view) {
            // Check if the user is authenticated
            if (Auth::guard('customer')->check()) {
                $userId = Auth::guard('customer')->user()->id;
                $hasquotations = AllTransactions::where('cust_id', $userId)->exists();
            } else {
                $hasquotations = false; // or any default value you prefer
            }

            // Share the variable with the view
            $view->with('hasquotations', $hasquotations);
        });
    }
}
