<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AccountingController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LoanController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\ClientGroupController;
use App\Http\Controllers\SavingsAccountController;
use App\Http\Controllers\ProcessingController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\AdminstrationController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TransactionController;
use App\Http\Controllers\MaintananceCOAController;
use App\Http\Controllers\TwilioWebhookController;
use App\Http\Controllers\SmsTestController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\AccountTypeController;
use App\Http\Controllers\CompanySettingsController;

// Redirect root to dashboard
Route::get('/', function () {
    return redirect()->route('dashboard');
});

// Authenticated Routes - All authenticated users have access
Route::middleware(['auth'])->group(function () {

    // Logout
    Route::post('/logout', [LoginController::class, 'logout'])->name('logout');

    // Dashboard - All authenticated users
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/data', [DashboardController::class, 'getDashboardData'])->name('dashboard.data');

    // Profile - All authenticated users
    Route::get('/profile', [ProfileController::class, 'show'])->name('profile');
    Route::get('/profile/settings', [ProfileController::class, 'settings'])->name('profile.settings');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::patch('/profile/password', [ProfileController::class, 'updatePassword'])->name('profile.password');

    // ========== USER MANAGEMENT ROUTES ==========
    // All authenticated users
    Route::get('/users', [UserController::class, 'index'])->name('users.index');
    Route::get('/users/create', [UserController::class, 'create'])->name('users.create');
    Route::post('/users', [UserController::class, 'store'])->name('users.store');
    Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('users.edit');
    Route::put('/users/{user}', [UserController::class, 'update'])->name('users.update');
    Route::delete('/users/{user}', [UserController::class, 'destroy'])->name('users.destroy');

    // Permissions Management
    Route::get('/permissions', [AdminstrationController::class, 'permissionsIndex'])->name('permissions.index');
    Route::get('/permissions/create', [AdminstrationController::class, 'permissionsCreate'])->name('permissions.create');
    Route::post('/permissions', [AdminstrationController::class, 'permissionsStore'])->name('permissions.store');
    Route::get('/permissions/{permission}/edit', [AdminstrationController::class, 'permissionsEdit'])->name('permissions.edit');
    Route::put('/permissions/{permission}', [AdminstrationController::class, 'permissionsUpdate'])->name('permissions.update');
    Route::delete('/permissions/{permission}', [AdminstrationController::class, 'permissionsDestroy'])->name('permissions.destroy');
    Route::post('/permissions/assign', [AdminstrationController::class, 'permissionsAssign'])->name('permissions.assign');
    Route::get('/permissions/user/{user}', [AdminstrationController::class, 'userPermissions'])->name('permissions.user');

    // ========== DEPARTMENT MANAGEMENT ROUTES ==========
    Route::prefix('departments')->name('departments.')->group(function () {
        Route::get('/create', [AccountingController::class, 'departmentCreate'])->name('create');
        Route::post('/store', [AccountingController::class, 'departmentStore'])->name('store');
        Route::post('/edit', [AccountingController::class, 'departmentEdit'])->name('edit');
        Route::get('/delete/{id}', [AccountingController::class, 'departmentDelete'])->name('delete');
    });

    // ========== CLIENT MANAGEMENT ROUTES ==========
    // All authenticated users
    // Non-parameter routes must come BEFORE resource routes
    Route::get('/clients/edit-delete', [ClientController::class, 'editDelete'])->name('clients.edit-delete');
    Route::get('clients/kyc', [ClientController::class, 'kyc'])->name('clients.kyc');
    Route::get('/clients/print-all', [ClientController::class, 'printAll'])->name('clients.print-all');
    Route::get('/clients/download-all', [ClientController::class, 'downloadAll'])->name('clients.download-all');
    Route::get('/clients/{client}/print', [ClientController::class, 'printSingle'])->name('clients.print-single');
    Route::get('/clients/{client}/download', [ClientController::class, 'downloadSingle'])->name('clients.download-single');
    Route::resource('clients', ClientController::class);
    Route::resource('client-groups', ClientGroupController::class);
    Route::get('/client-groups/print-all', [ClientGroupController::class, 'printAll'])->name('client-groups.print-all');
    Route::get('/client-groups/download-all', [ClientGroupController::class, 'downloadAll'])->name('client-groups.download-all');
    Route::get('/client-groups/{clientGroup}/print', [ClientGroupController::class, 'printSingle'])->name('client-groups.print-single');
    Route::get('/client-groups/{clientGroup}/download', [ClientGroupController::class, 'downloadSingle'])->name('client-groups.download-single');
    Route::get('clients/{client}/kyc', [ClientController::class, 'showKyc'])->name('clients.show.kyc');
    Route::post('clients/{client}/kyc', [ClientController::class, 'storeKyc'])->name('clients.kyc.store');

    // Client Group Members Management
    Route::get('client-groups/{clientGroup}/members', [ClientGroupController::class, 'members'])->name('client-groups.members');
    Route::post('client-groups/{clientGroup}/members', [ClientGroupController::class, 'addMember'])->name('client-groups.members.add');
    Route::delete('client-groups/{clientGroup}/members/{client}', [ClientGroupController::class, 'removeMember'])->name('client-groups.members.remove');

    // ========== LOAN MANAGEMENT ROUTES ==========
    // All authenticated users
    // Non-parameter routes must come BEFORE resource routes
    Route::get('/loans/edit-delete', [LoanController::class, 'editDelete'])->name('loans.edit-delete');
    Route::get('/loans/group/create', [LoanController::class, 'createGroup'])->name('loans.group.create');
    Route::post('/loans/group', [LoanController::class, 'storeGroup'])->name('loans.group.store');
    Route::get('/loans/pending', [LoanController::class, 'pending'])->name('loans.pending');
    Route::get('/loans/approved', [LoanController::class, 'approved'])->name('loans.approved');
    Route::get('/loans/pending/export-csv', [LoanController::class, 'exportPendingCsv'])->name('loans.pending.export-csv');
    Route::get('/loans/pending/export-pdf', [LoanController::class, 'exportPendingPdf'])->name('loans.pending.export-pdf');
    Route::get('/loans/print-all', [LoanController::class, 'printAll'])->name('loans.print-all');
    Route::get('/loans/{loan}/print', [LoanController::class, 'printSingle'])->name('loans.print-single');
    Route::get('/loans/download-all', [LoanController::class, 'downloadAll'])->name('loans.download-all');
    Route::get('/loans/{loan}/download', [LoanController::class, 'downloadSingle'])->name('loans.download-single');
    Route::get('/loan-products', [LoanController::class, 'products'])->name('loan.products');
    Route::get('/loan-repayments', [LoanController::class, 'repayments'])->name('loan.repayments.index');
    Route::resource('loans', LoanController::class);

    // Loan Action Routes
    Route::get('/loans/{loan}/wait', [LoanController::class, 'showWaitForm'])->name('loans.wait');
    Route::post('/loans/{loan}/wait', [LoanController::class, 'wait'])->name('loans.wait.store');
    Route::post('/loans/{loan}/approve', [LoanController::class, 'approve'])->name('loans.approve');
    Route::post('/loans/{loan}/reject', [LoanController::class, 'reject'])->name('loans.reject');
    Route::post('/loans/bulk-approve', [LoanController::class, 'bulkApprove'])->name('loans.bulk-approve');
    Route::post('/loans/bulk-reject', [LoanController::class, 'bulkReject'])->name('loans.bulk-reject');
    Route::post('/loans/{loan}/disburse', [LoanController::class, 'disburse'])->name('loans.disburse');
    Route::put('/loans/{loan}/pause', [LoanController::class, 'pause'])->name('loans.pause');
    Route::put('/loans/{loan}/close', [LoanController::class, 'close'])->name('loans.close');
    Route::put('/loans/{loan}/resume', [LoanController::class, 'resume'])->name('loans.resume');

    // Enhanced Repayment Routes
    Route::get('/loans/{loan}/repayments/create', [LoanController::class, 'createRepayment'])->name('loans.repayments.create');
    Route::post('/loans/{loan}/repayments', [LoanController::class, 'storeRepayment'])->name('loans.repayments.store');
    Route::get('/loans/{loan}/repayment-schedule', [LoanController::class, 'repaymentSchedule'])->name('loans.repayment-schedule');
    Route::get('/loan-repayments', [LoanController::class, 'repayments'])->name('loan.repayments.index');

    // Rescheduling Routes
    Route::get('/loans/{loan}/reschedule', [LoanController::class, 'createReschedule'])->name('loans.reschedule.create');
    Route::post('/loans/{loan}/reschedule', [LoanController::class, 'storeReschedule'])->name('loans.reschedule.store');
    Route::get('/loan-reschedules', [LoanController::class, 'reschedules'])->name('loans.reschedules.index');
    Route::post('/loan-reschedules/{reschedule}/approve', [LoanController::class, 'approveReschedule'])->name('loans.reschedules.approve');
    Route::post('/loan-reschedules/{reschedule}/reject', [LoanController::class, 'rejectReschedule'])->name('loans.reschedules.reject');

    // ========== SAVINGS MANAGEMENT ROUTES ==========
    // All authenticated users
    Route::prefix('savings')->name('savings.')->group(function () {
        // Non-parameter routes must come BEFORE parameterized routes
        Route::get('/accounts/edit-delete', [SavingsAccountController::class, 'editDelete'])->name('accounts.edit-delete');
        Route::get('/accounts', [SavingsAccountController::class, 'index'])->name('accounts.index');
        Route::get('/accounts/create', [SavingsAccountController::class, 'create'])->name('accounts.create');
        Route::post('/accounts', [SavingsAccountController::class, 'store'])->name('accounts.store');
        // Static report/download routes must be declared before the parameterized account routes
        Route::get('/accounts/print-all', [SavingsAccountController::class, 'printAll'])->name('accounts.print-all');
        Route::get('/accounts/download-all', [SavingsAccountController::class, 'downloadAll'])->name('accounts.download-all');
        Route::get('/accounts/{savingsAccount}', [SavingsAccountController::class, 'show'])->name('accounts.show');
        Route::get('/accounts/{savingsAccount}/edit', [SavingsAccountController::class, 'edit'])->name('accounts.edit');
        Route::put('/accounts/{savingsAccount}', [SavingsAccountController::class, 'update'])->name('accounts.update');
        Route::delete('/accounts/{savingsAccount}', [SavingsAccountController::class, 'destroy'])->name('accounts.destroy');
        Route::get('/accounts/{savingsAccount}/print', [SavingsAccountController::class, 'printSingle'])->name('accounts.print-single');
        Route::get('/accounts/{savingsAccount}/download', [SavingsAccountController::class, 'downloadSingle'])->name('accounts.download-single');
        Route::get('/accounts/{savingsAccount}/deposit', [SavingsAccountController::class, 'showDepositForm'])->name('accounts.deposit.form');
        Route::post('/accounts/{savingsAccount}/deposit', [SavingsAccountController::class, 'deposit'])->name('accounts.deposit');
        Route::get('/accounts/{savingsAccount}/withdraw', [SavingsAccountController::class, 'showWithdrawForm'])->name('accounts.withdraw.form');
        Route::post('/accounts/{savingsAccount}/withdraw', [SavingsAccountController::class, 'withdraw'])->name('accounts.withdraw');
        Route::get('/interest', [SavingsAccountController::class, 'interest'])->name('interest');
        Route::get('/deposits', [SavingsAccountController::class, 'deposits'])->name('deposits');
        Route::get('/deposits/create', [SavingsAccountController::class, 'showDepositForm'])->name('deposits.create');
        Route::get('/deposits/print-all', [SavingsAccountController::class, 'printDeposits'])->name('deposits.print-all');
        Route::get('/deposits/download-all', [SavingsAccountController::class, 'downloadDeposits'])->name('deposits.download-all');
        Route::get('/deposits/{deposit}/print', [SavingsAccountController::class, 'printSingleDeposit'])->name('deposits.print-single');
        Route::get('/deposits/{deposit}/download', [SavingsAccountController::class, 'downloadSingleDeposit'])->name('deposits.download-single');
        Route::get('/withdrawals', [SavingsAccountController::class, 'withdrawals'])->name('withdrawals');
        Route::get('/withdrawals/create', [SavingsAccountController::class, 'showWithdrawForm'])->name('withdrawals.create');
        Route::get('/withdrawals/print-all', [SavingsAccountController::class, 'printWithdrawals'])->name('withdrawals.print-all');
        Route::get('/withdrawals/download-all', [SavingsAccountController::class, 'downloadWithdrawals'])->name('withdrawals.download-all');
        Route::get('/withdrawals/{withdrawal}/print', [SavingsAccountController::class, 'printSingleWithdrawal'])->name('withdrawals.print-single');
        Route::get('/withdrawals/{withdrawal}/download', [SavingsAccountController::class, 'downloadSingleWithdrawal'])->name('withdrawals.download-single');
        Route::get('/transactions', [SavingsAccountController::class, 'transactions'])->name('transactions');
    });

    // ========== TRANSACTION ROUTES ==========
    // All authenticated users
    Route::resource('transactions', TransactionController::class);
    Route::get('receipts', [TransactionController::class, 'receipts'])->name('receipts.index');
    Route::get('receipts/{receipt}', [TransactionController::class, 'showReceipt'])->name('receipts.show');
    Route::post('receipts', [TransactionController::class, 'storeReceipt'])->name('receipts.store');
    Route::get('payments', [TransactionController::class, 'payments'])->name('payments.index');
    Route::post('payments', [TransactionController::class, 'storePayment'])->name('payments.store');

    // ========== PROCESSING ROUTES ==========
    // All authenticated users
    Route::prefix('processing')->group(function () {
        Route::get('/invoicing', [ProcessingController::class, 'invoicing'])->name('processing.invoicing.index');
        Route::post('/invoicing', [ProcessingController::class, 'storeInvoice'])->name('processing.invoicing.store');
        Route::get('/receipts', [ProcessingController::class, 'receipts'])->name('processing.receipts.index');
        Route::get('/payments', [ProcessingController::class, 'payments'])->name('processing.payments.index');
        Route::get('/transactions', [ProcessingController::class, 'transactions'])->name('processing.transactions.index');
    });

    // ========== REPORTS ROUTES ==========
    // All authenticated users
    Route::prefix('reports')->group(function () {
        Route::get('/financial', [ReportController::class, 'financial'])->name('reports.financial');
        Route::get('/loans', [ReportController::class, 'loans'])->name('reports.loans');
        Route::get('/savings', [ReportController::class, 'savings'])->name('reports.savings');
        Route::get('/statements', [ReportController::class, 'statements'])->name('reports.statements');
        Route::get('/audit', [ReportController::class, 'audit'])->name('reports.audit');
        Route::get('/compliance', [ReportController::class, 'compliance'])->name('reports.compliance');
    });

    // ========== ACCOUNTING ROUTES ==========
    // All authenticated users
    Route::prefix('accounts')->name('accounts.')->group(function () {
        Route::get('/', [AccountingController::class, 'index'])->name('index');

        // Journal Entries
        Route::prefix('journals')->name('journals.')->group(function () {
            Route::get('/', [AccountingController::class, 'journalsIndex'])->name('index');
            Route::get('/create', [AccountingController::class, 'journalsCreate'])->name('create');
            Route::post('/', [AccountingController::class, 'journalsStore'])->name('store');
            Route::put('/', [AccountingController::class, 'journalsUpdate'])->name('update');
            Route::delete('/{id}', [AccountingController::class, 'journalsDelete'])->name('delete');
            Route::post('/process', [AccountingController::class, 'journalsProcess'])->name('process');
            Route::post('/process/{id}', [AccountingController::class, 'journalsProcessSingle'])->name('processSingle');
        });

        // General Journal Temp Entries
        Route::prefix('general-journal')->name('general.journal.')->group(function () {
            Route::post('/', [AccountingController::class, 'generalJournalStore'])->name('store');
            Route::put('/', [AccountingController::class, 'generalJournalUpdate'])->name('update');
            Route::post('/process', [AccountingController::class, 'generalJournalProcess'])->name('process');
            Route::post('/process/{id}', [AccountingController::class, 'generalJournalProcessSingle'])->name('processSingle');
            Route::delete('/delete/{id}', [AccountingController::class, 'generalJournalDelete'])->name('delete');
        });

        // Cash Book
        Route::prefix('cashbook')->name('cashbook.')->group(function () {
            Route::get('/', [AccountingController::class, 'cashbookIndex'])->name('index');
            Route::get('/create', [AccountingController::class, 'cashbookCreate'])->name('create');
            Route::post('/', [AccountingController::class, 'cashbookStore'])->name('store');
            Route::post('/process', [AccountingController::class, 'cashbookProcess'])->name('process');
            Route::post('/process/{id}', [AccountingController::class, 'cashbookProcessSingle'])->name('process-single');
            Route::post('/accounts', [AccountingController::class, 'cashbookAccounts'])->name('accounts');
            Route::post('/references', [AccountingController::class, 'cashbookReferences'])->name('references');
            Route::get('/edit/{id}', [AccountingController::class, 'cashbookEdit'])->name('edit');
            Route::post('/update', [AccountingController::class, 'cashbookUpdate'])->name('update');
            Route::delete('/delete/{id}', [AccountingController::class, 'cashbookDelete'])->name('delete');
        });

        // Invoices
        Route::prefix('invoices')->name('invoices.')->group(function () {
            Route::get('/', [AccountingController::class, 'invoicesIndex'])->name('index');
            Route::get('/create', [AccountingController::class, 'invoicesCreate'])->name('create');
            Route::post('/', [AccountingController::class, 'invoicesStore'])->name('store');
            Route::get('/accounts', [AccountingController::class, 'invoiceAccounts'])->name('invoiceAccounts');
            Route::get('/next-number', [AccountingController::class, 'getNextInvoiceNumber'])->name('getNextNumber');
            Route::get('/{invoice}', [AccountingController::class, 'invoicesShow'])->name('show');
            Route::get('/{invoice}/pdf', [AccountingController::class, 'invoicesPdf'])->name('pdf');
            Route::get('/{invoice}/print', [AccountingController::class, 'invoicesPrint'])->name('print');
            Route::get('/{invoice}/invoice', [AccountingController::class, 'invoicesInvoice'])->name('invoice');
            Route::get('/print-all', [AccountingController::class, 'printAllInvoices'])->name('print-all');
            Route::get('/download-all', [AccountingController::class, 'downloadAllInvoices'])->name('download-all');
        });

        // Receipts
        Route::prefix('receipts')->name('receipts.')->group(function () {
            Route::get('/create', [AccountingController::class, 'receiptsCreate'])->name('create');
        });

        // General Ledger - REORDERED ROUTES
        Route::prefix('general-ledger')->name('general-ledger.')->group(function () {
            Route::get('/', [AccountingController::class, 'generalLedgerIndex'])->name('index');
            Route::get('/create', [AccountingController::class, 'generalLedgerCreate'])->name('create');
            Route::post('/', [AccountingController::class, 'generalLedgerStore'])->name('store');

            // ========== GENERAL LEDGER SUB-ACCOUNT ROUTES ==========
            // These MUST come BEFORE the generic {account} routes

            // Main Sub Account Routes - CORRECT ORDER
            Route::get('/{mainAccount}/main-sub-account/create', [AccountingController::class, 'createMainSubAccount'])
                ->name('createMainSubAccount');

            Route::post('/main-sub-account/store', [AccountingController::class, 'storeMainSubAccount'])
                ->name('main-sub-account.store');
            Route::match(['PUT', 'POST'], '/main-sub-account/{id}', [AccountingController::class, 'editMainSubAccount'])
                ->name('editMainSubAccount');
            Route::delete('/main-sub-account/{id}', [AccountingController::class, 'deleteMainSubAccount'])
                ->name('main-sub-account.delete');
            Route::get('/main-sub-account/add/{mainAccount}', [AccountingController::class, 'addMainSubAccount'])
                ->name('addMainSubAccount');

            // Sub Account 1 Routes
            Route::get('/sub-account1/create/{mainSubAccount}', [AccountingController::class, 'createSubAccount1'])
                ->name('createSubAccount1');
            Route::post('/sub-account1/store', [AccountingController::class, 'storeSubAccount1'])
                ->name('sub.account.1.store'); // Route for storing sub account 1
            Route::post('/sub-account1/edit', [AccountingController::class, 'editSubAccount1'])
                ->name('editSubAccount1');
            Route::post('/sub-account1/delete/{id}', [AccountingController::class, 'deleteSubAccount1'])
                ->name('sub.account.1.delete');
            Route::get('/sub-account1/add/{mainSubAccount}', [AccountingController::class, 'addSubAccount1'])
                ->name('addSubAccount1');

            // Sub Account 2 Routes
            Route::get('/sub-account2/create/{subAccount1}', [AccountingController::class, 'createSubAccount2'])
                ->name('createSubAccount2');
            Route::post('/sub-account2/store', [AccountingController::class, 'storeSubAccount2'])
                ->name('sub.account.2.store');
            Route::post('/sub-account2/edit', [AccountingController::class, 'editSubAccount2'])
                ->name('editSubAccount2');
            Route::delete('/sub-account2/delete/{id}', [AccountingController::class, 'deleteSubAccount2'])
                ->name('sub.account.2.delete');
            Route::get('/sub-account2/add/{subAccount1}', [AccountingController::class, 'addSubAccount2'])
                ->name('addSubAccount2');

            // Sub Account 3 Routes
            Route::get('/sub-account3/create/{subAccount2}', [AccountingController::class, 'createSubAccount3'])
                ->name('createSubAccount3');
            Route::post('/sub-account3/store', [AccountingController::class, 'storeSubAccount3'])
                ->name('sub.account.3.store');
            Route::post('/sub-account3/edit', [AccountingController::class, 'editSubAccount3'])
                ->name('editSubAccount3');
            Route::delete('/sub-account3/delete/{id}', [AccountingController::class, 'deleteSubAccount3'])
                ->name('sub.account.3.delete');
            Route::get('/sub-account3/add/{subAccount2}', [AccountingController::class, 'addSubAccount3'])
                ->name('addSubAccount3');

            // Sub Account 4 Routes
            Route::get('/sub-account4/create/{subAccount3}', [AccountingController::class, 'createSubAccount4'])
                ->name('createSubAccount4');
            Route::post('/sub-account4/store', [AccountingController::class, 'storeSubAccount4'])
                ->name('sub.account.4.store');
            Route::post('/sub-account4/edit', [AccountingController::class, 'editSubAccount4'])
                ->name('editSubAccount4');
            Route::delete('/sub-account4/delete/{id}', [AccountingController::class, 'deleteSubAccount4'])
                ->name('sub.account.4.delete');
            Route::get('/sub-account4/add/{subAccount3}', [AccountingController::class, 'addSubAccount4'])
                ->name('addSubAccount4');

            // Sub Account 5 Routes
            Route::get('/sub-account5/create/{subAccount4}', [AccountingController::class, 'createSubAccount5'])
                ->name('createSubAccount5');
            Route::post('/sub-account5/store', [AccountingController::class, 'storeSubAccount5'])
                ->name('sub.account.5.store');
            Route::post('/sub-account5/edit', [AccountingController::class, 'editSubAccount5'])
                ->name('editSubAccount5');
            Route::delete('/sub-account5/delete/{id}', [AccountingController::class, 'deleteSubAccount5'])
                ->name('sub.account.5.delete');
            Route::get('/sub-account5/add/{subAccount4}', [AccountingController::class, 'addSubAccount5'])
                ->name('addSubAccount5');

            // Generic account routes MUST come AFTER all specific routes
            Route::get('/{mainAccount}/edit', [AccountingController::class, 'generalLedgerEdit'])->name('edit');
            Route::match(['PUT', 'POST'], '/{accountId}', [AccountingController::class, 'generalLedgerUpdate'])->name('update');
            Route::delete('/{mainAccount}', [AccountingController::class, 'generalLedgerDestroy'])->name('destroy');
            Route::get('/{mainAccount}', [AccountingController::class, 'generalLedgerShow'])->name('show');
        });

        // Account Types - CRUD for account types
        Route::prefix('account-types')->name('account-types.')->group(function () {
            Route::get('/create', [AccountTypeController::class, 'index'])->name('create');
        });

        // Legacy Ledger Routes
        Route::get('/ledger', [MaintananceCOAController::class, 'createGL'])->name('ledger.create');
        Route::post('/store/ledger', [MaintananceCOAController::class, 'storeGL'])->name('ledger.store');
        Route::post('/EditMainAccounts', [MaintananceCOAController::class, 'editMainAccount'])->name('editMainAccount');
        Route::delete('/ledger/delete/{id}', [MaintananceCOAController::class, 'deleteMainAccount'])->name('deleteMainAccount');

        // Reports
        Route::prefix('reports')->name('reports.')->group(function () {
            Route::get('/balance-sheet', [AccountingController::class, 'balanceSheet'])->name('balance-sheet');
        });

        // API Routes
        Route::get('/api/accounts', [AccountingController::class, 'getAccounts'])->name('api.accounts');
        Route::get('/api/journals', [AccountingController::class, 'getJournalEntries'])->name('api.journals');
        Route::get('/api/cash-transactions', [AccountingController::class, 'getCashTransactions'])->name('api.cash-transactions');
        Route::get('/api/general-ledger-accounts', [AccountingController::class, 'getGeneralLedgerAccounts'])->name('api.general-ledger-accounts');
    });

    // Account types routes (legacy/flat names used by views)
    Route::get('/account-types', [AccountTypeController::class, 'index'])->name('account_types.index');
    Route::get('/account-types/create', [AccountTypeController::class, 'index'])->name('account_types.create');
    Route::post('/account-types', [AccountTypeController::class, 'store'])->name('account_types.store');
    Route::match(['PUT', 'POST'], '/account-types/{accountType}', [AccountTypeController::class, 'update'])->name('account_types.update');
    Route::delete('/account-types/{accountType}', [AccountTypeController::class, 'destroy'])->name('account_types.delete');
    Route::get('/accounts/account-types/create', [AccountTypeController::class, 'index'])->name('accounts.account-types.create');

    // ========== NOTIFICATION ROUTES ==========
    // All authenticated users
    Route::resource('notifications', NotificationController::class)->only(['index']);
    Route::post('notifications/send', [NotificationController::class, 'sendManualNotification'])->name('notifications.send');

    // ========== ADMINISTRATION ROUTES ==========
    // All authenticated users
    Route::prefix('administration')->group(function () {
        // User Management (Legacy - redirect to new UserController)
        Route::get('/users', function() {
            return redirect()->route('users.index');
        })->name('administration.users');

        Route::get('/roles', [AdminstrationController::class, 'roles'])->name('administration.roles');
        Route::post('/roles', [AdminstrationController::class, 'storeRole'])->name('administration.roles.store');



        Route::get('/settings', [AdminstrationController::class, 'settings'])->name('administration.settings');
        Route::put('/settings', [AdminstrationController::class, 'updateSettings'])->name('administration.settings.update');
        Route::get('/backup', [AdminstrationController::class, 'backup'])->name('administration.backup');
        Route::post('/backup', [AdminstrationController::class, 'createBackup'])->name('administration.backup.create');
    });

    // ========== COMPANY SETTINGS ROUTES ==========
    // All authenticated users
    Route::resource('company-settings', CompanySettingsController::class)->except(['show', 'edit', 'update', 'destroy'])->names([
        'index' => 'company-settings.index',
        'create' => 'company-settings.create',
        'store' => 'company-settings.store',
    ]);

    // Define edit, update and destroy routes separately (since there's only one company settings record)
    Route::get('company-settings/edit', [CompanySettingsController::class, 'edit'])->name('company-settings.edit');
    Route::put('company-settings', [CompanySettingsController::class, 'update'])->name('company-settings.update');
    Route::delete('company-settings', [CompanySettingsController::class, 'destroy'])->name('company-settings.destroy');

    // Legacy User Management route - redirect to new users index
    Route::get('/user-management', function() {
        return redirect()->route('users.index');
    })->name('user-management');

    // Cashbook Entries Routes (Simple CRUD)
    Route::prefix('cashbook')->name('cashbook.')->group(function () {
        Route::get('/entries/create', [\App\Http\Controllers\CashbookEntryController::class, 'createCashbook'])->name('entries.create');
        Route::post('/entries', [\App\Http\Controllers\CashbookEntryController::class, 'storeCashbook'])->name('entries.store');
        Route::post('/entries/edit', [\App\Http\Controllers\CashbookEntryController::class, 'editCashbook'])->name('entries.edit');
        Route::get('/entries/delete/{id}', [\App\Http\Controllers\CashbookEntryController::class, 'deleteCashbook'])->name('entries.delete');
    });

    // ========== LEGACY REDIRECT ROUTES ==========
    Route::get('/edit', function() {
        return redirect()->route('clients.index');
    })->name('edit');

    Route::get('/processing', function() {
        return redirect()->route('invoicing.index');
    })->name('processing');

    // FIXED: Removed named parameter 'uri:'
    Route::get('/administration', function() {
        return redirect()->route('administration.users');
    })->name('administration');

    Route::get('/reports', function() {
        return redirect()->route('reports.financial');
    })->name('reports');
});

// Guest routes - Login and registration
Route::middleware('guest')->group(function () {
    Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [LoginController::class, 'login']);
    Route::get('/register', [LoginController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [LoginController::class, 'register']);

    // Password Reset Routes
    Route::get('/forgot-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'showForgotPasswordForm'])->name('auth.forgotPassword');
    Route::post('/forgot-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'sendOtp'])->name('password.email');
    Route::get('/verify-otp', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'showVerifyOtpForm'])->name('password.verify');
    Route::post('/verify-otp', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'verifyOtp'])->name('password.verify.post');
    Route::get('/reset-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'showResetPasswordForm'])->name('password.reset');
    Route::post('/reset-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'resetPassword'])->name('password.update');
});

// Include auth routes (for email verification)
require __DIR__.'/auth.php';

// Public loan details route (signed URLs for security)
Route::get('/loans/{loan}/public', [LoanController::class, 'showPublic'])
    ->name('loans.public.show')
    ->middleware('signed');

// Twilio webhook for delivery status (public endpoint)
Route::post('/webhooks/twilio/delivery', [TwilioWebhookController::class, 'delivery'])
    ->name('webhooks.twilio.delivery');

// Admin SMS test routes (protected)
Route::get('/sms/test', [SmsTestController::class, 'showTestForm'])->name('sms.test')->middleware('auth');
Route::post('/sms/test', [SmsTestController::class, 'sendTest'])->name('sms.test.send')->middleware('auth');
