<?php

namespace App\Providers;

use App\Models\Section;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $minutes = 60 * 60; // 1 hour
        $sections = Cache::remember('sections', $minutes, function () {
            try {
                // Check if sections table exists before querying
                if (Schema::hasTable('sections')) {
                    return Section::all();
                }
                return collect([]);
            } catch (\Exception $e) {
                // If database or table doesn't exist yet, return empty collection
                return collect([]);
            }
        });

        $scopes = [];
        foreach ($sections as $section) {
            $scopes[$section->name] = $section->caption;
            Gate::define($section->name, function ($user) use ($section) {
                return $user->hasPermission($section->name);
            });
        }

        $this->registerPolicies();

        //
    }
}
