<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Request;
use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        // Trust Cloudflare proxies
        Request::setTrustedProxies(
            ['*'],
            \Illuminate\Http\Request::HEADER_X_FORWARDED_FOR |
            \Illuminate\Http\Request::HEADER_X_FORWARDED_HOST |
            \Illuminate\Http\Request::HEADER_X_FORWARDED_PORT |
            \Illuminate\Http\Request::HEADER_X_FORWARDED_PROTO |
            \Illuminate\Http\Request::HEADER_X_FORWARDED_AWS_ELB
        );
        
        // Force HTTPS
        URL::forceScheme('https');

        // Universal pagination view — used everywhere by default
        Paginator::defaultView('partials.pagination');
        Paginator::defaultSimpleView('partials.pagination');

        // Merge NAS credentials stored in the DB into the package config at runtime.
        // This way the live browser and all NAS operations use DB values without needing .env.
        $this->app->booted(function () {
            try {
                $host = \App\Models\Setting::get('nas_host', '');
                if ($host) {
                    config([
                        'nas-file-manager.connection.protocol'   => \App\Models\Setting::get('nas_protocol',   'smb'),
                        'nas-file-manager.connection.host'       => $host,
                        'nas-file-manager.connection.port'       => (int) \App\Models\Setting::get('nas_port', 445),
                        'nas-file-manager.connection.username'   => \App\Models\Setting::get('nas_username',   ''),
                        'nas-file-manager.connection.password'   => \App\Models\Setting::get('nas_password',   ''),
                        'nas-file-manager.connection.path'       => \App\Models\Setting::get('nas_path',       '/media'),
                        'nas-file-manager.connection.smb_share'  => \App\Models\Setting::get('nas_smb_share',  ''),
                        'nas-file-manager.connection.smb_domain' => \App\Models\Setting::get('nas_smb_domain', ''),
                    ]);
                }
            } catch (\Throwable $e) {
                // DB may not exist yet (fresh install / migrations not run) — silently skip
            }
        });
    }
}
