<?php

namespace App\Providers\Filament;

use AchyutN\FilamentLogViewer\FilamentLogViewer;
use App\Filament\Pages\Auth\EmailVerification;
use App\Filament\Pages\Auth\Login;
use App\Filament\Pages\Auth\Registration;
use App\Filament\Pages\Dashboard;
use App\Settings\GeneralSettings;
use BezhanSalleh\FilamentShield\FilamentShieldPlugin;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Support\Enums\Width;
use Filament\Widgets\AccountWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use Swindon\FilamentHashids\Middleware\FilamentHashidsMiddleware;
use Swis\Filament\Backgrounds\FilamentBackgroundsPlugin;
use Swis\Filament\Backgrounds\ImageProviders\MyImages;

class DashboardPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        $directoryAuthBg = 'auth-bg';
        $fullPath = storage_path("app/public/{$directoryAuthBg}");

        if (! is_dir($fullPath)) {
            mkdir($fullPath, 0777, true);
        }

        $files = glob($fullPath.'/*');
        if (! $files || count($files) === 0) {
            $defaultImage = public_path('assets/img/bg/default.jpg');
            $targetImage = $fullPath.'/default.png';
            copy($defaultImage, $targetImage);
        }

        $generalSettings = app(GeneralSettings::class);

        return $panel
            ->default()
            ->id('dashboard')
            ->path('dashboard')
            ->brandLogo(fn () => Storage::url($generalSettings->site_logo))
            ->favicon(fn () => Storage::url($generalSettings->site_icon))
            ->login(Login::class)
            ->registration(Registration::class)
            ->emailVerification(EmailVerification::class)
            ->colors([
                'primary' => Color::Blue,
                'slate' => Color::Slate,
            ])
            ->breadcrumbs(false)
            ->maxContentWidth(Width::Full)
            ->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources')
            ->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
            ->pages([
                Dashboard::class,
            ])
            ->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\Filament\Widgets')
            ->widgets([
                AccountWidget::class,
            ])
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                VerifyCsrfToken::class,
                SubstituteBindings::class,
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
                FilamentHashidsMiddleware::class,
            ])
            ->plugins([
                FilamentShieldPlugin::make()
                    ->navigationSort(999)
                    ->globallySearchable(false),

                FilamentBackgroundsPlugin::make()
                    ->imageProvider(
                        MyImages::make()
                            ->directory('storage/'.$directoryAuthBg)
                    ),

                FilamentLogViewer::make()
                    ->navigationGroup('Sistem')
                    ->navigationIcon('heroicon-o-server-stack')
                    ->navigationLabel('Log')
                    ->navigationUrl('/system/logs')
                    ->pollingTime(null)
                    ->authorize(fn (): bool => auth()->user()->can('View:LogTable')),
            ])
            ->authMiddleware([
                Authenticate::class,
            ])
            ->databaseTransactions()
            ->viteTheme('resources/css/filament/dashboard/theme.css')
            ->navigationGroups([
                'Master',
                'Kelola',
                'Monitoring',
                'Publikasi',
                'Pengaturan',
                'Pelindung',
                'Sistem',
            ])
            ->databaseNotifications()
            ->databaseNotificationsPolling('30s')
            ->brandLogo(fn () => Storage::url($generalSettings?->site_logo))
            ->favicon(fn () => Storage::url($generalSettings?->site_icon))
            ->globalSearch(false);
    }
}
