<?php

use App\Http\Controllers\AccountController;
use App\Http\Controllers\AiModuleController;
use App\Http\Controllers\AiSettingController;
use App\Http\Controllers\AnalyticsController;
use App\Http\Controllers\Auth\AuthorizationController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\SocialAuthController;
use App\Http\Controllers\CalendarController;
use App\Http\Controllers\CampaignController;
use App\Http\Controllers\Core\CoreController;
use App\Http\Controllers\Core\LanguageController;
use App\Http\Controllers\CronController;
use App\Http\Controllers\GalleryController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\MaintenanceController;
use App\Http\Controllers\PlatformController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\SocialTemplateController;
use App\Http\Controllers\StuffController;
use App\Http\Controllers\TwoFactorController;
use App\Http\Controllers\WorkspaceController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

$globalMiddleware = [

    'sanitizer',
    'https',
    "dos.security",
    'maintenance.mode',

];

try {
    DB::connection()->getPdo();
    if (DB::connection()->getDatabaseName())
        array_push($globalMiddleware, values: "throttle:refresh");
} catch (\Throwable $th) {
    //throw $th;
}


Route::get('/', function () {
    // If not installed, middleware will redirect to /install
    return redirect()->route('auth.login');
});

// Maintenance route - needs to be accessible even in maintenance mode
Route::get('/maintenance', [MaintenanceController::class, 'index'])
    ->name('maintenance')
    ->middleware(['auth:web']);

Route::middleware($globalMiddleware)->group(function () {

    #GUEST-ROUTE
    Route::middleware(['guest:web'])->name('auth.')
        ->group(function () {

            #LOGIN_ROUTE
            Route::controller(LoginController::class)
                ->group(function () {

                Route::get('/login', 'login')->name('login');
                Route::post('/login', 'authenticate')->name('authenticate');

            });



            #OTP_AUTHORIZATION_ROUTE
            Route::controller(AuthorizationController::class)
                ->group(function () {

                Route::get('/otp-verification', 'otpVerification')->name('otp.verification');
                Route::get('/email-verification', 'otpVerification')->name('email.verification')->withoutMiddleware(['guest:web']);
                Route::post('/otp-verify', 'otpVerify')->name('otp.verify')->withoutMiddleware('guest:web');
                Route::get('/otp-resend', 'otpResend')->name('otp.resend')->withoutMiddleware('guest:web');
            });

            #FORGOT_PASSWORD_ROUTE
            Route::controller(NewPasswordController::class)
                ->name('password.')
                ->group(function () {

                Route::get('forgot-password', 'create')->name('request');
                Route::post('password/email', 'store')->name('email');
                Route::get('password/verify', 'verify')->name('verify');
                Route::post('password/verify/code', 'verifyCode')->name('verify.code');
                Route::get('password/reset', 'resetPassword')->name('reset');
                Route::post('password/update', 'updatePassword')->name('update');
                Route::get('password/update/success', 'updatePasswordSuccess')->name('update.success');

            });


            #SOCIAL_LOGIN_CONTROLLER
            Route::controller(SocialAuthController::class)
                ->name('social.')
                ->group(function () {

                Route::get('login/{medium}', 'redirectToOauth')->name('login');
                Route::get('login/{medium}/callback', 'handleOauthCallback')->name('login.callback');
            });


        });


    Route::middleware(['auth:web'])
        ->prefix('user')
        ->name('user.')
        ->group(function () {

            #logout route
            Route::controller(LoginController::class)
                ->group(function () {
                Route::get('/logout', 'logout')->name('logout');
            });

            #home & profile route
            Route::controller(HomeController::class)
                ->group(function () {

                Route::get('dashboard', 'home')->name('home');
                Route::get('profile/settings', 'profileSettings')->name('profile.settings');
                Route::get('demo', 'generalSettings')->name('demo');
                Route::post('profile/avatar/update', 'profileAvatarUpdate')->name('profile.avatar.update');
                Route::post('profile/update', 'profileUpdate')->name('profile.update');
                Route::post('profile/delete', 'profileDelete')->name('profile.delete');
                Route::post('password/update', 'passwordUpdate')->name('password.update');


                Route::post('/read-notification', 'readNotification')->name('read.notification');
            });

            Route::controller(WorkspaceController::class)
                ->prefix('workspace')
                ->name('workspace.')
                ->group(function () {
                    Route::get('settings', 'settings')->name('settings');
                    Route::post('store', 'store')->name('store');
                    Route::post('switch', 'switch')->name('switch');
                    Route::post('delete', 'delete')->name('delete');
                    Route::post('status/update', 'statusUpdate')->name('status.update');
                    Route::post('bulk/action', 'bulk')->name('bulk');

                });

            Route::controller(SettingController::class)
                ->prefix('setting')
                ->name('setting.')
                ->group(function () {
                    Route::get('/', 'index')->name('index');
                    Route::post('/store', 'store')->name('store');
                    Route::post('/store/logo', 'logoSetting')->name('store.logo');
                    Route::post('/test-email', 'testEmail')->name('test-email');
                    Route::get('/data/export', 'dataExport')->name('data.export');
                    Route::post('/backup/create', 'createBackup')->name('backup.create');
                    Route::post('/backup/restore', 'restoreBackup')->name('backup.restore');
                    Route::post('/backup/delete', 'deleteBackup')->name('backup.delete');
                    Route::post('/maintenance/run', 'runMaintenance')->name('maintenance.run');



                });

            Route::controller(StuffController::class)
                ->prefix('access-control')
                ->name('access-control.')
                ->group(function () {
                    Route::get('/', 'index')->name('index');
                    Route::post('/store', 'store')->name('store');
                    Route::post('/update', 'update')->name('update');
                    Route::post('/status/update', 'statusUpdate')->name('status.update');
                    Route::post('delete', 'delete')->name('delete');
                    Route::post('bulk/action', 'bulk')->name('bulk');
                    Route::post('/login', 'login')->name('login');

                });

            Route::controller(RoleController::class)
                ->prefix('role')
                ->name('role.')
                ->group(function () {
                    Route::post('/store', 'store')->name('store');
                    Route::get('/edit/{id}', 'edit')->name('edit');
                    Route::post('/update', 'update')->name('update');

                    Route::post('/status/update', 'statusUpdate')->name('status.update');
                    Route::post('delete', 'delete')->name('delete');
                    Route::post('bulk/action', 'bulk')->name('bulk');
                });

            Route::controller(AiSettingController::class)
                ->prefix('aisetting')
                ->name('ai_setting.')
                ->group(function () {
                    Route::post('/store', 'AiConfigStore')->name('store');
                });

            Route::controller(LanguageController::class)
                ->prefix('language')
                ->name('language.')
                ->group(function () {
                    Route::post('/store', 'store')->name('store');
                    Route::post('/status/update', 'statusUpdate')->name('status.update');
                    Route::post('delete', 'delete')->name('delete');
                    Route::post('bulk/action', 'bulk')->name('bulk');
                    Route::post('make/default', 'makeDefault')->name('make.default');
                    Route::get('translation', 'translation')->name('translation');
                    Route::post('translations/add', 'translationAdd')->name('translation.add');
                    Route::post('auto-translate', 'autoTranslate')->name('auto-translate');
                    Route::post('switch', 'switch')->name('switch');



                });

            Route::controller(PlatformController::class)
                ->prefix('platform')
                ->name('platform.')
                ->group(function () {
                    Route::get('/index', 'index')->name('index');
                    Route::get('/setting/{id}', 'setting')->name('setting');
                    Route::get('/accounts/{id}', 'accounts')->name('accounts');
                    Route::post('/setting/store', 'settingStore')->name('setting.store');
                    Route::post('/account/create', 'createAccount')->name('account.create');

                    Route::controller(AccountController::class)
                        ->prefix('account')
                        ->name('account.')
                        ->group(function () {
                            Route::get('/', 'index')->name('index');
                            Route::post('delete', 'delete')->name('delete');
                            Route::post('bulk/action', 'bulk')->name('bulk');
                            Route::post('/status/update', 'statusUpdate')->name('status.update');
                            Route::post('create', 'create')->name('create');


                        });

                });

            #SOCIAL_MEDIA_POST
            Route::controller(PostController::class)
                ->prefix('post')
                ->name('post.')
                ->group(function () {

                Route::get('/create', 'create')->name('create');
                Route::post('/store', 'store')->name('store');
                Route::post('/reschedule', 'reschedule')->name('reschedule');
                Route::post('/send', 'send')->name('send');
                Route::get('/preview/{id}', 'preview')->name('preview');
                Route::get('/edit/{id}', 'edit')->name('edit');
                Route::post('/update', 'update')->name('update');


            });

            #ALL_POSTS
            Route::controller(PostController::class)
                ->prefix('posts')
                ->name('posts.')
                ->group(function () {
                Route::get('/index', 'allPosts')->name('index');
            });

            #GALLERY
            Route::controller(GalleryController::class)
                ->prefix('gallery')
                ->name('gallery.')
                ->group(function () {

                Route::get('/index', 'index')->name('index');
                Route::post('/store', 'store')->name('store');

                Route::post('/delete', 'delete')->name('item.delete');
                Route::post('/download/{file}', 'download')->name('download');
                Route::post('/quick-upload', 'quickUpload')->name('quick-upload');
            });

            #TEMPLATE
            Route::controller(SocialTemplateController::class)
                ->prefix('template')
                ->name('template.')
                ->group(function () {
                Route::get('/index', 'index')->name('index');
                Route::post('/store', 'store')->name('store');
                Route::get('/edit/{id}', 'edit')->name('edit');
                Route::post('/update', 'update')->name('update');
                Route::post('/delete', 'delete')->name('delete');




                Route::controller(AiModuleController::class)
                    ->prefix('ai')
                    ->name('ai.')
                    ->group(function () {
                        Route::post('/store', 'storeTemplate')->name('store');
                        Route::post('/update', 'updateTemplate')->name('update');
                        Route::post('/delete', 'deleteTemplate')->name('delete');


                    });

            });

            #CAMPAIGN
            Route::controller(CampaignController::class)
                ->prefix('campaign')
                ->name('campaign.')
                ->group(function () {
                Route::get('/index', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::get('/edit/{id}', 'edit')->name('edit');
                Route::post('/store', 'store')->name('store');
                Route::post('/update', 'update')->name('update');
                Route::post('delete', 'delete')->name('delete');
                Route::post('bulk/action', 'bulk')->name('bulk');
                Route::get('analytics', 'analytics')->name('analytics');


            });

            #ANALYTICS
            Route::controller(AnalyticsController::class)
                ->prefix('analytics')
                ->name('analytics.')
                ->group(function () {
                Route::get('/index', 'index')->name('index');
            });

            #CALENDER
            Route::controller(CalendarController::class)
                ->prefix('calender')
                ->name('calender.')
                ->group(function () {
                Route::get('/index', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::get('/store', 'store')->name('store');

            });

            #AiMODULE
            Route::controller(AiModuleController::class)
                ->prefix('ai')
                ->name('ai.')
                ->group(function () {
                Route::post('/generate', 'generate')->name('generate');


            });

            //#2FA ROUTES
            Route::controller(TwoFactorController::class)
                ->name('2fa.')
                ->prefix('2fa/')
                ->group(function () {

                Route::get('/', 'index')->name('index');
                Route::post('verify', 'verify')->name('verify');
                Route::post('disable', 'disable')->name('disable');
                Route::post('recovery-code/regenerate', 'regenerateRecoveryCodes')->name('regenerate.code');

            });

            // #CRON JOB ROUTES
            Route::controller(CronController::class)
                ->prefix('cron')
                ->name('cron.')
                ->group(function () {
                    Route::get('status', 'status')->name('status');
                    Route::post('toggle', 'toggle')->name('toggle');
                    Route::post('run-now', 'runNow')->name('run-now');
                    Route::get('logs/{job_id}', 'logs')->name('logs');
                    Route::get('health', 'health')->name('health');

                    // URL-based cron execution routes for shared hosting
                    Route::get('posts-schedule', 'executePostsSchedule')->name('posts-schedule');
                    Route::get('analytics-sync', 'executeAnalyticsSync')->name('analytics-sync');
                    Route::get('accounts-refresh-tokens', 'executeAccountsRefreshTokens')->name('accounts-refresh-tokens');
                    Route::get('system-cleanup', 'executeSystemCleanup')->name('system-cleanup');
                    Route::get('backup-run', 'executeBackupRun')->name('backup-run');
                });

            #CORE CONTROLER
            Route::controller(CoreController::class)
                ->withoutMiddleware(['throttle:refresh', 'dos.security'])
                ->group(function () {

                Route::get('/cron/run', 'cron')->name('cron.run');
                Route::get('/language/change/{code?}', 'languageChange')->name('language.change');
                Route::get('/optimize-clear', "clear")->name('optimize.clear');


                Route::get('process-images', 'processImages')->name('process.images');
                Route::post('process-videos', 'processVideos')->name('process.videos');

                /** social account connect - requires auth */
                Route::get('/account-connect/{medium}/{type?}', 'redirectAccount')->name('account.connect');

            });


        });

    /** Social OAuth Callback Routes - Outside user group for cleaner callback URLs */
    Route::controller(CoreController::class)
        ->middleware(['auth:web'])
        ->withoutMiddleware(['throttle:refresh', 'dos.security'])
        ->group(function () {
            Route::get('account/{medium}/callback', 'handleAccountCallback')->name('account.callback');
        });


});

// Public cron job routes for shared hosting (no authentication required)
Route::controller(CronController::class)
    ->prefix('cron')
    ->middleware(['throttle:60,1']) // Rate limit to prevent abuse
    ->group(function () {
        // URL-based cron execution routes for shared hosting
        Route::get('posts-schedule', 'executePostsSchedule')->name('public.cron.posts-schedule');
        Route::get('analytics-sync', 'executeAnalyticsSync')->name('public.cron.analytics-sync');
        Route::get('accounts-refresh-tokens', 'executeAccountsRefreshTokens')->name('public.cron.accounts-refresh-tokens');
        Route::get('system-cleanup', 'executeSystemCleanup')->name('public.cron.system-cleanup');
        Route::get('backup-run', 'executeBackupRun')->name('public.cron.backup-run');
    });

