<?php

use App\Http\Controllers\Admin\Auth\AuthenticatedSessionController as AdminAuthenticatedSessionController;
use App\Http\Controllers\Admin\CashbackController;
use App\Http\Controllers\Admin\AirtimeToCashController as AdminAirtimeToCashController;
use App\Http\Controllers\Admin\BrandingSettingController;
use App\Http\Controllers\Admin\ContactSettingController;
use App\Http\Controllers\Admin\CommerceSettingController;
use App\Http\Controllers\Admin\CouponController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\IntegrationSettingController;
use App\Http\Controllers\Admin\MappingController;
use App\Http\Controllers\Admin\StaffManagementController;
use App\Http\Controllers\Admin\NotificationController as AdminNotificationController;
use App\Http\Controllers\Admin\PlanController;
use App\Http\Controllers\Admin\ReferralController;
use App\Http\Controllers\Admin\ReportController;
use App\Http\Controllers\Admin\ReservedAccountController;
use App\Http\Controllers\Admin\ServiceControlController;
use App\Http\Controllers\Admin\TicketController as AdminTicketController;
use App\Http\Controllers\Admin\TransactionController as AdminTransactionController;
use App\Http\Controllers\Admin\UserManagementController;
use App\Http\Controllers\Admin\VendorController;
use App\Http\Controllers\Admin\VendorPlanCatalogController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\Shop\DashboardController as ShopDashboardController;
use App\Http\Controllers\Shop\PurchaseController;
use App\Http\Controllers\Shop\NotificationController as ShopNotificationController;
use App\Http\Controllers\Shop\ReferralController as ShopReferralController;
use App\Http\Controllers\Shop\ApiAccessController;
use App\Http\Controllers\Shop\SupportTicketController;
use App\Http\Controllers\Shop\TransactionHistoryController;
use App\Http\Controllers\Shop\WalletController;
use App\Http\Controllers\Shop\WalletFundingController;
use App\Http\Controllers\Shop\AirtimeToCashController as ShopAirtimeToCashController;
use App\Http\Controllers\Shop\AboutController as ShopAboutController;
use App\Http\Controllers\Shop\ContactController as ShopContactController;
use App\Http\Controllers\Shop\LegalAcknowledgeController;
use App\Http\Controllers\Admin\LegalSettingController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    if (auth()->check()) {
        return redirect()->route('app.dashboard');
    }

    return redirect()->route('login');
});

Route::get('/dashboard', function () {
    return redirect()->route('app.dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::patch('/profile/transaction-pin', [ProfileController::class, 'updateTransactionPin'])->name('profile.transaction-pin.update');
    Route::patch('/profile/notification-preferences', [ProfileController::class, 'updateNotificationPreferences'])->name('profile.notification-preferences.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

Route::prefix('admin')->name('admin.')->middleware('guest')->group(function () {
    Route::get('/login', [AdminAuthenticatedSessionController::class, 'create'])->name('login');
    Route::post('/login', [AdminAuthenticatedSessionController::class, 'store'])->name('login.store');
});

Route::middleware(['auth', 'verified'])->prefix('app')->name('app.')->group(function () {
    Route::get('/dashboard', ShopDashboardController::class)->name('dashboard');
    Route::get('/wallet', [WalletController::class, 'index'])->name('wallet');
    Route::get('/wallet/beneficiary', [WalletController::class, 'lookupBeneficiary'])
        ->middleware('throttle:wallet-beneficiary-lookup')
        ->name('wallet.beneficiary.lookup');
    Route::post('/wallet/transfer', [WalletController::class, 'transfer'])
        ->middleware('throttle:wallet-transfers')
        ->name('wallet.transfer');
    Route::post('/wallet/funding/paystack', [WalletFundingController::class, 'initializePaystack'])
        ->middleware('throttle:wallet-funding-init')
        ->name('wallet.funding.paystack');
    Route::post('/wallet/funding/monnify-instant', [WalletFundingController::class, 'initializeMonnifyInstant'])
        ->middleware('throttle:wallet-funding-init')
        ->name('wallet.funding.monnify-instant');

    Route::prefix('buy')->name('buy.')->group(function () {
        Route::get('/data', [PurchaseController::class, 'data'])->name('data');
        Route::post('/data', [PurchaseController::class, 'purchaseData'])->middleware('throttle:purchases')->name('data.purchase');

        Route::get('/airtime', [PurchaseController::class, 'airtime'])->name('airtime');
        Route::post('/airtime', [PurchaseController::class, 'purchaseAirtime'])->middleware('throttle:purchases')->name('airtime.purchase');

        Route::get('/cable', [PurchaseController::class, 'cable'])->name('cable');
        Route::post('/cable', [PurchaseController::class, 'purchaseCable'])->middleware('throttle:purchases')->name('cable.purchase');

        Route::get('/electricity', [PurchaseController::class, 'electricity'])->name('electricity');
        Route::get('/electricity/validate-meter', [PurchaseController::class, 'validateElectricityMeter'])
            ->middleware('throttle:purchases')
            ->name('electricity.validate-meter');
        Route::post('/electricity', [PurchaseController::class, 'purchaseElectricity'])->middleware('throttle:purchases')->name('electricity.purchase');

        Route::get('/epin', [PurchaseController::class, 'epin'])->name('epin');
        Route::post('/epin', [PurchaseController::class, 'purchaseEpin'])->middleware('throttle:purchases')->name('epin.purchase');
    });

    Route::get('/transactions', [TransactionHistoryController::class, 'index'])->name('transactions.history');
    Route::get('/notifications', [ShopNotificationController::class, 'index'])->name('notifications.index');
    Route::post('/notifications/{notification}/read', [ShopNotificationController::class, 'read'])->name('notifications.read');
    Route::post('/notifications/{notification}/dismiss-popup', [ShopNotificationController::class, 'dismissPopup'])->name('notifications.dismiss-popup');
    Route::get('/referrals', ShopReferralController::class)->name('referrals.index');
    Route::get('/about', ShopAboutController::class)->name('about.index');
    Route::get('/contact', ShopContactController::class)->name('contact.index');
    Route::post('/legal/acknowledge', LegalAcknowledgeController::class)->name('legal.acknowledge');
    Route::get('/airtime-to-cash', [ShopAirtimeToCashController::class, 'index'])->name('airtime-to-cash.index');
    Route::get('/airtime-to-cash/banks', [ShopAirtimeToCashController::class, 'banks'])
        ->middleware('throttle:airtime-to-cash-banks')
        ->name('airtime-to-cash.banks');
    Route::get('/airtime-to-cash/resolve-account', [ShopAirtimeToCashController::class, 'resolveAccount'])
        ->middleware('throttle:airtime-to-cash-bank-resolve')
        ->name('airtime-to-cash.resolve-account');
    Route::post('/airtime-to-cash', [ShopAirtimeToCashController::class, 'store'])->name('airtime-to-cash.store');
    Route::post('/airtime-to-cash/{airtimeToCashRequest}/cancel', [ShopAirtimeToCashController::class, 'cancel'])->name('airtime-to-cash.cancel');
    Route::get('/api-access', [ApiAccessController::class, 'index'])->name('api-access.index');
    Route::post('/api-access/rotate', [ApiAccessController::class, 'rotate'])->name('api-access.rotate');
    Route::get('/support/tickets/create', [SupportTicketController::class, 'create'])->name('support.tickets.create');
    Route::post('/support/tickets', [SupportTicketController::class, 'store'])->name('support.tickets.store');
});

Route::middleware(['auth', 'verified', 'permission:access admin panel'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/', fn () => redirect()->route('admin.dashboard'))->name('home');
        Route::get('/dashboard', AdminDashboardController::class)->name('dashboard');
        Route::get('/dashboard/export-csv', [AdminDashboardController::class, 'exportCsv'])->name('dashboard.export-csv');
        Route::get('/dashboard/printable', [AdminDashboardController::class, 'printableReport'])->name('dashboard.printable');

        Route::resource('vendors', VendorController::class)
            ->middleware('permission:vendors.manage')
            ->except(['show', 'destroy']);
        Route::post('vendors/{vendor}/test-connection', [VendorController::class, 'testConnection'])
            ->middleware('can:testConnection,vendor')
            ->name('vendors.test-connection');
        Route::get('vendors/{vendor}/plan-catalog', VendorPlanCatalogController::class)
            ->middleware('permission:vendors.manage')
            ->name('vendors.plan-catalog');

        Route::resource('plans', PlanController::class)
            ->middleware('permission:plans.manage')
            ->except(['show', 'destroy']);
        Route::patch('plans/{plan}/status', [PlanController::class, 'toggleStatus'])
            ->middleware('can:update,plan')
            ->name('plans.toggle-status');

        Route::get('mappings', [MappingController::class, 'index'])->middleware('permission:mappings.manage')->name('mappings.index');
        Route::put('mappings/service-rules', [MappingController::class, 'updateServiceRules'])
            ->middleware('permission:mappings.manage')
            ->name('mappings.service-rules.update');
        Route::post('mappings/auto-fix', [MappingController::class, 'autoFix'])
            ->middleware('permission:mappings.manage')
            ->name('mappings.auto-fix');
        Route::post('mappings/import-plan-codes', [MappingController::class, 'importPlanCodes'])
            ->middleware('permission:mappings.manage')
            ->name('mappings.plan-codes.import');

        Route::get('service-controls', [ServiceControlController::class, 'index'])->name('service-controls.index');
        Route::put('service-controls/rule', [ServiceControlController::class, 'upsertRule'])->name('service-controls.rule.upsert');
        Route::put('service-controls/rules/bulk', [ServiceControlController::class, 'bulkUpsertRules'])->name('service-controls.rules.bulk-upsert');
        Route::get('coupons', [CouponController::class, 'index'])->name('coupons.index');
        Route::post('coupons', [CouponController::class, 'store'])->name('coupons.store');
        Route::put('coupons/{coupon}', [CouponController::class, 'update'])->name('coupons.update');
        Route::get('cashbacks', [CashbackController::class, 'index'])->name('cashbacks.index');
        Route::put('cashbacks/settings', [CashbackController::class, 'updateSettings'])->name('cashbacks.settings.update');
        Route::post('cashbacks', [CashbackController::class, 'store'])->name('cashbacks.store');
        Route::put('cashbacks/{cashback}', [CashbackController::class, 'update'])->name('cashbacks.update');
        Route::get('airtime-to-cash', [AdminAirtimeToCashController::class, 'index'])->name('airtime-to-cash.index');
        Route::get('airtime-to-cash/payout-queue', [AdminAirtimeToCashController::class, 'payoutQueue'])->name('airtime-to-cash.payout-queue');
        Route::post('airtime-to-cash/{airtimeToCashRequest}/decide', [AdminAirtimeToCashController::class, 'decide'])->name('airtime-to-cash.decide');
        Route::post('airtime-to-cash/{airtimeToCashRequest}/payout', [AdminAirtimeToCashController::class, 'updatePayout'])->name('airtime-to-cash.payout.update');

        Route::get('transactions', [AdminTransactionController::class, 'index'])
            ->middleware('permission:transactions.view')
            ->name('transactions.index');
        Route::post('transactions/{transaction}/manual-requery', [AdminTransactionController::class, 'manualRequery'])
            ->middleware('can:manualRequery,transaction')
            ->name('transactions.manual-requery');
        Route::post('transactions/{transaction}/refund', [AdminTransactionController::class, 'refund'])
            ->middleware('can:refund,transaction')
            ->name('transactions.refund');

        Route::get('reports', [ReportController::class, 'index'])
            ->middleware('permission:reports.view')
            ->name('reports.index');
        Route::get('reports/export-csv', [ReportController::class, 'exportCsv'])
            ->middleware('permission:reports.view')
            ->name('reports.export-csv');

        Route::get('users', [UserManagementController::class, 'index'])->name('users.index');
        Route::get('users/export-api-clients-csv', [UserManagementController::class, 'exportApiClientsCsv'])->name('users.export-api-clients-csv');
        Route::post('users', [UserManagementController::class, 'store'])->name('users.store');
        Route::put('users/{user}', [UserManagementController::class, 'update'])->name('users.update');
        Route::post('users/{user}/wallet-adjust', [UserManagementController::class, 'adjustWallet'])
            ->name('users.wallet-adjust');
        Route::put('users/{user}/api-client', [UserManagementController::class, 'updateApiClient'])
            ->name('users.api-client.update');
        Route::post('users/{user}/api-client/rotate', [UserManagementController::class, 'rotateApiClientSecret'])
            ->name('users.api-client.rotate');

        Route::middleware(['role:super-admin'])->group(function () {
            Route::get('staff', [StaffManagementController::class, 'index'])->name('staff.index');
            Route::post('staff', [StaffManagementController::class, 'store'])->name('staff.store');
            Route::put('staff/{user}', [StaffManagementController::class, 'update'])->name('staff.update');
        });
        Route::get('notifications', [AdminNotificationController::class, 'index'])->name('notifications.index');
        Route::post('notifications', [AdminNotificationController::class, 'store'])->name('notifications.store');
        Route::put('notifications/{notification}', [AdminNotificationController::class, 'update'])->name('notifications.update');

        Route::get('referrals', [ReferralController::class, 'index'])->name('referrals.index');
        Route::put('referrals/settings', [ReferralController::class, 'updateSettings'])->name('referrals.settings.update');
        Route::post('referrals/{referral}/reward', [ReferralController::class, 'reward'])->name('referrals.reward');
        Route::patch('referrals/{referral}/status', [ReferralController::class, 'updateStatus'])->name('referrals.status.update');

        Route::get('settings/integrations', [IntegrationSettingController::class, 'edit'])
            ->name('settings.integrations.edit');
        Route::put('settings/integrations', [IntegrationSettingController::class, 'update'])
            ->name('settings.integrations.update');
        Route::post('settings/integrations/test-report', [IntegrationSettingController::class, 'sendTestReport'])
            ->name('settings.integrations.test-report');
        Route::middleware('role:super-admin')->group(function () {
            Route::get('settings/branding', [BrandingSettingController::class, 'edit'])->name('settings.branding.edit');
            Route::post('settings/branding', [BrandingSettingController::class, 'update'])->name('settings.branding.update');
            Route::post('settings/branding/reset', [BrandingSettingController::class, 'reset'])->name('settings.branding.reset');
        });
        Route::get('settings/commerce', [CommerceSettingController::class, 'edit'])
            ->name('settings.commerce.edit');
        Route::put('settings/commerce', [CommerceSettingController::class, 'update'])
            ->name('settings.commerce.update');
        Route::middleware('role:super-admin')->group(function () {
            Route::post('settings/commerce/flush/preview', [CommerceSettingController::class, 'flushPreview'])
                ->name('settings.commerce.flush.preview');
            Route::post('settings/commerce/flush/execute', [CommerceSettingController::class, 'flushExecute'])
                ->name('settings.commerce.flush.execute');
            Route::post('settings/commerce/inactivity/preview', [CommerceSettingController::class, 'inactivityPreview'])
                ->name('settings.commerce.inactivity.preview');
            Route::post('settings/commerce/inactivity/execute', [CommerceSettingController::class, 'inactivityExecute'])
                ->name('settings.commerce.inactivity.execute');
        });
        Route::get('settings/legal', [LegalSettingController::class, 'edit'])
            ->name('settings.legal.edit');
        Route::put('settings/legal', [LegalSettingController::class, 'update'])
            ->name('settings.legal.update');
        Route::get('settings/contact', [ContactSettingController::class, 'edit'])
            ->name('settings.contact.edit');
        Route::put('settings/contact', [ContactSettingController::class, 'update'])
            ->name('settings.contact.update');

        Route::get('reserved-accounts', [ReservedAccountController::class, 'index'])
            ->name('reserved-accounts.index');
        Route::post('reserved-accounts/provision', [ReservedAccountController::class, 'provision'])
            ->name('reserved-accounts.provision');
        Route::post('reserved-accounts', [ReservedAccountController::class, 'store'])
            ->name('reserved-accounts.store');
        Route::put('reserved-accounts/{reservedAccount}', [ReservedAccountController::class, 'update'])
            ->name('reserved-accounts.update');

        Route::get('tickets', [AdminTicketController::class, 'index'])->middleware('permission:tickets.view')->name('tickets.index');
        Route::patch('tickets/{ticket}', [AdminTicketController::class, 'update'])->middleware('permission:tickets.manage')->name('tickets.update');
    });

require __DIR__.'/auth.php';
