<?php

namespace App\Providers;

use App\Services\MobileConfig\MobileConfigService;
use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;

class SystemConfigServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        $this->app->singleton(SystemConfigService::class);
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // 1. Ensure settings helper is loaded
        $helper = app_path('Helpers/SettingsHelper.php');
        if (file_exists($helper)) {
            require_once $helper;
        }

        /** @var SystemConfigService $systemConfig */
        $systemConfig = $this->app->make(SystemConfigService::class);

        // 2. Localization
        $locale = $systemConfig->get('default_locale', 'en');
        app()->setLocale($locale);

        // Sync app.name globally so mail sender name, document title etc. use DB value
        config(['app.name' => $systemConfig->get('app_name', config('app.name'))]);

        // 3. Performance: Only run config overrides if not in console (optional, but speeds up Artisan)
        // or prioritize based on current context

        // Apply timezone globally from settings
        $timezone = $systemConfig->get('regional_timezone', 'Asia/Jakarta');
        config(['app.timezone' => $timezone]);
        date_default_timezone_set($timezone);

        // HTTPS Enforcement
        if ($systemConfig->get('force_https', false)) {
            URL::forceScheme('https');
        }

        // CORS Dynamic Configuration
        config([
            'cors.allowed_origins' => array_filter(array_map('trim', explode(',', $systemConfig->get('cors_origins', '*')))),
            'cors.allowed_methods' => array_filter(array_map('trim', explode(',', $systemConfig->get('cors_methods', '*')))),
            'cors.allowed_headers' => array_filter(array_map('trim', explode(',', $systemConfig->get('cors_headers', '*')))),
        ]);

        // Apply Captcha Config
        config([
            'captcha.sitekey' => $systemConfig->get('captcha_site_key'),
            'captcha.secret' => $systemConfig->get('captcha_secret_key'),
            'captcha.options' => [
                'timeout' => 30,
            ],
        ]);

        // Unified Social Login Callback Base
        $callbackUrl = $systemConfig->get('social_login_callback_url', '/auth/callback');

        // Apply Socialite Config
        config([
            'services.google' => [
                'client_id' => $systemConfig->get('google_client_id'),
                'client_secret' => $systemConfig->get('google_client_secret'),
                'redirect' => url($callbackUrl),
            ],
            'services.facebook' => [
                'client_id' => $systemConfig->get('facebook_app_id'),
                'client_secret' => $systemConfig->get('facebook_app_secret'),
                'redirect' => url($callbackUrl),
            ],
            'services.github' => [
                'client_id' => $systemConfig->get('github_client_id'),
                'client_secret' => $systemConfig->get('github_client_secret'),
                'redirect' => url($callbackUrl),
            ],
        ]);

        // Apply Session Configuration
        config([
            'session.driver' => $systemConfig->get('session_driver', 'file'),
            'session.lifetime' => $systemConfig->get('session_lifetime', 120),
            'session.secure' => $systemConfig->get('session_secure_cookie', false),
            'session.encrypt' => $systemConfig->get('session_encrypt', false),
            'session.remember' => $systemConfig->get('session_remember_me_duration', 30) * 1440, // Days to Minutes
        ]);

        config(['auth.passwords.users.expire' => $systemConfig->get('password_reset_link_expiry', 60)]);

        // 7. DYNAMIC MAIL CONFIGURATION
        if ($systemConfig->get('mail_host')) {
            config([
                'mail.default' => $systemConfig->get('mail_driver', 'smtp'),
                'mail.mailers.smtp.host' => $systemConfig->get('mail_host'),
                'mail.mailers.smtp.port' => $systemConfig->get('mail_port', 587),
                'mail.mailers.smtp.encryption' => $systemConfig->get('mail_encryption', 'tls'),
                'mail.mailers.smtp.username' => $systemConfig->get('mail_username'),
                'mail.mailers.smtp.password' => $systemConfig->get('mail_password'),
                'mail.from.address' => $systemConfig->get('mail_from_address', 'noreply@example.com'),
                'mail.from.name' => $systemConfig->get('mail_from_name', config('app.name')),
            ]);

            // If using smtp transport specifically
        }

        // 8. DYNAMIC BACKUP CONFIGURATION (Spatie Backup)
        if ($systemConfig->get('backup_db_enabled')) {
            $driver = $systemConfig->get('backup_db_driver', 'local');
            config([
                'backup.backup.destination.disks' => [$driver],
                'backup.monitor_backups.0.disks' => [$driver],
                'backup.cleanup.default_strategy.keep_all_backups_for_days' => (int) $systemConfig->get('backup_db_retention', 7),
            ]);

            // Encryption
            if ($systemConfig->get('backup_db_encrypt') && $systemConfig->get('backup_db_encrypt_key')) {
                config([
                    'backup.backup.password' => $systemConfig->get('backup_db_encrypt_key'),
                    'backup.backup.encryption' => 'aes256',
                ]);
            } else {
                config([
                    'backup.backup.password' => null,
                    'backup.backup.encryption' => 'none',
                ]);
            }

            // Exclude Tables (Injected via database config dump key)
            if ($excludeTables = $systemConfig->get('backup_db_exclude')) {
                $tables = array_map('trim', explode(',', $excludeTables));
                $dbDriver = config('database.default');
                config(["database.connections.{$dbDriver}.dump.exclude_tables" => $tables]);
            }

            // Notifications
            $notifyTo = $systemConfig->get('backup_db_notify_to');
            if ($notifyTo) {
                if (filter_var($notifyTo, FILTER_VALIDATE_EMAIL)) {
                    config(['backup.notifications.mail.to' => $notifyTo]);
                } elseif (str_starts_with($notifyTo, 'http')) {
                    config(['backup.notifications.notifications.webhook.url' => $notifyTo]);
                }
            }
        }

        // 9. DYNAMIC MOBILE AUTH CONFIGURATION
        $mobileConfig = $this->app->make(MobileConfigService::class);
        $allMobile = $mobileConfig->all();
        if ($ttl = ($allMobile['security_auth']['token_ttl_minutes'] ?? null)) {
            config(['sanctum.expiration' => (int) $ttl]);
        }

        // 3. View Sharing (Cached for request duration)
        view()->share($systemConfig->getPublicSettings());

        // 4. Pulse Access Gate
        Gate::define('viewPulse', function ($user) {
            return $user->can('view pulse');
        });
    }
}
