<?php

declare(strict_types=1);

use App\Http\Controllers\Admin\AffiliateController as AdminAffiliateController;
use App\Http\Controllers\Admin\AuditLogController;
use App\Http\Controllers\Admin\CancellationSurveyController;
use App\Http\Controllers\Admin\CannedResponseController;
use App\Http\Controllers\Admin\ConfigGroupController;
use App\Http\Controllers\Admin\CouponController;
use App\Http\Controllers\Admin\CreditNoteController;
use App\Http\Controllers\Admin\CurrencyController;
use App\Http\Controllers\Admin\CustomerController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\Admin\DebitNoteController;
use App\Http\Controllers\Admin\EmailTemplateController;
use App\Http\Controllers\Admin\FraudQueueController;
use App\Http\Controllers\Admin\ImpersonationController;
use App\Http\Controllers\Admin\InvoiceController;
use App\Http\Controllers\Admin\KnowledgeBaseArticleController;
use App\Http\Controllers\Admin\KnowledgeBaseCategoryController;
use App\Http\Controllers\Admin\OrderController;
use App\Http\Controllers\Admin\PlanController;
use App\Http\Controllers\Admin\QuoteController;
use App\Http\Controllers\Admin\ReportController;
use App\Http\Controllers\Admin\RoleController;
use App\Http\Controllers\Admin\ServiceController;
use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Admin\StaffController;
use App\Http\Controllers\Admin\TaxRateController;
use App\Http\Controllers\Admin\TicketController as AdminTicketController;
use App\Http\Controllers\Admin\TicketSettingsController;
use App\Http\Controllers\Admin\TransactionController;
use App\Http\Controllers\Admin\WinbackCampaignController;
use Illuminate\Support\Facades\Route;

Route::get('/dashboard', [DashboardController::class, 'index'])->name('admin.dashboard');

// Customer Management
Route::middleware('permission:customers.view')->group(function (): void {
    Route::get('customers', [CustomerController::class, 'index'])->name('customers.index');
    Route::get('customers/{user}', [CustomerController::class, 'show'])->name('customers.show');
});

Route::middleware('permission:customers.edit')->group(function (): void {
    Route::get('customers/{user}/edit', [CustomerController::class, 'edit'])->name('customers.edit');
    Route::put('customers/{user}', [CustomerController::class, 'update'])->name('customers.update');
    Route::post('customers/{user}/reset-password', [CustomerController::class, 'resetPassword'])->name('customers.reset-password');
    Route::post('customers/{user}/send-notification', [CustomerController::class, 'sendNotification'])->name('customers.send-notification');
    Route::post('customers/{user}/place-order', [CustomerController::class, 'placeOrder'])->name('customers.place-order');
    Route::post('customers/{user}/force-logout', [CustomerController::class, 'forceLogout'])->name('customers.force-logout');
});

Route::post('customers/{user}/suspend', [CustomerController::class, 'suspend'])
    ->middleware('permission:customers.suspend')
    ->name('customers.suspend');

Route::post('customers/{user}/unsuspend', [CustomerController::class, 'unsuspend'])
    ->middleware('permission:customers.suspend')
    ->name('customers.unsuspend');

Route::delete('customers/{user}/purge', [CustomerController::class, 'purge'])
    ->middleware('permission:customers.delete')
    ->name('customers.purge');

// Plans (create before edit wildcard — index has no wildcard conflict)
Route::middleware('permission:plans.view')->group(function (): void {
    Route::get('plans', [PlanController::class, 'index'])->name('admin.plans.index');
});

Route::middleware('permission:plans.create')->group(function (): void {
    Route::get('plans/create', [PlanController::class, 'create'])->name('admin.plans.create');
    Route::post('plans', [PlanController::class, 'store'])->name('admin.plans.store');
});

Route::middleware('permission:plans.edit')->group(function (): void {
    Route::get('plans/{plan}/edit', [PlanController::class, 'edit'])->name('admin.plans.edit');
    Route::put('plans/{plan}', [PlanController::class, 'update'])->name('admin.plans.update');
});

Route::delete('plans/{plan}', [PlanController::class, 'destroy'])
    ->middleware('permission:plans.delete')
    ->name('admin.plans.destroy');

// Services
Route::middleware('permission:services.view')->group(function (): void {
    Route::get('services', [ServiceController::class, 'index'])->name('services.index');
    Route::get('services/{service}', [ServiceController::class, 'show'])->name('services.show');
    Route::put('services/{service}', [ServiceController::class, 'update'])->name('services.update');
});

Route::middleware('permission:services.suspend')->group(function (): void {
    Route::post('services/{service}/suspend', [ServiceController::class, 'suspend'])->name('services.suspend');
    Route::post('services/{service}/unsuspend', [ServiceController::class, 'unsuspend'])->name('services.unsuspend');
});

Route::post('services/{service}/terminate', [ServiceController::class, 'terminate'])
    ->middleware('permission:services.terminate')
    ->name('services.terminate');

Route::post('services/{service}/provision', [ServiceController::class, 'provision'])
    ->middleware('permission:services.provision')
    ->name('services.provision');

Route::post('services/{service}/restore', [ServiceController::class, 'restore'])
    ->middleware('permission:services.provision')
    ->name('services.restore');

Route::post('services/{service}/extend-expiry', [ServiceController::class, 'extendExpiry'])
    ->middleware('permission:services.extend')
    ->name('admin.services.extend-expiry');

Route::delete('services/{service}', [ServiceController::class, 'destroy'])
    ->middleware('permission:services.terminate')
    ->name('services.destroy');

// Invoices (create before wildcard {invoice})
Route::middleware('permission:invoices.create')->group(function (): void {
    Route::get('invoices/create', [InvoiceController::class, 'create'])->name('invoices.create');
    Route::post('invoices', [InvoiceController::class, 'store'])->name('invoices.store');
    Route::post('invoices/{invoice}/resend', [InvoiceController::class, 'resend'])->name('invoices.resend');
});

Route::middleware('permission:invoices.view')->group(function (): void {
    Route::get('invoices', [InvoiceController::class, 'index'])->name('invoices.index');
    Route::get('invoices/{invoice}', [InvoiceController::class, 'show'])->name('invoices.show');
    Route::get('invoices/{invoice}/download', [InvoiceController::class, 'download'])->name('invoices.download');
});

Route::middleware('permission:invoices.edit')->group(function (): void {
    Route::get('invoices/{invoice}/edit', [InvoiceController::class, 'edit'])->name('invoices.edit');
    Route::put('invoices/{invoice}', [InvoiceController::class, 'update'])->name('invoices.update');
});

Route::post('invoices/{invoice}/void', [InvoiceController::class, 'void'])
    ->middleware('permission:invoices.void')
    ->name('invoices.void');

// Transactions
Route::middleware('permission:invoices.view')->group(function (): void {
    Route::get('transactions', [TransactionController::class, 'index'])->name('transactions.index');
    Route::get('transactions/{transaction}', [TransactionController::class, 'show'])->name('transactions.show');
});

// Credit Notes (create before wildcard {creditNote})
Route::middleware('permission:credit_notes.create')->group(function (): void {
    Route::get('credit-notes/create', [CreditNoteController::class, 'create'])->name('credit-notes.create');
    Route::post('credit-notes', [CreditNoteController::class, 'store'])->name('credit-notes.store');
});

Route::middleware('permission:credit_notes.view')->group(function (): void {
    Route::get('credit-notes', [CreditNoteController::class, 'index'])->name('credit-notes.index');
    Route::get('credit-notes/{creditNote}', [CreditNoteController::class, 'show'])->name('credit-notes.show');
    Route::get('credit-notes/{creditNote}/download', [CreditNoteController::class, 'download'])->name('credit-notes.download');
});

Route::post('credit-notes/{creditNote}/void', [CreditNoteController::class, 'void'])
    ->middleware('permission:credit_notes.void')
    ->name('credit-notes.void');

// Debit Notes (create before wildcard {debitNote})
Route::middleware('permission:debit_notes.create')->group(function (): void {
    Route::get('debit-notes/create', [DebitNoteController::class, 'create'])->name('debit-notes.create');
    Route::post('debit-notes', [DebitNoteController::class, 'store'])->name('debit-notes.store');
});

Route::middleware('permission:debit_notes.view')->group(function (): void {
    Route::get('debit-notes', [DebitNoteController::class, 'index'])->name('debit-notes.index');
    Route::get('debit-notes/{debitNote}', [DebitNoteController::class, 'show'])->name('debit-notes.show');
    Route::get('debit-notes/{debitNote}/download', [DebitNoteController::class, 'download'])->name('debit-notes.download');
});

Route::post('debit-notes/{debitNote}/void', [DebitNoteController::class, 'void'])
    ->middleware('permission:debit_notes.void')
    ->name('debit-notes.void');

// Coupons (create/redemptions before wildcard {coupon})
Route::middleware('permission:coupons.create')->group(function (): void {
    Route::get('coupons/create', [CouponController::class, 'create'])->name('admin.coupons.create');
    Route::post('coupons', [CouponController::class, 'store'])->name('admin.coupons.store');
});

Route::middleware('permission:coupons.view')->group(function (): void {
    Route::get('coupons', [CouponController::class, 'index'])->name('admin.coupons.index');
    Route::get('coupons/redemptions', [CouponController::class, 'redemptions'])->name('admin.coupons.redemptions');
    Route::get('coupons/{coupon}', [CouponController::class, 'show'])->name('admin.coupons.show');
});

Route::middleware('permission:coupons.edit')->group(function (): void {
    Route::get('coupons/{coupon}/edit', [CouponController::class, 'edit'])->name('admin.coupons.edit');
    Route::put('coupons/{coupon}', [CouponController::class, 'update'])->name('admin.coupons.update');
});

Route::delete('coupons/{coupon}', [CouponController::class, 'destroy'])
    ->middleware('permission:coupons.delete')
    ->name('admin.coupons.destroy');

// Orders
Route::middleware('permission:invoices.view')->group(function (): void {
    Route::get('orders', [OrderController::class, 'index'])->name('orders.index');
    Route::get('orders/{order}', [OrderController::class, 'show'])->name('orders.show');
    Route::post('orders/{order}/process', [OrderController::class, 'process'])->name('orders.process');
    Route::post('orders/{order}/complete', [OrderController::class, 'complete'])->name('orders.complete');
    Route::post('orders/{order}/cancel', [OrderController::class, 'cancel'])->name('orders.cancel');
    Route::put('orders/{order}/notes', [OrderController::class, 'updateNotes'])->name('orders.notes');
});

// Tax Rates (create before edit wildcards)
Route::middleware('permission:settings.edit')->group(function (): void {
    Route::get('tax-rates/create', [TaxRateController::class, 'create'])->name('admin.tax-rates.create');
    Route::post('tax-rates', [TaxRateController::class, 'store'])->name('admin.tax-rates.store');
    Route::get('tax-rates/{taxRate}/edit', [TaxRateController::class, 'edit'])->name('admin.tax-rates.edit');
    Route::put('tax-rates/{taxRate}', [TaxRateController::class, 'update'])->name('admin.tax-rates.update');
    Route::delete('tax-rates/{taxRate}', [TaxRateController::class, 'destroy'])->name('admin.tax-rates.destroy');
    Route::post('tax-rates/{taxRate}/toggle-active', [TaxRateController::class, 'toggleActive'])->name('admin.tax-rates.toggle-active');
});

Route::middleware('permission:settings.view')->group(function (): void {
    Route::get('tax-rates', [TaxRateController::class, 'index'])->name('admin.tax-rates.index');
});

// Currencies
Route::middleware('permission:settings.view')->group(function (): void {
    Route::get('currencies', [CurrencyController::class, 'index'])->name('admin.currencies.index');
});

Route::middleware('permission:settings.edit')->group(function (): void {
    Route::post('currencies', [CurrencyController::class, 'store'])->name('admin.currencies.store');
    Route::put('currencies/{currency}', [CurrencyController::class, 'update'])->name('admin.currencies.update');
    Route::delete('currencies/{currency}', [CurrencyController::class, 'destroy'])->name('admin.currencies.destroy');
    Route::post('currencies/sync-rates', [CurrencyController::class, 'syncRates'])->name('admin.currencies.sync-rates');
});

// Quotes (create before wildcard {quote})
Route::middleware('permission:invoices.create')->group(function (): void {
    Route::get('quotes/create', [QuoteController::class, 'create'])->name('admin.quotes.create');
    Route::post('quotes', [QuoteController::class, 'store'])->name('admin.quotes.store');
    Route::post('quotes/{quote}/send', [QuoteController::class, 'send'])->name('admin.quotes.send');
    Route::get('quotes/{quote}/download', [QuoteController::class, 'download'])->name('admin.quotes.download');
});

Route::middleware('permission:invoices.view')->group(function (): void {
    Route::get('quotes', [QuoteController::class, 'index'])->name('admin.quotes.index');
    Route::get('quotes/{quote}', [QuoteController::class, 'show'])->name('admin.quotes.show');
});

Route::middleware('permission:invoices.edit')->group(function (): void {
    Route::get('quotes/{quote}/edit', [QuoteController::class, 'edit'])->name('admin.quotes.edit');
    Route::put('quotes/{quote}', [QuoteController::class, 'update'])->name('admin.quotes.update');
});

Route::delete('quotes/{quote}', [QuoteController::class, 'destroy'])
    ->middleware('permission:invoices.void')
    ->name('admin.quotes.destroy');

// Email Templates
Route::middleware('permission:settings.view')->group(function (): void {
    Route::get('email-templates', [EmailTemplateController::class, 'index'])->name('admin.email-templates.index');
    Route::get('email-templates/{emailTemplate}/edit', [EmailTemplateController::class, 'edit'])->name('admin.email-templates.edit');
});

Route::middleware('permission:settings.edit')->group(function (): void {
    Route::put('email-templates/{emailTemplate}', [EmailTemplateController::class, 'update'])->name('admin.email-templates.update');
    Route::post('email-templates/{emailTemplate}/preview', [EmailTemplateController::class, 'preview'])->name('admin.email-templates.preview');
    Route::post('email-templates/{emailTemplate}/reset', [EmailTemplateController::class, 'resetToDefault'])->name('admin.email-templates.reset');
});

// Financial Reports
Route::middleware('permission:reports.view')->group(function (): void {
    Route::get('reports', [ReportController::class, 'index'])->name('reports.index');
    Route::post('reports/generate', [ReportController::class, 'generate'])->name('reports.generate');
});

Route::post('reports/export', [ReportController::class, 'export'])
    ->middleware('permission:reports.export')
    ->name('reports.export');

// Audit Logs
Route::middleware('permission:audit_logs.view')->group(function (): void {
    Route::get('audit-logs', [AuditLogController::class, 'index'])->name('audit-logs.index');
});

Route::get('audit-logs/export', [AuditLogController::class, 'export'])
    ->middleware('permission:audit_logs.export')
    ->name('audit-logs.export');

// Settings
Route::middleware('permission:settings.view')->group(function (): void {
    Route::get('settings', [SettingsController::class, 'index'])->name('admin.settings.index');
});

Route::middleware('permission:settings.edit')->group(function (): void {
    Route::put('settings', [SettingsController::class, 'update'])->name('admin.settings.update');
    Route::post('settings/test-api', [SettingsController::class, 'testApiConnection'])->name('admin.settings.test-api');
    Route::post('settings/test-discord', [SettingsController::class, 'testDiscordWebhook'])->name('admin.settings.test-discord');
});

// Ticket Settings (must be before tickets/{ticket} wildcard)
Route::middleware('permission:settings.edit')->prefix('tickets/settings')->name('admin.ticket-settings.')->group(function (): void {
    Route::get('/', [TicketSettingsController::class, 'index'])->name('index');
    // Departments
    Route::post('departments', [TicketSettingsController::class, 'storeDepartment'])->name('departments.store');
    Route::put('departments/{department}', [TicketSettingsController::class, 'updateDepartment'])->name('departments.update');
    Route::delete('departments/{department}', [TicketSettingsController::class, 'destroyDepartment'])->name('departments.destroy');
    // SLA Policies
    Route::post('sla-policies', [TicketSettingsController::class, 'storeSlaPolicy'])->name('sla.store');
    Route::put('sla-policies/{slaPolicy}', [TicketSettingsController::class, 'updateSlaPolicy'])->name('sla.update');
    Route::delete('sla-policies/{slaPolicy}', [TicketSettingsController::class, 'destroySlaPolicy'])->name('sla.destroy');
    // Business Hours
    Route::put('business-hours', [TicketSettingsController::class, 'updateBusinessHours'])->name('business-hours.update');
    // Tags
    Route::post('tags', [TicketSettingsController::class, 'storeTag'])->name('tags.store');
    Route::put('tags/{ticketTag}', [TicketSettingsController::class, 'updateTag'])->name('tags.update');
    Route::delete('tags/{ticketTag}', [TicketSettingsController::class, 'destroyTag'])->name('tags.destroy');
    // Custom Fields
    Route::post('custom-fields', [TicketSettingsController::class, 'storeCustomField'])->name('custom-fields.store');
    Route::put('custom-fields/{ticketCustomField}', [TicketSettingsController::class, 'updateCustomField'])->name('custom-fields.update');
    Route::delete('custom-fields/{ticketCustomField}', [TicketSettingsController::class, 'destroyCustomField'])->name('custom-fields.destroy');
});

// Support Tickets
Route::middleware('permission:tickets.view')->group(function (): void {
    Route::get('tickets', [AdminTicketController::class, 'index'])->name('admin.tickets.index');
    Route::get('tickets/{ticket}', [AdminTicketController::class, 'show'])->name('admin.tickets.show');
});

Route::post('tickets/{ticket}/reply', [AdminTicketController::class, 'reply'])
    ->middleware('permission:tickets.reply')
    ->name('admin.tickets.reply');

Route::put('tickets/{ticket}/status', [AdminTicketController::class, 'updateStatus'])
    ->middleware('permission:tickets.close')
    ->name('admin.tickets.status');

Route::post('tickets/{ticket}/assign', [AdminTicketController::class, 'assign'])
    ->middleware('permission:tickets.reply')
    ->name('admin.tickets.assign');

Route::post('tickets/{ticket}/merge', [AdminTicketController::class, 'merge'])
    ->middleware('permission:tickets.close')
    ->name('admin.tickets.merge');

Route::post('tickets/{ticket}/tags', [AdminTicketController::class, 'updateTags'])
    ->middleware('permission:tickets.reply')
    ->name('admin.tickets.tags');

// Canned Responses
Route::middleware('permission:tickets.reply')->group(function (): void {
    Route::resource('canned-responses', CannedResponseController::class)->names('admin.canned-responses');
});

// Win-back Campaigns
Route::middleware('permission:customers.view')->group(function (): void {
    Route::resource('winback-campaigns', WinbackCampaignController::class);
});

// Cancellation Surveys
Route::get('cancellation-surveys', [CancellationSurveyController::class, 'index'])
    ->middleware('permission:customers.view')
    ->name('cancellation-surveys.index');

// Config Groups (create before wildcards)
Route::middleware('permission:plans.edit')->group(function (): void {
    Route::get('config-groups/create', [ConfigGroupController::class, 'create'])->name('admin.config-groups.create');
    Route::post('config-groups', [ConfigGroupController::class, 'store'])->name('admin.config-groups.store');
    Route::get('config-groups/{configGroup}/edit', [ConfigGroupController::class, 'edit'])->name('admin.config-groups.edit');
    Route::put('config-groups/{configGroup}', [ConfigGroupController::class, 'update'])->name('admin.config-groups.update');
    Route::delete('config-groups/{configGroup}', [ConfigGroupController::class, 'destroy'])->name('admin.config-groups.destroy');
});

Route::middleware('permission:plans.view')->group(function (): void {
    Route::get('config-groups', [ConfigGroupController::class, 'index'])->name('admin.config-groups.index');
});

// Impersonation
Route::post('impersonate/{user}', [ImpersonationController::class, 'start'])
    ->middleware('permission:customers.impersonate')
    ->name('impersonate.start');

Route::post('impersonate/stop', [ImpersonationController::class, 'stop'])
    ->name('impersonate.stop');

// Role Management (must come before staff/{user} wildcard)
Route::middleware('permission:staff.manage')->group(function (): void {
    Route::get('staff/roles', [RoleController::class, 'index'])->name('admin.roles.index');
    Route::get('staff/roles/create', [RoleController::class, 'create'])->name('admin.roles.create');
    Route::post('staff/roles', [RoleController::class, 'store'])->name('admin.roles.store');
    Route::get('staff/roles/{role}/edit', [RoleController::class, 'edit'])->name('admin.roles.edit');
    Route::put('staff/roles/{role}', [RoleController::class, 'update'])->name('admin.roles.update');
    Route::delete('staff/roles/{role}', [RoleController::class, 'destroy'])->name('admin.roles.destroy');
});

// Knowledge Base
Route::middleware('permission:settings.edit')->group(function (): void {
    Route::resource('knowledge-base/categories', KnowledgeBaseCategoryController::class)
        ->except(['show'])->names('admin.kb.categories')->parameters(['categories' => 'category']);
    Route::resource('knowledge-base/articles', KnowledgeBaseArticleController::class)
        ->names('admin.kb.articles')->parameters(['articles' => 'article']);
});

// Staff Management
Route::middleware('permission:staff.view')->group(function (): void {
    Route::get('staff', [StaffController::class, 'index'])->name('admin.staff.index');
    Route::get('staff/{user}', [StaffController::class, 'show'])->name('admin.staff.show');
});

// Affiliates (static routes before wildcards)
Route::middleware('permission:affiliates.view')->group(function (): void {
    Route::get('affiliates/commissions/queue', [AdminAffiliateController::class, 'commissions'])->name('admin.affiliates.commissions');
    Route::get('affiliates/payouts/queue', [AdminAffiliateController::class, 'payouts'])->name('admin.affiliates.payouts');
    Route::get('affiliates/settings', [AdminAffiliateController::class, 'settings'])->name('admin.affiliates.settings');
    Route::get('affiliates', [AdminAffiliateController::class, 'index'])->name('admin.affiliates.index');
    Route::get('affiliates/{affiliate}', [AdminAffiliateController::class, 'show'])->name('admin.affiliates.show');
});

Route::middleware('permission:affiliates.approve')->group(function (): void {
    Route::post('affiliates/{affiliate}/approve', [AdminAffiliateController::class, 'approve'])->name('admin.affiliates.approve');
    Route::post('affiliates/{affiliate}/suspend', [AdminAffiliateController::class, 'suspend'])->name('admin.affiliates.suspend');
    Route::post('affiliate-commissions/{commission}/approve', [AdminAffiliateController::class, 'approveCommission'])->name('admin.affiliates.commissions.approve');
});

Route::middleware('permission:affiliates.payout')->group(function (): void {
    Route::post('affiliate-payouts/{payout}/process', [AdminAffiliateController::class, 'processPayout'])->name('admin.affiliates.payouts.process');
});

// Fraud Queue
Route::middleware('permission:invoices.view')->group(function (): void {
    Route::get('fraud-queue', [FraudQueueController::class, 'index'])->name('admin.fraud-queue.index');
    Route::get('fraud-queue/{assessment}', [FraudQueueController::class, 'show'])->name('admin.fraud-queue.show');
    Route::post('fraud-queue/{assessment}/approve', [FraudQueueController::class, 'approve'])->name('admin.fraud-queue.approve');
    Route::post('fraud-queue/{assessment}/reject', [FraudQueueController::class, 'reject'])->name('admin.fraud-queue.reject');
});
