<?php

use App\Http\Controllers\ProfileController;
use App\Installer\Services\InstallationManager;
use Illuminate\Support\Facades\Route;

Route::get('/', function (InstallationManager $installationManager) {
    // If not installed, redirect to installer
    if (! $installationManager->isInstalled()) {
        return redirect()->route('installer.step1');
    }

    // If user is already authenticated, redirect to their dashboard
    if (auth()->check()) {
        $user = auth()->user();
        if ($user->role) {
            $roleSlug = $user->role->slug;
            if (in_array($roleSlug, ['super-admin', 'admin'])) {
                return redirect()->route('admin.dashboard');
            }
            if ($roleSlug === 'customer') {
                return redirect()->route('customer.dashboard');
            }
        }

        return redirect()->route('admin.dashboard');
    }

    // If not authenticated, redirect to login
    return redirect()->route('login');
});

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

// Admin Routes
Route::middleware(['auth'])->prefix('admin')->name('admin.')->group(function () {
    // Smart billing reminders (automation settings, templates, manual send API)
    Route::prefix('reminders')->name('reminders.')->group(function () {
        Route::middleware('permission:manage_reminders')->group(function () {
            Route::get('/settings', [\App\Http\Controllers\Admin\ReminderSettingsController::class, 'edit'])->name('settings');
            Route::post('/settings', [\App\Http\Controllers\Admin\ReminderSettingsController::class, 'update'])->name('settings.update');
        });
        Route::middleware('permission:manage_email_templates')->group(function () {
            Route::get('/email-templates', [\App\Http\Controllers\Admin\ReminderEmailTemplateController::class, 'index'])->name('email-templates.index');
            Route::get('/email-templates/{emailTemplate}/edit', [\App\Http\Controllers\Admin\ReminderEmailTemplateController::class, 'edit'])->name('email-templates.edit');
            Route::put('/email-templates/{emailTemplate}', [\App\Http\Controllers\Admin\ReminderEmailTemplateController::class, 'update'])->name('email-templates.update');
            Route::post('/email-templates/{emailTemplate}/preview', [\App\Http\Controllers\Admin\ReminderEmailTemplateController::class, 'preview'])->name('email-templates.preview');
            Route::post('/email-templates/{emailTemplate}/reset', [\App\Http\Controllers\Admin\ReminderEmailTemplateController::class, 'reset'])->name('email-templates.reset');
        });
    });

    // Dashboard
    Route::get('/dashboard', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');

    // Dashboard API routes
    Route::prefix('dashboard')->name('dashboard.')->group(function () {
        Route::get('/calendar', [\App\Http\Controllers\Admin\DashboardController::class, 'getCalendar'])->name('calendar');
        Route::get('/chart-data', [\App\Http\Controllers\Admin\DashboardController::class, 'getChartData'])->name('chart-data');
        Route::get('/notes', [\App\Http\Controllers\Admin\DashboardController::class, 'getNotes'])->name('notes');
        Route::post('/notes', [\App\Http\Controllers\Admin\DashboardController::class, 'storeNote'])->name('notes.store');
        Route::put('/notes/{note}', [\App\Http\Controllers\Admin\DashboardController::class, 'updateNote'])->name('notes.update');
        Route::delete('/notes/{note}', [\App\Http\Controllers\Admin\DashboardController::class, 'deleteNote'])->name('notes.delete');
    });

    // Notifications
    Route::get('/notifications', [\App\Http\Controllers\Admin\NotificationController::class, 'index'])->name('notifications.index');

    // Search
    Route::get('/search', [\App\Http\Controllers\Admin\SearchController::class, 'search'])->name('search');

    // Invoices
    // GET must be registered before Route::resource; otherwise "preview" is captured as {invoice} and returns 404.
    // Do not redirect to create here: failed store() used to redirect "back" to this URL and a redirect
    // would drop validation errors and strand users on an empty create form.
    Route::get('/invoices/preview', function () {
        return view('admin.invoices.preview-landing');
    })->name('invoices.preview.get');
    Route::post('/invoices/preview', [\App\Http\Controllers\Admin\InvoiceController::class, 'preview'])->name('invoices.preview');
    Route::get('/invoices/{invoice}/preview', [\App\Http\Controllers\Admin\InvoiceController::class, 'previewExisting'])->name('invoices.preview-existing');
    Route::get('/invoices/{invoice}/view', [\App\Http\Controllers\Admin\InvoiceController::class, 'view'])->name('invoices.view');
    Route::post('/invoices/{invoice}/send-email', [\App\Http\Controllers\Admin\InvoiceController::class, 'sendEmail'])->name('invoices.send-email');
    Route::post('/invoices/{invoice}/send-whatsapp', [\App\Http\Controllers\Admin\InvoiceController::class, 'sendWhatsApp'])->name('invoices.send-whatsapp');
    Route::get('/invoices/{invoice}/share-link', [\App\Http\Controllers\Admin\InvoiceController::class, 'getShareLink'])->name('invoices.share-link');
    Route::get('/invoices/{invoice}/data', [\App\Http\Controllers\Admin\InvoiceController::class, 'getInvoiceData'])->name('invoices.data');
    Route::patch('/invoices/{invoice}/status', [\App\Http\Controllers\Admin\InvoiceController::class, 'updateStatus'])->name('invoices.update-status');
    Route::post('/invoices/{invoice}/mark-paid', [\App\Http\Controllers\Admin\InvoiceController::class, 'markAsPaid'])->name('invoices.mark-paid');
    Route::post('/invoices/{invoice}/send-reminder', [\App\Http\Controllers\Admin\ManualReminderController::class, 'sendInvoice'])
        ->middleware('permission:send_manual_reminders')
        ->name('invoices.send-reminder');
    Route::resource('invoices', \App\Http\Controllers\Admin\InvoiceController::class);
    Route::get('/invoices/{invoice}/download', [\App\Http\Controllers\Admin\InvoiceController::class, 'downloadPdf'])->name('invoices.download');

    // API endpoints for invoice form dropdowns
    Route::get('/invoices/api/company-settings', [\App\Http\Controllers\Admin\InvoiceController::class, 'getCompanySettings'])->name('invoices.api.company-settings');
    Route::get('/api/companies', [\App\Http\Controllers\Admin\InvoiceController::class, 'getCompanies'])->name('api.companies');
    Route::get('/api/customers', [\App\Http\Controllers\Admin\InvoiceController::class, 'getCustomersAjax'])->name('api.customers');

    // Estimates
    Route::resource('estimates', \App\Http\Controllers\Admin\EstimateController::class);

    // Quotations
    Route::post('/quotations/preview', [\App\Http\Controllers\Admin\QuotationController::class, 'preview'])->name('quotations.preview');
    Route::get('/quotations/api/company-settings', [\App\Http\Controllers\Admin\QuotationController::class, 'getCompanySettings'])->name('quotations.api.company-settings');
    Route::get('/quotations/api/companies', [\App\Http\Controllers\Admin\InvoiceController::class, 'getCompanies'])->name('quotations.api.companies');
    Route::get('/quotations/api/customers', [\App\Http\Controllers\Admin\InvoiceController::class, 'getCustomersAjax'])->name('quotations.api.customers');
    Route::post('/quotations/{quotation}/convert', [\App\Http\Controllers\Admin\QuotationController::class, 'convertToInvoice'])->name('quotations.convert');
    Route::post('/quotations/{quotation}/send-reminder', [\App\Http\Controllers\Admin\ManualReminderController::class, 'sendQuotation'])
        ->middleware('permission:send_manual_reminders')
        ->name('quotations.send-reminder');
    Route::post('/quotations/{quotation}/send-email', [\App\Http\Controllers\Admin\QuotationController::class, 'sendEmail'])->name('quotations.send-email');
    Route::post('/quotations/{quotation}/send-whatsapp', [\App\Http\Controllers\Admin\QuotationController::class, 'sendWhatsApp'])->name('quotations.send-whatsapp');
    Route::get('/quotations/{quotation}/share-link', [\App\Http\Controllers\Admin\QuotationController::class, 'getShareLink'])->name('quotations.share-link');
    Route::get('/quotations/{quotation}/data', [\App\Http\Controllers\Admin\QuotationController::class, 'getQuotationData'])->name('quotations.data');
    Route::get('/quotations/{quotation}/download', [\App\Http\Controllers\Admin\QuotationController::class, 'downloadPdf'])->name('quotations.download');
    Route::get('/quotations/{quotation}/print', [\App\Http\Controllers\Admin\QuotationController::class, 'printView'])->name('quotations.print');
    Route::resource('quotations', \App\Http\Controllers\Admin\QuotationController::class);

    // Payments
    Route::resource('payments', \App\Http\Controllers\Admin\PaymentController::class);

    // Recurring Invoices
    Route::resource('recurring-invoices', \App\Http\Controllers\Admin\RecurringInvoiceController::class);

    // Invoice Templates
    Route::prefix('invoice-templates')->name('invoice-templates.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\InvoiceTemplateController::class, 'index'])->name('index');
        Route::post('/set-default', [\App\Http\Controllers\Admin\InvoiceTemplateController::class, 'setDefault'])->name('set-default');
    });

    // Tax Rates (for products and other modules)
    Route::get('/tax-rates', [\App\Http\Controllers\Admin\SettingsController::class, 'getTaxRates'])->name('tax-rates.index');
    Route::post('/tax-rates', [\App\Http\Controllers\Admin\SettingsController::class, 'storeTaxRate'])->name('tax-rates.store');

    // Products & Services
    Route::prefix('products')->name('products.')->group(function () {
        // Categories (must come before product routes to avoid route conflicts)
        Route::get('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'index'])->name('categories.index');
        Route::get('/categories/{category}', [\App\Http\Controllers\Admin\CategoryController::class, 'show'])->name('categories.show');
        Route::post('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'store'])->name('categories.store');
        Route::put('/categories/{category}', [\App\Http\Controllers\Admin\CategoryController::class, 'update'])->name('categories.update');
        Route::delete('/categories/{category}', [\App\Http\Controllers\Admin\CategoryController::class, 'destroy'])->name('categories.destroy');

        // Brands (must come before product routes to avoid route conflicts)
        Route::get('/brands', [\App\Http\Controllers\Admin\BrandController::class, 'index'])->name('brands.index');
        Route::get('/brands/{brand}', [\App\Http\Controllers\Admin\BrandController::class, 'show'])->name('brands.show');
        Route::post('/brands', [\App\Http\Controllers\Admin\BrandController::class, 'store'])->name('brands.store');
        Route::put('/brands/{brand}', [\App\Http\Controllers\Admin\BrandController::class, 'update'])->name('brands.update');
        Route::delete('/brands/{brand}', [\App\Http\Controllers\Admin\BrandController::class, 'destroy'])->name('brands.destroy');

        // Units (must come before product routes to avoid route conflicts)
        Route::get('/units', [\App\Http\Controllers\Admin\UnitController::class, 'index'])->name('units.index');
        Route::get('/units/{unit}', [\App\Http\Controllers\Admin\UnitController::class, 'show'])->name('units.show');
        Route::post('/units', [\App\Http\Controllers\Admin\UnitController::class, 'store'])->name('units.store');
        Route::put('/units/{unit}', [\App\Http\Controllers\Admin\UnitController::class, 'update'])->name('units.update');
        Route::delete('/units/{unit}', [\App\Http\Controllers\Admin\UnitController::class, 'destroy'])->name('units.destroy');

        // Products (wildcard routes must come last)
        Route::get('/', [\App\Http\Controllers\Admin\ProductController::class, 'index'])->name('index');
        Route::get('/create', [\App\Http\Controllers\Admin\ProductController::class, 'create'])->name('create');
        Route::post('/', [\App\Http\Controllers\Admin\ProductController::class, 'store'])->name('store');
        Route::get('/{product}', [\App\Http\Controllers\Admin\ProductController::class, 'show'])->name('show');
        Route::get('/{product}/edit', [\App\Http\Controllers\Admin\ProductController::class, 'edit'])->name('edit');
        Route::put('/{product}', [\App\Http\Controllers\Admin\ProductController::class, 'update'])->name('update');
        Route::patch('/{product}/status', [\App\Http\Controllers\Admin\ProductController::class, 'updateStatus'])->name('updateStatus');
        Route::delete('/{product}', [\App\Http\Controllers\Admin\ProductController::class, 'destroy'])->name('destroy');
    });

    // Customers (export must be registered before resource so "export" is not captured as {customer})
    Route::get('customers/export', [\App\Http\Controllers\Admin\CustomerController::class, 'export'])->name('customers.export');
    Route::resource('customers', \App\Http\Controllers\Admin\CustomerController::class);

    // Receipts (specific routes before resource)
    Route::get('receipts/{receipt}/print', [\App\Http\Controllers\Admin\ReceiptController::class, 'printView'])->name('receipts.print');
    Route::get('receipts/{receipt}/download', [\App\Http\Controllers\Admin\ReceiptController::class, 'downloadPdf'])->name('receipts.download');
    Route::post('receipts/{receipt}/send-email', [\App\Http\Controllers\Admin\ReceiptController::class, 'sendEmail'])->name('receipts.send-email');
    Route::post('receipts/{receipt}/send-whatsapp', [\App\Http\Controllers\Admin\ReceiptController::class, 'sendWhatsApp'])->name('receipts.send-whatsapp');
    Route::get('receipts/{receipt}/share-link', [\App\Http\Controllers\Admin\ReceiptController::class, 'getShareLink'])->name('receipts.share-link');
    Route::resource('receipts', \App\Http\Controllers\Admin\ReceiptController::class)->only(['index', 'show', 'store']);

    // Inventory
    Route::prefix('inventory')->name('inventory.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\InventoryController::class, 'index'])->name('index');
        Route::get('/products', [\App\Http\Controllers\Admin\InventoryController::class, 'getProducts'])->name('products');
        Route::post('/', [\App\Http\Controllers\Admin\InventoryController::class, 'store'])->name('store');
        Route::get('/{item}', [\App\Http\Controllers\Admin\InventoryController::class, 'show'])->name('show');
        Route::put('/{item}', [\App\Http\Controllers\Admin\InventoryController::class, 'update'])->name('update');
        Route::delete('/{item}', [\App\Http\Controllers\Admin\InventoryController::class, 'destroy'])->name('destroy');
    });

    // Credit Notes
    Route::prefix('credit-notes')->name('credit-notes.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\CreditNoteController::class, 'index'])->name('index');
        Route::get('/create', [\App\Http\Controllers\Admin\CreditNoteController::class, 'create'])->name('create');
        Route::post('/', [\App\Http\Controllers\Admin\CreditNoteController::class, 'store'])->name('store');
        Route::get('/{creditNote}', [\App\Http\Controllers\Admin\CreditNoteController::class, 'show'])->name('show');
        Route::get('/{creditNote}/edit', [\App\Http\Controllers\Admin\CreditNoteController::class, 'edit'])->name('edit');
        Route::put('/{creditNote}', [\App\Http\Controllers\Admin\CreditNoteController::class, 'update'])->name('update');
        Route::delete('/{creditNote}', [\App\Http\Controllers\Admin\CreditNoteController::class, 'destroy'])->name('destroy');
    });

    // Delivery Challans
    Route::prefix('delivery-challans')->name('delivery-challans.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'index'])->name('index');
        Route::get('/create', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'create'])->name('create');
        Route::post('/', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'store'])->name('store');
        Route::get('/{challan}', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'show'])->name('show');
        Route::get('/{challan}/edit', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'edit'])->name('edit');
        Route::put('/{challan}', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'update'])->name('update');
        Route::delete('/{challan}', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'destroy'])->name('destroy');

        // API endpoints for Select2
        Route::get('/api/invoices', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getInvoices'])->name('api.invoices');
        Route::get('/api/customers', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getCustomers'])->name('api.customers');
        Route::get('/api/users', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getUsers'])->name('api.users');
        Route::get('/api/company-details', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getCompanyDetails'])->name('api.company-details');
        Route::get('/api/bank-accounts', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getBankAccounts'])->name('api.bank-accounts');
        Route::get('/api/signatures', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getSignatures'])->name('api.signatures');
        Route::get('/api/products', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getProducts'])->name('api.products');
        Route::get('/api/invoice/{id}', [\App\Http\Controllers\Admin\DeliveryChallanController::class, 'getInvoiceDetails'])->name('api.invoice-details');
    });

    // Finance & Accounts
    // Banking
    Route::prefix('banking')->name('banking.')->group(function () {
        Route::get('/overview', [\App\Http\Controllers\Admin\BankingController::class, 'overview'])->name('overview');
        Route::get('/balance-trend', [\App\Http\Controllers\Admin\BankingController::class, 'balanceTrend'])->name('balance-trend');
        Route::get('/create', [\App\Http\Controllers\Admin\BankingController::class, 'create'])->name('create');
        Route::post('/', [\App\Http\Controllers\Admin\BankingController::class, 'store'])->name('store');
        Route::get('/{id}/edit', [\App\Http\Controllers\Admin\BankingController::class, 'edit'])->name('edit');
        Route::put('/{id}', [\App\Http\Controllers\Admin\BankingController::class, 'update'])->name('update');
        Route::delete('/{id}', [\App\Http\Controllers\Admin\BankingController::class, 'destroy'])->name('destroy');
        Route::post('/{id}/set-default', [\App\Http\Controllers\Admin\BankingController::class, 'setDefault'])->name('set-default');
        Route::get('/transactions', [\App\Http\Controllers\Admin\BankingController::class, 'transactions'])->name('transactions.index');
        Route::get('/transactions/api', [\App\Http\Controllers\Admin\BankingController::class, 'getTransactions'])->name('transactions.api');
        Route::get('/transactions/export/csv', [\App\Http\Controllers\Admin\BankingController::class, 'exportBankTransactionsCsv'])->name('transactions.export.csv');
        Route::get('/transactions/export/pdf', [\App\Http\Controllers\Admin\BankingController::class, 'exportBankTransactionsPdf'])->name('transactions.export.pdf');
    });

    // Expenses
    Route::patch('/expenses/{expense}/status', [\App\Http\Controllers\Admin\ExpenseController::class, 'updateStatus'])->name('expenses.update-status');
    Route::resource('expenses', \App\Http\Controllers\Admin\ExpenseController::class);

    // Purchases
    Route::resource('purchases', \App\Http\Controllers\Admin\PurchaseController::class);
    Route::get('/purchases/api/company-settings', [\App\Http\Controllers\Admin\PurchaseController::class, 'getCompanySettings'])->name('purchases.api.company-settings');
    Route::get('/purchases/api/companies', [\App\Http\Controllers\Admin\PurchaseController::class, 'getCompanies'])->name('purchases.api.companies');
    Route::get('/purchases/api/suppliers', [\App\Http\Controllers\Admin\PurchaseController::class, 'getSuppliers'])->name('purchases.api.suppliers');
    Route::get('/purchases/api/products', [\App\Http\Controllers\Admin\PurchaseController::class, 'getProducts'])->name('purchases.api.products');
    Route::get('/purchases/api/bank-accounts', [\App\Http\Controllers\Admin\PurchaseController::class, 'getBankAccounts'])->name('purchases.api.bank-accounts');
    Route::get('/purchases/api/signatures', [\App\Http\Controllers\Admin\PurchaseController::class, 'getSignatures'])->name('purchases.api.signatures');

    // Suppliers
    Route::resource('suppliers', \App\Http\Controllers\Admin\SupplierController::class);
    Route::get('/suppliers/api/suppliers', [\App\Http\Controllers\Admin\SupplierController::class, 'getSuppliers'])->name('suppliers.api.suppliers');

    // Supplier Payments
    Route::resource('supplier-payments', \App\Http\Controllers\Admin\SupplierPaymentController::class);
    Route::get('/supplier-payments/api/purchases', [\App\Http\Controllers\Admin\SupplierPaymentController::class, 'getPurchases'])->name('supplier-payments.api.purchases');
    Route::get('/supplier-payments/api/payment-sources', [\App\Http\Controllers\Admin\SupplierPaymentController::class, 'getPaymentSources'])->name('supplier-payments.api.payment-sources');

    // Debit Notes
    Route::resource('debit-notes', \App\Http\Controllers\Admin\DebitNoteController::class);
    Route::get('/debit-notes/api/purchases', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getPurchases'])->name('debit-notes.api.purchases');
    Route::get('/debit-notes/api/companies', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getCompanies'])->name('debit-notes.api.companies');
    Route::get('/debit-notes/api/suppliers', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getSuppliers'])->name('debit-notes.api.suppliers');
    Route::get('/debit-notes/api/products', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getProducts'])->name('debit-notes.api.products');
    Route::get('/debit-notes/api/company-settings', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getCompanySettings'])->name('debit-notes.api.company-settings');
    Route::get('/debit-notes/api/bank-accounts', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getBankAccounts'])->name('debit-notes.api.bank-accounts');
    Route::get('/debit-notes/api/signatures', [\App\Http\Controllers\Admin\DebitNoteController::class, 'getSignatures'])->name('debit-notes.api.signatures');

    // Purchase Orders
    Route::resource('purchase-orders', \App\Http\Controllers\Admin\PurchaseOrderController::class);
    Route::get('/purchase-orders/api/companies', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getCompanies'])->name('purchase-orders.api.companies');
    Route::get('/purchase-orders/api/suppliers', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getSuppliers'])->name('purchase-orders.api.suppliers');
    Route::get('/purchase-orders/api/products', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getProducts'])->name('purchase-orders.api.products');
    Route::get('/purchase-orders/api/company-settings', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getCompanySettings'])->name('purchase-orders.api.company-settings');
    Route::get('/purchase-orders/api/bank-accounts', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getBankAccounts'])->name('purchase-orders.api.bank-accounts');
    Route::get('/purchase-orders/api/signatures', [\App\Http\Controllers\Admin\PurchaseOrderController::class, 'getSignatures'])->name('purchase-orders.api.signatures');

    // Petty Cash
    Route::prefix('petty-cash')->name('petty-cash.')->group(function () {
        Route::get('/', [\App\Http\Controllers\Admin\PettyCashController::class, 'index'])->name('index');
        Route::post('/', [\App\Http\Controllers\Admin\PettyCashController::class, 'store'])->name('store');
        Route::put('/{id}', [\App\Http\Controllers\Admin\PettyCashController::class, 'update'])->name('update');
        Route::delete('/{id}', [\App\Http\Controllers\Admin\PettyCashController::class, 'destroy'])->name('destroy');
        Route::post('/return', [\App\Http\Controllers\Admin\PettyCashController::class, 'return'])->name('return');
        Route::post('/top-up', [\App\Http\Controllers\Admin\PettyCashController::class, 'topUp'])->name('top-up');
    });

    // Reports
    Route::prefix('reports')->name('reports.')->group(function () {
        // Transaction Reports
        Route::prefix('transactions')->name('transactions.')->group(function () {
            Route::get('/sales', [\App\Http\Controllers\Admin\TransactionReportController::class, 'sales'])->name('sales');
            Route::get('/sales/api', [\App\Http\Controllers\Admin\TransactionReportController::class, 'getSalesData'])->name('sales.api');
            Route::get('/sales/returns/api', [\App\Http\Controllers\Admin\TransactionReportController::class, 'getSalesReturnsData'])->name('sales.returns.api');
            Route::get('/sales/export/csv', [\App\Http\Controllers\Admin\TransactionReportController::class, 'exportSalesCsv'])->name('sales.export.csv');
            Route::get('/sales/export/pdf', [\App\Http\Controllers\Admin\TransactionReportController::class, 'exportSalesPdf'])->name('sales.export.pdf');
            Route::get('/purchase', [\App\Http\Controllers\Admin\TransactionReportController::class, 'purchase'])->name('purchase');
            Route::get('/quotation', [\App\Http\Controllers\Admin\TransactionReportController::class, 'quotation'])->name('quotation');
        });

        // Accounting Reports
        Route::get('/accounting', [\App\Http\Controllers\Admin\AccountingReportController::class, 'index'])->name('accounting.index');
        Route::get('/accounting/income/api', [\App\Http\Controllers\Admin\AccountingReportController::class, 'getIncomeData'])->name('accounting.income.api');
        Route::get('/accounting/expense/api', [\App\Http\Controllers\Admin\AccountingReportController::class, 'getExpenseData'])->name('accounting.expense.api');
        Route::get('/accounting/income/export/csv', [\App\Http\Controllers\Admin\AccountingReportController::class, 'exportIncomeCsv'])->name('accounting.income.export.csv');
        Route::get('/accounting/income/export/pdf', [\App\Http\Controllers\Admin\AccountingReportController::class, 'exportIncomePdf'])->name('accounting.income.export.pdf');
        Route::get('/accounting/expense/export/csv', [\App\Http\Controllers\Admin\AccountingReportController::class, 'exportExpenseCsv'])->name('accounting.expense.export.csv');
        Route::get('/accounting/expense/export/pdf', [\App\Http\Controllers\Admin\AccountingReportController::class, 'exportExpensePdf'])->name('accounting.expense.export.pdf');

        // Inventory Reports
        Route::get('/inventory', [\App\Http\Controllers\Admin\InventoryReportController::class, 'index'])->name('inventory.index');
        Route::get('/inventory/api', [\App\Http\Controllers\Admin\InventoryReportController::class, 'getInventoryData'])->name('inventory.api');
        Route::get('/inventory/export/csv', [\App\Http\Controllers\Admin\InventoryReportController::class, 'exportInventoryCsv'])->name('inventory.export.csv');
        Route::get('/inventory/export/pdf', [\App\Http\Controllers\Admin\InventoryReportController::class, 'exportInventoryPdf'])->name('inventory.export.pdf');

        Route::get('/reminder-logs', [\App\Http\Controllers\Admin\ReminderLogController::class, 'index'])
            ->middleware('permission:view_reminder_logs')
            ->name('reminder-logs.index');
    });

    // Accounting
    Route::prefix('accounting')->name('accounting.')->group(function () {
        // Chart of Accounts
        Route::resource('chart-of-accounts', \App\Http\Controllers\Admin\ChartOfAccountController::class);

        // Journal Entries
        Route::resource('journal-entries', \App\Http\Controllers\Admin\JournalEntryController::class);

        // Income
        Route::resource('income', \App\Http\Controllers\Admin\IncomeController::class);

        // Expenses
        Route::resource('expenses', \App\Http\Controllers\Admin\AccountingExpenseController::class);

        // Reports
        Route::prefix('reports')->name('reports.')->group(function () {
            Route::get('/trial-balance', [\App\Http\Controllers\Admin\AccountingReportController::class, 'trialBalance'])->name('trial-balance');
            Route::get('/profit-loss', [\App\Http\Controllers\Admin\AccountingReportController::class, 'profitLoss'])->name('profit-loss');
            Route::get('/tax-report', [\App\Http\Controllers\Admin\AccountingReportController::class, 'taxReport'])->name('tax-report');
        });
    });

    // Settings
    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/', function () {
            return redirect()->route('admin.settings.general');
        })->name('index');

        Route::get('/general', [\App\Http\Controllers\Admin\SettingsController::class, 'general'])->name('general');
        Route::post('/company/update', [\App\Http\Controllers\Admin\SettingsController::class, 'updateCompany'])->name('company.update');
        Route::post('/localization/update', [\App\Http\Controllers\Admin\SettingsController::class, 'updateLocalization'])->name('localization.update');
        Route::post('/change-language', [\App\Http\Controllers\Admin\SettingsController::class, 'changeLanguage'])->name('change-language');
        Route::post('/dark-mode', [\App\Http\Controllers\Admin\SettingsController::class, 'updateDarkMode'])->name('dark-mode');

        // Signatures routes
        Route::get('/signatures', function () {
            return redirect()->route('admin.settings.general', ['tab' => 'signatures']);
        })->name('signatures.index');
        Route::get('/signatures/search', [\App\Http\Controllers\Admin\SettingsController::class, 'searchSignatures'])->name('signatures.search');
        Route::post('/signatures', [\App\Http\Controllers\Admin\SettingsController::class, 'storeSignature'])->name('signatures.store');
        Route::put('/signatures/{signature}', [\App\Http\Controllers\Admin\SettingsController::class, 'updateSignature'])->name('signatures.update');
        Route::patch('/signatures/{signature}/status', [\App\Http\Controllers\Admin\SettingsController::class, 'updateSignatureStatus'])->name('signatures.update-status');
        Route::delete('/signatures/{signature}', [\App\Http\Controllers\Admin\SettingsController::class, 'deleteSignature'])->name('signatures.destroy');

        Route::get('/system', [\App\Http\Controllers\Admin\SettingsController::class, 'system'])->name('system');
        Route::get('/finance', [\App\Http\Controllers\Admin\SettingsController::class, 'finance'])->name('finance');

        // Currencies
        Route::post('/currencies', [\App\Http\Controllers\Admin\SettingsController::class, 'storeCurrency'])->name('currencies.store');
        Route::get('/currencies/api', [\App\Http\Controllers\Admin\SettingsController::class, 'getCurrenciesData'])->name('currencies.api');
        Route::put('/currencies/{currency}', [\App\Http\Controllers\Admin\SettingsController::class, 'updateCurrency'])->name('currencies.update');
        Route::patch('/currencies/{currency}/status', [\App\Http\Controllers\Admin\SettingsController::class, 'updateCurrencyStatus'])->name('currencies.update-status');
        Route::post('/currencies/{currency}/set-default', [\App\Http\Controllers\Admin\SettingsController::class, 'setDefaultCurrency'])->name('currencies.set-default');
        Route::delete('/currencies/{currency}', [\App\Http\Controllers\Admin\SettingsController::class, 'deleteCurrency'])->name('currencies.destroy');
        Route::get('/currencies/export', [\App\Http\Controllers\Admin\SettingsController::class, 'exportCurrenciesCsv'])->name('currencies.export');

        // Tax Groups
        Route::get('/tax-groups/api', [\App\Http\Controllers\Admin\SettingsController::class, 'getTaxGroupsData'])->name('tax-groups.api');
        Route::post('/tax-groups', [\App\Http\Controllers\Admin\SettingsController::class, 'storeTaxGroup'])->name('tax-groups.store');
        Route::put('/tax-groups/{taxGroup}', [\App\Http\Controllers\Admin\SettingsController::class, 'updateTaxGroup'])->name('tax-groups.update');
        Route::patch('/tax-groups/{taxGroup}/status', [\App\Http\Controllers\Admin\SettingsController::class, 'updateTaxGroupStatus'])->name('tax-groups.update-status');
        Route::delete('/tax-groups/{taxGroup}', [\App\Http\Controllers\Admin\SettingsController::class, 'deleteTaxGroup'])->name('tax-groups.destroy');
        Route::get('/tax-groups/export', [\App\Http\Controllers\Admin\SettingsController::class, 'exportTaxGroupsCsv'])->name('tax-groups.export');

        // Payment Gateways
        Route::put('/payment-gateways/{gateway}', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePaymentGateway'])->name('payment-gateways.update');
        Route::patch('/payment-gateways/{gateway}/status', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePaymentGatewayStatus'])->name('payment-gateways.update-status');
        Route::post('/payment-gateways/{gateway}/test', [\App\Http\Controllers\Admin\SettingsController::class, 'testPaymentGateway'])->name('payment-gateways.test');

        Route::post('/bank-account', [\App\Http\Controllers\Admin\SettingsController::class, 'storeBankAccount'])->name('bank-account.store');
        Route::put('/bank-account/{id}', [\App\Http\Controllers\Admin\SettingsController::class, 'updateBankAccount'])->name('bank-account.update');
        Route::post('/bank-account/{id}/set-default', [\App\Http\Controllers\Admin\SettingsController::class, 'setDefaultBankAccount'])->name('bank-account.set-default');
        Route::delete('/bank-account/{id}', [\App\Http\Controllers\Admin\SettingsController::class, 'destroyBankAccount'])->name('bank-account.destroy');

        // Tax Rates
        Route::get('/tax-rates', [\App\Http\Controllers\Admin\SettingsController::class, 'getTaxRates'])->name('tax-rates.index');
        Route::post('/tax-rates', [\App\Http\Controllers\Admin\SettingsController::class, 'storeTaxRate'])->name('tax-rates.store');
        Route::get('/modules', [\App\Http\Controllers\Admin\SettingsController::class, 'modules'])->name('modules');
        Route::post('/invoice-settings', [\App\Http\Controllers\Admin\SettingsController::class, 'updateInvoiceSettings'])->name('invoice-settings.update');
        Route::post('/quotation-settings', [\App\Http\Controllers\Admin\SettingsController::class, 'updateQuotationSettings'])->name('quotation-settings.update');
        Route::post('/purchase-settings', [\App\Http\Controllers\Admin\SettingsController::class, 'updatePurchaseSettings'])->name('purchase-settings.update');
        Route::get('/check-updates', [\App\Http\Controllers\Admin\SettingsController::class, 'checkUpdates'])->name('check-updates');

        // Roles & Permissions (View only - roles are seeded and protected)
        Route::get('/roles', [\App\Http\Controllers\Admin\RoleController::class, 'index'])->name('roles');

        // Users
        Route::get('/users', [\App\Http\Controllers\Admin\SettingsController::class, 'users'])->name('users');
        Route::get('/users/api', [\App\Http\Controllers\Admin\SettingsController::class, 'getUsersData'])->name('users.api');
        Route::get('/users/create', [\App\Http\Controllers\Admin\SettingsController::class, 'createUser'])->name('users.create');
        Route::post('/users', [\App\Http\Controllers\Admin\SettingsController::class, 'storeUser'])->name('users.store');
        Route::get('/users/{user}/edit', [\App\Http\Controllers\Admin\SettingsController::class, 'editUser'])->name('users.edit');
        Route::put('/users/{user}', [\App\Http\Controllers\Admin\SettingsController::class, 'updateUser'])->name('users.update');
        Route::delete('/users/{user}', [\App\Http\Controllers\Admin\SettingsController::class, 'deleteUser'])->name('users.destroy');

        // Email Settings
        Route::get('/email', [\App\Http\Controllers\Admin\SettingsController::class, 'email'])->name('email');
        Route::post('/email', [\App\Http\Controllers\Admin\SettingsController::class, 'updateEmail'])->name('email.update');
        Route::post('/email/test', [\App\Http\Controllers\Admin\SettingsController::class, 'testEmail'])->name('email.test');

        // SMS Settings
        Route::get('/sms', [\App\Http\Controllers\Admin\SettingsController::class, 'sms'])->name('sms');
        Route::post('/sms', [\App\Http\Controllers\Admin\SettingsController::class, 'updateSms'])->name('sms.update');
        Route::post('/sms/test', [\App\Http\Controllers\Admin\SettingsController::class, 'testSms'])->name('sms.test');

        // WhatsApp Settings
        Route::get('/whatsapp', [\App\Http\Controllers\Admin\SettingsController::class, 'whatsapp'])->name('whatsapp');
        Route::post('/whatsapp', [\App\Http\Controllers\Admin\SettingsController::class, 'updateWhatsApp'])->name('whatsapp.update');
        Route::post('/whatsapp/test', [\App\Http\Controllers\Admin\SettingsController::class, 'testWhatsApp'])->name('whatsapp.test');

        // Signatures
        Route::get('/signatures/create', [\App\Http\Controllers\Admin\SettingsController::class, 'createSignature'])->name('signatures.create');
        Route::post('/signatures', [\App\Http\Controllers\Admin\SettingsController::class, 'storeSignature'])->name('signatures.store');
    });

    // Addons
    Route::get('/addons', function () {
        return view('admin.addons.index');
    })->name('addons.index');

    // License
    Route::get('/license', function () {
        return view('admin.license.index');
    })->name('license.index');

    // Updates
    Route::prefix('updates')->name('updates.')->group(function () {
        Route::get('/', function () {
            return view('admin.updates.index');
        })->name('index');
        Route::get('/{update}', function ($update) {
            return view('admin.updates.show', ['update' => $update]);
        })->name('show');
    });
});

// Public Invoice Routes (no authentication required)
Route::get('/invoice/{token}', [\App\Http\Controllers\PublicInvoiceController::class, 'show'])->name('invoice.public');
Route::post('/invoice/{token}/pay', [\App\Http\Controllers\PublicInvoiceController::class, 'processPayment'])->name('invoice.public.pay');

// Public quotation (share link)
Route::get('/quotation/{token}', [\App\Http\Controllers\PublicQuotationController::class, 'show'])->name('quotation.public');

// Public payment receipt (share link)
Route::get('/receipt/{token}', [\App\Http\Controllers\PublicReceiptController::class, 'show'])->name('receipt.public');

require __DIR__.'/auth.php';
require __DIR__.'/installer.php';
