<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Controllers\DashboardController;
use App\Controllers\StationController;
use App\Controllers\EmployeeController;
use App\Controllers\LossController;
use App\Controllers\InternetPaymentController;
use App\Controllers\PaymentController;
use App\Controllers\VendorController;
use App\Controllers\VendorCategoryController;
use App\Controllers\UserController;
use App\Controllers\Auth\LoginController;
use App\Controllers\Auth\RegisterController;
use App\Controllers\Auth\ForgotPasswordController;
use App\Controllers\Auth\ResetPasswordController;
use App\Controllers\ReportController;
use App\Controllers\DeductionTransactionController;
use App\Controllers\OrderNumberController;
use App\Controllers\InternetProviderController;
use App\Controllers\NotificationController;
use App\Controllers\PendingApprovalController;
use App\Controllers\EmployeeProfileController;
use App\Controllers\LinkController;
use App\Controllers\Salary\SalaryDashboardController;
use App\Controllers\Salary\SalaryPaymentController;
use App\Controllers\Salary\SalaryDeductionController;
use App\Controllers\Salary\SalaryScheduleController;
use App\Controllers\UserPreferenceController;
use App\Controllers\SuccessRateController;
use App\Controllers\Salary\DismissalController;
use App\Controllers\Salary\SuperDeductionController;
use App\Controllers\Admin\EmployeeDismissalController;
use App\Controllers\Admin\EmployeeImportController;
use App\Controllers\Admin\DismissalDashboardController;
use App\Controllers\ServiceProviderController;
use App\Controllers\MpesaController;

    // No Auth Required

    Route::resource('order-numbers', OrderNumberController::class);

    Route::get('/', function () {
        return view('welcome');
    });

    // Authentication
    Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [LoginController::class, 'login'])->middleware('throttle:5,1');

    Route::get('/register', [RegisterController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [RegisterController::class, 'register'])->middleware('throttle:5,1');

    Route::get('/password/reset', [ForgotPasswordController::class, 'showLinkRequestForm'])->name('password.request');
    Route::post('/password/email', [ForgotPasswordController::class, 'sendResetLinkEmail'])->name('password.email');
    Route::get('/password/reset/{token}', [ResetPasswordController::class, 'showResetForm'])->name('password.reset');
    Route::post('/password/reset', [ResetPasswordController::class, 'reset'])->name('password.update');

    Route::post('/logout', function () {
        Auth::logout();
        return redirect('/login')->with('status', 'You have been logged out.');
    })->name('logout');

    // Cookie Consent 
    Route::prefix('cookie')->name('cookie.')->group(function () {
        Route::get('/consent', function () {
            return view('cookie-consent');
        })->name('consent');
        
        Route::post('/accept', function () {
            return response()->json(['message' => 'Cookie consent accepted'])->cookie('cookie_consent', 'accepted', 60 * 24 * 30);
        })->name('accept');
        
        Route::post('/reject', function () {
            return response()->json(['message' => 'Cookie consent rejected'])->cookie('cookie_consent', 'rejected', 60 * 24 * 30);
        })->name('reject');
    });

    // Health Check
    Route::get('/health', function () {
        return response()->json([
            'status' => 'operational',
            'service' => 'Link Manager',
            'timestamp' => now()->toIso8601String(),
            'gdpr_compliant' => true
        ]);
    })->name('health.check');

    // AUTHENTICATED

    Route::middleware(['auth'])->group(function () {
        
        // Dashboard
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
        Route::get('/sidebar', [DashboardController::class, 'sidebar']);
        
        // EMPLOYEE PROFILE 
        Route::prefix('employee-profile')->name('employees_profile.')->group(function () {
            Route::get('/', [EmployeeProfileController::class, 'index'])->name('index');
            Route::get('/create', [EmployeeProfileController::class, 'create'])->name('create');
            Route::post('/', [EmployeeProfileController::class, 'store'])->name('store');
            Route::get('/{employee}', [EmployeeProfileController::class, 'show'])->name('show');
            Route::get('/{employee}/edit', [EmployeeProfileController::class, 'edit'])->name('edit');
            Route::put('/{employee}', [EmployeeProfileController::class, 'update'])->name('update');
            Route::delete('/{employee}', [EmployeeProfileController::class, 'destroy'])->name('destroy');
        });
        
        Route::post('/employees-profile/{employee}/qualifications', [EmployeeProfileController::class, 'addQualification'])->name('employees.add-qualification');
        Route::patch('/employees-profile/{employee}/terminate', [EmployeeProfileController::class, 'terminate'])->name('employees.terminate');
        Route::get('/documents/{document}/download', [EmployeeProfileController::class, 'downloadDocument'])->name('employees.download');
        Route::get('/documents/{document}/view', [EmployeeProfileController::class, 'viewDocument'])->name('employees.view');
        Route::get('/employees/{employee}/change-history', [EmployeeProfileController::class, 'changeHistory'])->name('employee.change_history');
        Route::post('/employee-change-logs/{changeLog}/approve', [EmployeeProfileController::class, 'approveChange'])->name('employee_profile.approve_change')->middleware('can:approve,changeLog');
        Route::post('/employee-change-logs/{changeLog}/reject', [EmployeeProfileController::class, 'rejectChange'])->name('employee_profile.reject_change')->middleware('can:approve,changeLog');
        
        // SALARY MANAGEMENT
        Route::prefix('salary')->name('salary.')->group(function () {
            
            Route::get('/', [SalaryDashboardController::class, 'index'])->name('dashboard');
            
            // Payments
            Route::get('/payments', [SalaryPaymentController::class, 'index'])->name('payments.index');
            Route::get('/payments/create', [SalaryPaymentController::class, 'create'])->name('payments.create');
            Route::post('/payments', [SalaryPaymentController::class, 'store'])->name('payments.store');
            Route::get('/payments/{payment}', [SalaryPaymentController::class, 'show'])->name('payments.show');
            Route::post('/payments/{payment}/approve', [SalaryPaymentController::class, 'approve'])->name('payments.approve');
            Route::delete('/payments/{id}', [SalaryPaymentController::class, 'destroy'])->name('payments.destroy');
            Route::get('/payments/preview/{employeeId}', [SalaryPaymentController::class, 'preview'])->name('payments.preview');
            Route::get('/payments/approval-info', [SalaryPaymentController::class, 'approvalInfo'])->name('payments.approval-info');
            Route::get('/payments/payable/{id}', [SalaryPaymentController::class, 'showPayableAmount'])->name('payments.show-payable');
            Route::post('/payments/confirm/{id}', [SalaryPaymentController::class, 'confirmPayment'])->name('payments.confirm');
            Route::post('/payments/preview-deduction', [SalaryPaymentController::class, 'previewDeduction'])->name('payments.preview-deduction');
            Route::get('/payments/receipt/{id}', [SalaryPaymentController::class, 'generateReceipt'])->name('payments.receipt');
            Route::get('/payments/{payment}/print', [SalaryPaymentController::class, 'print'])->name('payments.print');
            Route::post('/payments/process-with-deduction', [SalaryPaymentController::class, 'processPaymentWithDeduction'])->name('payments.process-with-deduction');
            Route::post('/payments/{id}/reject', [SalaryPaymentController::class, 'reject'])->name('payments.reject');
            
            // History
            Route::get('/history', [SalaryPaymentController::class, 'history'])->name('history');
            Route::get('/history/chart-data', [SalaryPaymentController::class, 'chartData'])->name('history.chart');
            Route::post('/history/clear', [SalaryPaymentController::class, 'clearHistory'])->name('history.clear');
            
            // Deductions
            Route::get('/deductions', [SalaryDeductionController::class, 'index'])->name('deductions.index');
            Route::get('/deductions/create', [SalaryDeductionController::class, 'create'])->name('deductions.create');
            Route::post('/deductions', [SalaryDeductionController::class, 'store'])->name('deductions.store');
            Route::get('/deductions/{id}', [SalaryDeductionController::class, 'show'])->name('deductions.show');
            Route::post('/deductions/{deduction}/approve', [SalaryDeductionController::class, 'approve'])->name('deductions.approve');
            Route::post('/deductions/{deduction}/cancel', [SalaryDeductionController::class, 'cancel'])->name('deductions.cancel');
            Route::post('/deductions/{id}/reject', [SalaryDeductionController::class, 'reject'])->name('deductions.reject');
            Route::get('/deductions/employee-summary/{employeeId}', [SalaryDeductionController::class, 'getEmployeeSummary'])->name('deductions.employee-summary');
            Route::get('/deductions/pending-for-payment/{employeeId}', [SalaryDeductionController::class, 'getPendingForPayment'])->name('deductions.pending-for-payment');
            Route::get('/deductions/employee/{employeeId}/pending', [SalaryDeductionController::class, 'getEmployeePendingDeductions'])->name('deductions.employee-pending');
            Route::post('/deductions/bulk-approve', [SalaryDeductionController::class, 'bulkApprove'])->name('deductions.bulk-approve');
            Route::get('/deductions/export', [SalaryDeductionController::class, 'export'])->name('deductions.export');
            Route::get('/deductions/summary', [SalaryDeductionController::class, 'getSummary'])->name('deductions.summary');
            Route::post('/deductions/{deductionId}/process-dismissal', [SalaryPaymentController::class, 'processDismissal'])->name('deductions.process-dismissal');
            Route::get('/deductions/can-add/{employeeId}/{amount}', function($employeeId, $amount) {
                $service = app(\App\Services\Salary\DeductionRuleService::class);
                return response()->json($service->canAddDeduction($employeeId, $amount));
            })->name('deductions.can-add');
            
            // Schedules
            Route::get('/schedules', [SalaryScheduleController::class, 'index'])->name('schedules.index');
            Route::get('/schedules/create', [SalaryScheduleController::class, 'create'])->name('schedules.create');
            Route::post('/schedules', [SalaryScheduleController::class, 'store'])->name('schedules.store');
            Route::get('/schedules/{schedule}/edit', [SalaryScheduleController::class, 'edit'])->name('schedules.edit');
            Route::put('/schedules/{schedule}', [SalaryScheduleController::class, 'update'])->name('schedules.update');
            Route::delete('/schedules/{schedule}', [SalaryScheduleController::class, 'destroy'])->name('schedules.destroy');
            Route::post('/schedules/{schedule}/approve', [SalaryScheduleController::class, 'approve'])->name('schedules.approve');
            Route::post('/schedules/{schedule}/reject', [SalaryScheduleController::class, 'reject'])->name('schedules.reject');
            Route::post('/schedules/{schedule}/process', [SalaryScheduleController::class, 'processNow'])->name('schedules.process');
            Route::post('/schedules/bulk-approve', [SalaryScheduleController::class, 'bulkApprove'])->name('schedules.bulk-approve');
            Route::post('/schedules/bulk-delete', [SalaryScheduleController::class, 'bulkDelete'])->name('schedules.bulk-delete');
            Route::get('/schedules/export', [SalaryScheduleController::class, 'export'])->name('schedules.export');
            
            // Pending Approvals
            Route::get('/pending-approvals', [SalaryPaymentController::class, 'getPendingApprovals'])->name('pending.approvals');
            Route::get('/pending-count', [SalaryPaymentController::class, 'getPendingCount'])->name('pending.count');
            Route::post('/salary/payments/{id}/approve', [SalaryPaymentController::class, 'approve'])->name('salary.payments.approve');
            
            // Dismissals
            Route::get('/dismissals', [DismissalController::class, 'index'])->name('dismissals.index');
            Route::get('/dismissals/create', [DismissalController::class, 'create'])->name('dismissals.create');
            Route::post('/dismissals', [DismissalController::class, 'store'])->name('dismissals.store');
            Route::get('/dismissals/{id}', [DismissalController::class, 'show'])->name('dismissals.show');
            Route::post('/dismissals/{id}/approve', [DismissalController::class, 'approve'])->name('dismissals.approve');
            Route::post('/dismissals/{id}/reject', [DismissalController::class, 'reject'])->name('dismissals.reject');
            Route::post('/dismissals/{id}/process', [DismissalController::class, 'process'])->name('dismissals.process');
            Route::post('/dismissals/{id}/complete', [DismissalController::class, 'complete'])->name('dismissals.complete');
            Route::get('/employees/{id}/details', [DismissalController::class, 'getEmployeeDetails'])->name('employees.details');
            
            // Super Deductions
            Route::get('/super-deductions', [SuperDeductionController::class, 'index'])->name('super-deductions.index');
            Route::get('/super-deductions/create', [SuperDeductionController::class, 'create'])->name('super-deductions.create');
            Route::post('/super-deductions', [SuperDeductionController::class, 'store'])->name('super-deductions.store');
            Route::post('/super-deductions/{id}/approve', [SuperDeductionController::class, 'approve'])->name('super-deductions.approve');
            Route::post('/super-deductions/{id}/reject', [SuperDeductionController::class, 'reject'])->name('super-deductions.reject');
        });
        
        // LINKS MANAGEMENT
        Route::prefix('links')->name('links.')->group(function () {
            Route::get('/', [LinkController::class, 'index'])->name('index');
            Route::get('/create', [LinkController::class, 'create'])->name('create');
            Route::post('/', [LinkController::class, 'store'])->name('store');
            Route::get('/{link}', [LinkController::class, 'show'])->name('show');
            Route::get('/{link}/edit', [LinkController::class, 'edit'])->name('edit');
            Route::put('/{link}', [LinkController::class, 'update'])->name('update');
            Route::patch('/{link}', [LinkController::class, 'update'])->name('update.patch');
            Route::delete('/{link}', [LinkController::class, 'destroy'])->name('destroy');
            Route::delete('/{link}/gdpr-erasure', [LinkController::class, 'gdprErasure'])->name('gdpr.erasure')->where('link', '[0-9]+');
            Route::delete('/{link}/force-delete', [LinkController::class, 'forceDelete'])->name('force.delete')->where('link', '[0-9]+');
            Route::post('/{link}/restore', [LinkController::class, 'restore'])->name('restore')->where('link', '[0-9]+');
            Route::post('/bulk/activate', [LinkController::class, 'bulkActivate'])->name('bulk.activate');
            Route::post('/bulk/deactivate', [LinkController::class, 'bulkDeactivate'])->name('bulk.deactivate');
            Route::post('/bulk/delete', [LinkController::class, 'bulkDelete'])->name('bulk.delete');
            Route::get('/export/json', [LinkController::class, 'exportJson'])->name('export.json');
            Route::get('/export/csv', [LinkController::class, 'exportCsv'])->name('export.csv');
            Route::get('/statistics', [LinkController::class, 'statistics'])->name('statistics');
            Route::get('/dashboard', [LinkController::class, 'dashboard'])->name('dashboard');
            Route::get('/type/{type}', [LinkController::class, 'filterByType'])->name('filter.type')->where('type', 'whatsapp|group|jforce|study');
            Route::get('/active', [LinkController::class, 'activeOnly'])->name('active');
            Route::get('/expired', [LinkController::class, 'expiredOnly'])->name('expired');
            Route::get('/trash', [LinkController::class, 'trash'])->name('trash');
            Route::get('/search', [LinkController::class, 'search'])->name('search');
            Route::post('/{link}/click', [LinkController::class, 'trackClick'])->name('track.click');
            Route::post('/{link}/renew', [LinkController::class, 'renew'])->name('renew');
            Route::get('/{link}/qrcode', [LinkController::class, 'generateQrCode'])->name('qrcode');
        });
        
        // REPORTS
        Route::controller(ReportController::class)->group(function () {
            Route::get('/reports/index', 'index')->name('reports.index');
            Route::get('/reports/create', 'create')->name('reports.create');
            Route::post('/reports', 'store')->name('reports.store');
            Route::get('/handlereports', 'handleReports')->name('reports.handle');
            Route::get('/reports/{report}', 'show')->name('reports.show');
            Route::get('/reports/{report}/edit', 'edit')->name('reports.edit');
            Route::put('/reports/{report}', 'update')->name('reports.update');
            Route::delete('/reports/{report}', 'destroy')->name('reports.destroy');
            Route::get('/reports/{report}/download', 'download')->name('reports.download');
            Route::get('/approve', 'approve')->name('approve');
            Route::get('/masters', 'masters')->name('ViewAll');
            Route::get('/clear-reports', 'clearReports')->name('clear.reports');
            Route::post('/reports/bulk-actions', 'bulkActions')->name('reports.bulk');
            Route::post('/reports/{report}/approve', 'approve')->name('reports.approve');
            Route::post('/reports/{report}/reject', 'reject')->name('reports.reject');
        });
        
        Route::prefix('reports')->group(function () {
            Route::get('/monthly', [ReportController::class, 'monthlyReport'])->name('reports.monthly');
            Route::get('/station/{stationId}', [ReportController::class, 'stationReport'])->name('reports.station');
            Route::get('/export', [ReportController::class, 'exportReport'])->name('reports.export');
        });
        
        // DEDUCTION TRANSACTION 
        Route::resource('/deductions', DeductionTransactionController::class)->names([
            'index' => 'deductions.index',
            'create' => 'deductions.create',
            'show' => 'deductions.show',
            'store' => 'deductions.store',
            'edit' => 'deductions.edit',
            'update' => 'deductions.update',
            'destroy' => 'deductions.destroy',
        ]);
        
        Route::get('/deductions/employee/{employeeId}', [DeductionTransactionController::class, 'employeeTransactions'])->name('deductions.employee-transactions');
        Route::get('/deductions/balance/{employeeId}', [DeductionTransactionController::class, 'getCurrentBalance'])->name('deductions.balance');
        Route::get('/employees/{employeeId}/deduction-history', [DeductionTransactionController::class, 'employeeHistory'])->name('employees.deduction-history');
        Route::get('/deductions/get-balance/{employeeId}', [DeductionTransactionController::class, 'getCurrentBalance'])->name('deductions.get-balance');
        
        // PAYMENT 
        
        // Payment Schedules 
        Route::prefix('payments/schedules')->name('payments.schedules.')->group(function () {
            Route::get('/', [PaymentController::class, 'indexSchedules'])->name('index');
            Route::get('/create', [PaymentController::class, 'createSchedule'])->name('create');
            Route::post('/', [PaymentController::class, 'storeSchedule'])->name('store');
            Route::get('/{schedule}', [PaymentController::class, 'showSchedule'])->name('show');
            Route::get('/{schedule}/edit', [PaymentController::class, 'editSchedule'])->name('edit');
            Route::put('/{schedule}', [PaymentController::class, 'updateSchedule'])->name('update');
            Route::delete('/{schedule}', [PaymentController::class, 'destroySchedule'])->name('destroy');
        });
        
        // INTERNET PAYMENT 
        Route::prefix('payments/internet')->name('payments.internet.')->group(function () {
            Route::get('/', [PaymentController::class, 'indexInternetPayments'])->name('index');
            Route::get('/create', [PaymentController::class, 'createInternetPayment'])->name('create');
            Route::post('/', [PaymentController::class, 'storeInternetPayment'])->name('store');
            Route::get('/{id}/edit', [PaymentController::class, 'editInternetPayment'])->name('edit');
            Route::put('/{id}', [PaymentController::class, 'updateInternetPayment'])->name('update');
            Route::get('/{id}/partial', [PaymentController::class, 'showInternetPaymentPartial'])->name('partial');
            Route::get('/{id}', [PaymentController::class, 'showInternetPayment'])->name('show');
            Route::delete('/{id}', [PaymentController::class, 'destroyInternetPayment'])->name('destroy');
            Route::post('/{id}/mpesa-payment', [PaymentController::class, 'initiateMpesaPayment'])->name('mpesa-payment');
        });
        
        Route::get('/payments/internet/check-transaction/{transactionId}', [PaymentController::class, 'checkMpesaTransaction'])->name('payments.internet.check-transaction');
        Route::post('/mpesa/callback', [PaymentController::class, 'mpesaCallback'])->name('mpesa.callback');
        
        // Alternate Internet Payments
        Route::prefix('internet-payments')->name('payments.internet.')->group(function () {
            Route::get('/', [InternetPaymentController::class, 'index'])->name('index-alt');
            Route::get('/create', [InternetPaymentController::class, 'create'])->name('create-alt');
            Route::post('/', [InternetPaymentController::class, 'store'])->name('store-alt');
            Route::get('/{id}/edit', [InternetPaymentController::class, 'edit'])->name('edit-alt');
            Route::put('/{id}', [InternetPaymentController::class, 'update'])->name('update-alt');
            Route::delete('/{id}', [InternetPaymentController::class, 'destroy'])->name('destroy-alt');
            Route::get('/{id}/partial', [InternetPaymentController::class, 'showPartial'])->name('partial-alt');
            Route::get('/{id}', [InternetPaymentController::class, 'show'])->name('show-alt');
            Route::post('/{id}/mark-paid', [InternetPaymentController::class, 'markPaid'])->name('mark-paid');
            Route::post('/{id}/send-reminder', [InternetPaymentController::class, 'sendReminder'])->name('send-reminder');
        });
        
        // AIRTIME PAYMENT
        Route::prefix('payments/airtime')->name('payments.airtime.')->group(function () {
            Route::get('/', [PaymentController::class, 'indexAirtimePayments'])->name('index');
            Route::get('/create', [PaymentController::class, 'createAirtimePayment'])->name('create');
            Route::post('/', [PaymentController::class, 'storeAirtimePayment'])->name('store');
            Route::get('/{id}/edit', [PaymentController::class, 'editAirtimePayment'])->name('edit');
            Route::put('/{id}', [PaymentController::class, 'updateAirtimePayment'])->name('update');
            Route::get('/{id}/renew', [PaymentController::class, 'renewAirtimePayment'])->name('renew');
            Route::get('/{id}/partial', [PaymentController::class, 'getAirtimeDetailsPartial'])->name('partial');
            Route::get('/{id}', [PaymentController::class, 'showAirtimeDetails'])->name('show');
            Route::delete('/{id}', [PaymentController::class, 'destroyAirtimePayment'])->name('delete');
            Route::post('/check-expiries', [PaymentController::class, 'checkAirtimeExpiries'])->name('check-expiries');
        });
        
        // Other Payments
        Route::prefix('payments')->group(function () {
            Route::get('/upcoming', [PaymentController::class, 'upcomingPayments'])->name('payments.upcoming');
            Route::get('/overdue', [PaymentController::class, 'overduePayments'])->name('payments.overdue');
            Route::get('/station/{stationId}', [PaymentController::class, 'stationPayments'])->name('payments.station');
            Route::get('/station-details/{stationId}', [PaymentController::class, 'showStationDetails'])->name('payments.station.details');
            Route::get('/create', [PaymentController::class, 'create'])->name('payments.create');
            Route::post('/', [PaymentController::class, 'store'])->name('payments.store');
            Route::get('/index', [PaymentController::class, 'index'])->name('payments.index');
            Route::get('/{payment}/edit', [PaymentController::class, 'edit'])->name('payments.edit');
            Route::put('/{payment}', [PaymentController::class, 'update'])->name('payments.update');
            Route::delete('/{payment}', [PaymentController::class, 'destroy'])->name('payments.destroy');
            Route::post('/{payment}/approve', [PaymentController::class, 'approve'])->name('payments.approve');
            Route::post('/{payment}/mark-as-paid', [PaymentController::class, 'markAsPaid'])->name('payments.mark-as-paid');
            Route::post('/send-bulk-reminders', [PaymentController::class, 'sendBulkReminders'])->name('payments.bulk-reminders');
            Route::get('/bulk-reminder/form', [PaymentController::class, 'showBulkReminderForm']);
            Route::post('/bulk-reminder/send', [PaymentController::class, 'sendBulkReminders']);
            
            // WILDCARD 
            Route::get('/{payment}', [PaymentController::class, 'show'])->name('payments.show');
        });
        
        // STATIONS
        Route::prefix('stations')->name('stations.')->group(function () {
            Route::get('/', [StationController::class, 'index'])->name('index');
            Route::get('/create', [StationController::class, 'create'])->name('create');
            Route::post('/', [StationController::class, 'store'])->name('store');
            Route::get('/{station}', [StationController::class, 'show'])->name('show');
            Route::get('/{station}/edit', [StationController::class, 'edit'])->name('edit');
            Route::put('/{station}', [StationController::class, 'update'])->name('update');
            Route::delete('/{station}', [StationController::class, 'destroy'])->name('destroy');
            
            // Service Providers and Vendors
            Route::get('/service-providers', [ServiceProviderController::class, 'index'])->name('service-providers.index');
            Route::get('/service-providers/{id}', [ServiceProviderController::class, 'show'])->name('service-providers.show');
            Route::get('/vendors', [VendorController::class, 'index'])->name('vendors.index');
            Route::get('/vendors/{id}', [VendorController::class, 'show'])->name('vendors.show');
            
            // Provider and Vendor assignments
            Route::post('/{stationId}/assign-provider', [StationController::class, 'assignProvider'])->name('assign-provider');
            Route::post('/{stationId}/assign-vendor', [StationController::class, 'assignVendor'])->name('assign-vendor');
            Route::get('/{stationId}/provider-assignment/{providerId}', [StationController::class, 'getProviderAssignment'])->name('get-provider-assignment');
            Route::get('/{stationId}/vendor-assignment/{vendorId}', [StationController::class, 'getVendorAssignment'])->name('get-vendor-assignment');
            Route::put('/{stationId}/update-provider-assignment/{providerId}', [StationController::class, 'updateProviderAssignment'])->name('update-provider-assignment');
            Route::put('/{stationId}/update-vendor-assignment/{vendorId}', [StationController::class, 'updateVendorAssignment'])->name('update-vendor-assignment');
            Route::delete('/{stationId}/remove-provider/{providerId}', [StationController::class, 'removeProvider'])->name('remove-provider');
            Route::delete('/{stationId}/remove-vendor/{vendorId}', [StationController::class, 'removeVendor'])->name('remove-vendor');
        });
        
        //for station payments
        Route::get('/station/{stationId}', [PaymentController::class, 'stationPayments'])->name('station');
        
        // EMPLOYEE 
        Route::resource('/employees', EmployeeController::class)->names([
            'index' => 'employees.index',
            'create' => 'employees.create',
            'edit' => 'employees.edit',
            'show' => 'employees.show',
        ]);
        
        Route::get('/employees/search', [EmployeeController::class, 'search'])->name('employees.search');
        Route::get('/employees/{id}', function($id) {
            $employee = \App\Models\Employee::findOrFail($id);
            return response()->json(['success' => true, 'data' => $employee]);
        })->name('employee.show');
        
        // OTHER RESOURCES
        Route::resource('/losses', LossController::class)->names([
            'index' => 'losses.index',
            'create' => 'losses.create',
            'stationLosses' => 'losses.station',
            'show' => 'losses.show',
            'edit' => 'loss.edit'
        ]);
        
        Route::resource('vendors', VendorController::class);
        Route::get('vendors/{vendor}/download-contract', [VendorController::class, 'downloadContract'])->name('vendors.contract.download');
        Route::resource('vendor-categories', VendorCategoryController::class);
        Route::resource('users', UserController::class);
        Route::resource('internet-providers', InternetProviderController::class);
        
        // NOTIFICATION
        Route::get('/notifications', [NotificationController::class, 'index'])->name('notifications.index');
        Route::get('/notifications/{notification}', [NotificationController::class, 'show'])->name('notifications.show');
        Route::post('/notifications/{notification}/read', [NotificationController::class, 'markAsRead'])->name('notifications.read');
        Route::post('/notifications/mark-all-read', [NotificationController::class, 'markAllAsRead'])->name('notifications.mark-all-read');
        Route::post('/notifications/check-expiries', [NotificationController::class, 'checkExpiries'])->name('notifications.check-expiries');
        Route::post('/notifications/cleanup', [NotificationController::class, 'cleanupOld'])->name('notifications.cleanup');
        Route::delete('/notifications/{notification}', [NotificationController::class, 'destroy'])->name('notifications.destroy');
        
        // PENDING APPROVALS
        Route::prefix('pending-approvals')->name('pending-approvals.')->group(function () {
            Route::get('/', [PendingApprovalController::class, 'index'])->name('index');
            Route::post('/{id}/approve', [PendingApprovalController::class, 'approve'])->name('approve');
            Route::post('/{id}/reject', [PendingApprovalController::class, 'reject'])->name('reject');
        });
        
        // USER PREFERENCES
        Route::post('/preferences/theme', [UserPreferenceController::class, 'updateTheme'])->name('preferences.theme');
        Route::post('/preferences/brightness', [UserPreferenceController::class, 'updateBrightness'])->name('preferences.brightness');
        Route::get('/preferences', [UserPreferenceController::class, 'getUserPreferences'])->name('preferences.get');
        
        // SUCCESS RATE
        Route::get('/successrate', [SuccessRateController::class, 'index'])->name('successrate.index');
        Route::post('/successrate/upload', [SuccessRateController::class, 'upload'])->name('successrate.upload');
        Route::get('/successrate/analysis', [SuccessRateController::class, 'showAnalysis'])->name('successrate.analysis');
        Route::get('/successrate/station/{stationName}', [SuccessRateController::class, 'getStationDetails'])->name('successrate.station.details');
        Route::get('/api/weekly-progress', [SuccessRateController::class, 'getWeeklyProgress'])->name('successrate.weekly.progress');
        Route::get('/export-report', [SuccessRateController::class, 'exportReport'])->name('successrate.export');
        
        // EMPLOYEE DISMISSAL & IMPORT
        Route::post('employees/{employee}/dismiss', [EmployeeDismissalController::class, 'dismiss'])->name('employees.dismiss');
        Route::post('employees/{employee}/reinstate', [EmployeeDismissalController::class, 'reinstate'])->name('employees.reinstate');
        Route::get('employees/{employee}/termination-logs', [EmployeeDismissalController::class, 'logs'])->name('employees.termination-logs');
        Route::get('employees/import', [EmployeeImportController::class, 'showImportForm'])->name('employees.import.form');
        Route::post('employees/import', [EmployeeImportController::class, 'importEmployees'])->name('employees.import');
        Route::get('dismissal/dashboard', [DismissalDashboardController::class, 'index'])->name('dismissal.dashboard');
        Route::post('dismissal/cleanup', [DismissalDashboardController::class, 'triggerCleanup'])->name('dismissal.cleanup');
        Route::post('dismissal/retry-payroll/{employee}', [DismissalDashboardController::class, 'retryPayroll'])->name('dismissal.retry-payroll');
        Route::post('dismissal/retry-all-pending', [DismissalDashboardController::class, 'retryAllPendingPayroll'])->name('dismissal.retry-all');
        
        // API
        Route::prefix('api')->group(function () {
            Route::get('/payments/upcoming-count', [PaymentController::class, 'getUpcomingCount']);
            Route::get('/payments/overdue-count', [PaymentController::class, 'getOverdueCount']);
        });
    });

    // MANAGER ONLY
    Route::middleware(['auth', 'role:manager'])->group(function () {
        Route::get('reports', [ReportController::class, 'index']);
    });

    // TEST & DEBUG
    Route::get('/test-deductions/{station_id}', function($station_id) {
        $station = \App\Models\Station::find($station_id);
        if (!$station) {
            return "Station not found";
        }
        echo "<h1>Station: {$station->name}</h1>";
        echo "<h2>Employees: {$station->employees->count()}</h2>";
        foreach ($station->employees as $employee) {
            echo "<h3>Employee: {$employee->full_name} (ID: {$employee->employee_id})</h3>";
            $deductionsCount = \App\Models\DeductionTransaction::where('employee_id', $employee->employee_id)->count();
            echo "Deductions count: " . $deductionsCount . "<br>";
            $deductions = \App\Models\DeductionTransaction::where('employee_id', $employee->employee_id)->get();
            if ($deductions->count() > 0) {
                echo "<table border='1'><tr><th>Date</th><th>Reason</th><th>Amount</th></tr>";
                foreach ($deductions as $deduction) {
                    echo "<tr><td>{$deduction->transaction_date}</td><td>{$deduction->reason}</td><td>{$deduction->amount}</td></tr>";
                }
                echo "</table>";
            } else {
                echo "No deductions found<br>";
            }
            echo "<hr>";
        }
        return "";
    });

    Route::get('/test-approval-service', function() {
        try {
            $service = new \App\Services\PendingApprovalService();
            return response()->json([
                'success' => true,
                'requires_approval' => $service->requiresApproval(['basic_salary' => 50000]),
                'message' => 'Service is working'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ], 500);
        }
    });

    Route::get('/sync-employees', function () {
        $employees = App\Models\Employee::all();
        $count = 0;
        foreach ($employees as $employee) {
            App\Models\SalaryEmployee::updateOrCreate(
                ['phone' => $employee->phone],
                [
                    'name' => $employee->full_name ?? $employee->first_name . ' ' . $employee->last_name,
                    'phone' => $employee->phone,
                    'position' => $employee->position,
                    'station' => $employee->station?->name ?? 'Main Office',
                    'status' => $employee->status,
                    'base_salary' => $employee->salary,
                    'bank_account' => $employee->bank_account ?? null,
                    'mpesa_number' => $employee->phone,
                ]
            );
            $count++;
        }
        return "Successfully synced {$count} employees!";
    });

    // Debug 
    Route::get('/debug-routes', function() {
        $routes = [];
        foreach (Route::getRoutes() as $route) {
            if (str_contains($route->uri(), 'airtime') || str_contains($route->uri(), 'internet-payments') || str_contains($route->uri(), 'payments')) {
                $routes[] = [
                    'uri' => $route->uri(),
                    'name' => $route->getName(),
                    'methods' => $route->methods(),
                ];
            }
        }
        return response()->json($routes);
    });

    Route::prefix('mpesa')->name('mpesa.')->middleware(['auth'])->group(function () {
        
        // Main payment form - Direct access route
        Route::get('/pay/{payment}', [MpesaController::class, 'showPaymentForm'])
            ->name('pay.form')
            ->where('payment', '[0-9]+');
        
        // Alternative: Pay by invoice/account number
        Route::get('/pay/account/{accountNumber}', function ($accountNumber) {
            $payment = InternetPayment::where('account_number', $accountNumber)
                ->where('status', 'pending')
                ->latest()
                ->firstOrFail();
            
            return redirect()->route('mpesa.pay.form', $payment->id);
        })->name('pay.by_account');
        
        // API endpoints for the payment flow
        Route::post('/initiate/{payment}', [MpesaController::class, 'initiateMpesaPayment'])
            ->name('initiate');
        
        Route::get('/transaction/{checkoutRequestId}', [MpesaController::class, 'checkMpesaTransaction'])
            ->name('check');
        
        Route::get('/status/{payment}', [MpesaController::class, 'getPaymentStatus'])
            ->name('status');
    });

    // Callback routes
    Route::prefix('mpesa')->group(function () {
        Route::post('/callback', [MpesaController::class, 'mpesaCallback'])
            ->name('mpesa.callback');
        
        Route::post('/result', [MpesaController::class, 'mpesaResult'])
            ->name('mpesa.result');
        
        Route::post('/timeout', [MpesaController::class, 'mpesaTimeout'])
            ->name('mpesa.timeout');
    });

    // Helper route to generate payment link (can be shared)
    Route::get('/payment-link/{paymentId}/mpesa', function ($paymentId) {
        $payment = InternetPayment::findOrFail($paymentId);
        $link = route('mpesa.pay.form', $payment->id);
        
        return response()->json([
            'payment_id' => $payment->id,
            'amount' => $payment->amount,
            'payment_link' => $link,
            'qr_code_url' => 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . urlencode($link)
        ]);
    })->name('mpesa.payment_link')->middleware('auth');

    Route::get('/mpesa/test-callback', function () {
    return response()->json([
        'message' => 'Callback URL is working!',
        'ip' => request()->ip(),
        'timestamp' => now()
    ]);
    })->name('mpesa.test');

    // FALLBACK 
    Route::fallback(function () {
        return redirect()->route('links.index')
            ->with('error', 'Page not found. Redirected to Link Manager.');
    });

    