<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Route;

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

    public function boot(): void
    {
        // 強制 HTTPS 檢測邏輯 (包含 Cloudflare/Load Balancer 支援)
        $isHttps = $this->app->environment('production') 
            || str_contains(config('app.url'), 'https')
            || request()->header('x-forwarded-proto') === 'https'
            || request()->server('HTTPS') === 'on';

        if ($isHttps) {
            URL::forceScheme('https');
            
            // 強制讓 Request 物件認為自己是安全連線 (解決 Paginator 或 Request::secure() 判斷問題)
            request()->server->set('HTTPS', 'on');
        }

        // 隱含授權：讓 "super-admin" 角色擁有所有權限
        \Illuminate\Support\Facades\Gate::before(function ($user, $ability) {
            return $user->hasRole('super-admin') ? true : null;
        });

        // 載入房東後台路由 (只在 central domain 可用)
        $this->app->booted(function () {
            if (file_exists(base_path('routes/landlord.php'))) {
                Route::middleware('web')->group(base_path('routes/landlord.php'));
            }
        });
    }
}

