<?php

namespace App\Providers;

use App\Models\AuditLog;
use App\Models\BookingNote;
use App\Models\Campaign;
use App\Models\Creator;
use App\Models\SopStep;
use App\Models\Task;
use App\Models\User;
use App\Models\Video;
use App\Policies\AuditLogPolicy;
use App\Policies\BookingNotePolicy;
use App\Policies\CampaignPolicy;
use App\Policies\CreatorPolicy;
use App\Policies\TaskPolicy;
use App\Policies\UserPolicy;
use App\Policies\VideoPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;

class RouteServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Đăng ký các policies
        Gate::policy(AuditLog::class, AuditLogPolicy::class);
        Gate::policy(User::class, UserPolicy::class);
        Gate::policy(Creator::class, CreatorPolicy::class);
        Gate::policy(Campaign::class, CampaignPolicy::class);
        Gate::policy(Video::class, VideoPolicy::class);
        Gate::policy(BookingNote::class, BookingNotePolicy::class);
        Gate::policy(Task::class, TaskPolicy::class);
        Gate::policy(SopStep::class, \App\Policies\SopStepPolicy::class);

        // Đăng ký gate cho Export — kiểm tra quyền xuất file dữ liệu
        Gate::define('exportData', function ($user) {
            $policy = new \App\Policies\ExportPolicy();
            return $policy->exportData($user);
        });

        // Đăng ký gate cho Export PDF — tất cả role đều được
        Gate::define('exportPdf', function ($user) {
            $policy = new \App\Policies\ExportPolicy();
            return $policy->exportPdf($user);
        });

        // Đăng ký gate cho Analysis — kiểm tra quyền truy cập trang phân tích số liệu
        Gate::define('analysisViewAny', function ($user, $organization = null) {
            $policy = new \App\Policies\AnalysisPolicy();
            return $policy->viewAny($user, $organization);
        });

        Gate::define('analysisUpload', function ($user, $organization = null) {
            $policy = new \App\Policies\AnalysisPolicy();
            return $policy->upload($user, $organization);
        });

        $this->routes(function () {
            // Load web routes inside the 'web' middleware group so session, CSRF, etc. work
            \Illuminate\Support\Facades\Route::middleware('web')
                ->group(base_path('routes/web.php'));

            // Load API routes with the 'api' middleware
            \Illuminate\Support\Facades\Route::prefix('')
                ->middleware('api')
                ->group(base_path('routes/api.php'));

            // Ensure auth routes are loaded under 'web' as well
            if (file_exists(base_path('routes/auth.php'))) {
                \Illuminate\Support\Facades\Route::middleware('web')
                    ->group(base_path('routes/auth.php'));
            }
        });
    }
}
