<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\ForgotPasswordController;
use App\Http\Controllers\Auth\ResetPasswordController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\MemberController;
use App\Http\Controllers\MemberLedgerController;
use App\Http\Controllers\LoanController;
use App\Http\Controllers\SavingController;
use App\Http\Controllers\CommitteeController;
use App\Http\Controllers\MeetingController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\NoticeController;
use App\Http\Controllers\IncomeController;
use App\Http\Controllers\ExpenseController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\EventController;
use App\Http\Controllers\SystemController;
use App\Http\Controllers\LogController;
use App\Http\Controllers\ChartOfAccountController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('/test-dashboard', function() {
    try {
        $user = auth()->user();
        
        if (!$user) {
            return '❌ ইউজার লগইন নেই';
        }
        
        $data = [
            'user' => $user,
            'user_type' => $user->user_type,
            'member_exists' => $user->member ? 'হ্যাঁ' : 'না',
        ];
        
        // ডাটাবেস টেস্ট
        $data['total_members'] = \App\Models\Member::count();
        $data['total_savings'] = \App\Models\MonthlySaving::sum('amount') ?? 0;
        $data['total_loans'] = \App\Models\Loan::sum('loan_amount') ?? 0;
        
        return response()->json($data);
    } catch (\Exception $e) {
        return response()->json([
            'error' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ], 500);
    }
})->middleware('auth');
// ====================
// ডিবাগ রুটস (সবসময় উপরে রাখুন)
// ====================
Route::get('/debug', function() {
    $data = [
        'php_version' => PHP_VERSION,
        'laravel_version' => app()->version(),
        'environment' => app()->environment(),
        'debug_mode' => config('app.debug'),
    ];
    
    // ডাটাবেস সংযোগ চেক
    try {
        DB::connection()->getPdo();
        $data['database'] = '✅ সংযোগ সফল';
        $data['database_name'] = DB::connection()->getDatabaseName();
    } catch (\Exception $e) {
        $data['database'] = '❌ ' . $e->getMessage();
    }
    
    return response()->json($data);
});

Route::get('/test-db', function() {
    try {
        DB::connection()->getPdo();
        return response()->json([
            'success' => true,
            'message' => 'ডাটাবেস সংযোগ সফল',
            'database' => DB::connection()->getDatabaseName()
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage()
        ], 500);
    }
});

// ====================
// পাবলিক রুটস
// ====================
Route::get('/', function () {
    return view('welcome');
})->name('home');

// অথেন্টিকেশন রুটস
Route::get('login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('login', [LoginController::class, 'login']);
Route::post('logout', [LoginController::class, 'logout'])->name('logout');

// পাসওয়ার্ড রিসেট রুটস
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::get('/register/member', [MemberController::class, 'registerForm'])->name('members.register.form');
Route::post('/register/member', [MemberController::class, 'registerStore'])->name('members.register.store');

// ====================
// সকল অথেন্টিকেটেড ইউজারের রুটস
// ====================
Route::middleware(['auth'])->group(function () {
    
    // চেক অথেন্টিকেশন
    Route::get('/check-auth', function() {
        return response()->json([
            'authenticated' => auth()->check(),
            'user' => auth()->check() ? auth()->user() : null
        ]);
    });
    
    // ড্যাশবোর্ড
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/accounts', [ChartOfAccountController::class, 'index']);
    
    // প্রোফাইল রুটস
    Route::get('/profile', [MemberController::class, 'profile'])->name('profile');
    Route::put('/profile/update', [MemberController::class, 'updateProfile'])->name('profile.update');
    Route::get('/profile/change-password', [MemberController::class, 'showChangePasswordForm'])->name('profile.change-password');
    Route::post('/profile/change-password', [MemberController::class, 'changePassword'])->name('profile.change-password.submit');
    
    // সাধারণ সদস্য রুটস
    Route::get('/savings/history', [SavingController::class, 'history'])->name('savings.history');
    Route::get('/savings/print-receipt/{saving}', [SavingController::class, 'printReceipt'])->name('savings.print-receipt');
    Route::get('/loans/my-loans', [LoanController::class, 'myLoans'])->name('loans.my-loans');
    Route::post('/apply-loan', [LoanController::class, 'apply'])->name('loans.apply');
    Route::get('/loans/{loan}/details', [LoanController::class, 'memberLoanDetails'])->name('loans.member-details');
    Route::get('/meetings', [MeetingController::class, 'index'])->name('meetings.index');
    Route::get('/meetings/{meeting}/details', [MeetingController::class, 'memberMeetingDetails'])->name('meetings.member-details');
    Route::get('/events', [EventController::class, 'memberEvents'])->name('events.member-events');
    Route::post('/events/{event}/register', [EventController::class, 'register'])->name('events.register');
    
    // সদস্য লোন বিবরণী
    Route::get('/loans/{loan}/statement', [LoanController::class, 'statement'])->name('loans.statement');
    Route::get('/loans/{loan}/print-card', [LoanController::class, 'printCard'])->name('loans.print-card');
    
    // লোন রিপোর্ট (সকলের জন্য)
    Route::get('/loans-report', [LoanController::class, 'report'])->name('loans.report');
    Route::get('/overdue-loans', [LoanController::class, 'overdueLoans'])->name('loans.overdue');
    Route::get('/loan-summary', [LoanController::class, 'summary'])->name('loans.summary');

    // ====================
    // নোটিশ রুটস (সকল অথেন্টিকেটেড ইউজার)
    // ====================
    Route::prefix('notices')->name('notices.')->group(function () {
        Route::get('/', [NoticeController::class, 'index'])->name('index');
        Route::get('/search', [NoticeController::class, 'search'])->name('search');
        Route::get('/{notice}', [NoticeController::class, 'show'])->name('show');
        Route::get('/{notice}/print', [NoticeController::class, 'printNotice'])->name('print');
        Route::get('/important', [NoticeController::class, 'important'])->name('important');
        Route::get('/meeting', [NoticeController::class, 'meetingNotices'])->name('meeting');
        Route::get('/upcoming', [NoticeController::class, 'upcoming'])->name('upcoming');
        Route::get('/for-me', [NoticeController::class, 'forSpecificMembers'])->name('for-me');
        Route::get('/urgent', [NoticeController::class, 'urgentNotices'])->name('urgent');
        Route::get('/pinned', [NoticeController::class, 'pinnedNotices'])->name('pinned');
        Route::get('/type/{type}', [NoticeController::class, 'byNoticeType'])->name('by-type');
        Route::get('/month/{year}/{month}', [NoticeController::class, 'byMonth'])->name('by-month');
    });

    // সিস্টেম রুটস
    Route::post('/system/maintenance/up', [SystemController::class, 'up'])->name('system.maintenance.up');
    Route::post('/system/maintenance/down', [SystemController::class, 'down'])->name('system.maintenance.down');
    Route::post('/system/cache/clear', [SystemController::class, 'clearCache'])->name('system.cache.clear');
    Route::post('/system/optimize', [SystemController::class, 'optimize'])->name('system.optimize');
    
    // লগস রুটস
    Route::get('/logs/system', [LogController::class, 'system'])->name('logs.system');
    Route::get('/logs/audit', [LogController::class, 'audit'])->name('logs.audit');
    
    // AJAX API Routes
    Route::get('/api/member-info/{memberId}', [MemberController::class, 'getMemberInfo']);
    Route::get('/api/overdue-savings/{memberId}', [MemberController::class, 'getOverdueSavings']);
    Route::get('/api/overdue-months/{memberId}', [MemberController::class, 'getOverdueMonthsList']);
    Route::get('/api/check-existing-saving', [MemberController::class, 'checkExistingSaving']);
    Route::get('/api/monthly-savings-stats', [MemberController::class, 'getMonthlyStats']);
});

// ====================
// কমিটি ও অ্যাডমিন রুটস
// ====================
Route::middleware(['auth', 'checkusertype:committee,admin'])->group(function () {
    
    // কমিটি ড্যাশবোর্ড
    Route::get('/dashboard/committee', [DashboardController::class, 'committeeDashboard'])->name('dashboard.committee');
    
    // সদস্য ব্যবস্থাপনা
    Route::resource('members', MemberController::class)->except(['create', 'store']);
    Route::get('/members/create', [MemberController::class, 'create'])->name('members.create');
    Route::post('/members', [MemberController::class, 'store'])->name('members.store');
    Route::post('/members/{member}/pay-form-fee', [MemberController::class, 'payFormFee'])->name('members.pay-form-fee');
    Route::post('/members/{member}/change-status', [MemberController::class, 'changeStatus'])->name('members.change-status');
    Route::post('/members/{member}/change-approval-status', [MemberController::class, 'changeApprovalStatus'])->name('members.change-approval-status');
    Route::get('/members/{member}/print-card', [MemberController::class, 'printCard'])->name('members.print-card');
    Route::get('/members/report/overview', [MemberController::class, 'report'])->name('members.report');
    Route::get('/members/export/excel', [MemberController::class, 'exportExcel'])->name('members.export.excel');
    Route::get('/members/export/pdf', [MemberController::class, 'exportPdf'])->name('members.export.pdf');
    
    // ====================
    // মেম্বার লেজার রুটস
    // ====================
    Route::prefix('member-ledger')->name('member-ledger.')->group(function () {
        Route::get('/', [MemberLedgerController::class, 'index'])->name('index');
        Route::get('/{member}', [MemberLedgerController::class, 'show'])->name('show');
        Route::get('/{member}/download-pdf', [MemberLedgerController::class, 'downloadPdf'])->name('download.pdf');
        Route::get('/{member}/download-excel', [MemberLedgerController::class, 'downloadExcel'])->name('download.excel');
        Route::get('/api/search-members', [MemberLedgerController::class, 'searchMembers'])->name('api.search');
        Route::get('/create/{member?}', [MemberLedgerController::class, 'create'])->name('create');
        Route::post('/', [MemberLedgerController::class, 'store'])->name('store');
        Route::get('/transaction/{ledger}/edit', [MemberLedgerController::class, 'edit'])->name('edit');
        Route::put('/transaction/{ledger}', [MemberLedgerController::class, 'update'])->name('update');
        Route::delete('/transaction/{ledger}', [MemberLedgerController::class, 'destroy'])->name('destroy');
        Route::post('/transaction/{ledger}/reverse', [MemberLedgerController::class, 'reverse'])->name('reverse');
        Route::post('/generate-from-existing', [MemberLedgerController::class, 'generateFromExisting'])->name('generate.from-existing');
    });
    
    // ঋণ ব্যবস্থাপনা
    Route::prefix('loans')->name('loans.')->group(function () {
        Route::get('/', [LoanController::class, 'index'])->name('index');
        Route::get('/create', [LoanController::class, 'create'])->name('create');
        Route::post('/', [LoanController::class, 'store'])->name('store');
        Route::get('/{loan}', [LoanController::class, 'show'])->name('show');
        Route::get('/{loan}/edit', [LoanController::class, 'edit'])->name('edit');
        Route::put('/{loan}', [LoanController::class, 'update'])->name('update');
        Route::delete('/{loan}', [LoanController::class, 'destroy'])->name('destroy');
        Route::post('/{loan}/approve', [LoanController::class, 'approve'])->name('approve');
        Route::post('/{loan}/disburse', [LoanController::class, 'disburse'])->name('disburse');
        Route::post('/{loan}/reject', [LoanController::class, 'reject'])->name('reject');
        Route::post('/{loan}/pay-installment', [LoanController::class, 'payInstallment'])->name('pay-installment');
        Route::get('/applications', [LoanController::class, 'applications'])->name('applications');
        Route::get('/{loan}/print-agreement', [LoanController::class, 'printAgreement'])->name('print-agreement');
        Route::get('/{loan}/print-schedule', [LoanController::class, 'printSchedule'])->name('print-schedule');
    });
    
    // সঞ্চয় ব্যবস্থাপনা
    Route::prefix('savings')->name('savings.')->group(function () {
        Route::get('/', [SavingController::class, 'index'])->name('index');
        Route::get('/create', [SavingController::class, 'create'])->name('create');
        Route::post('/', [SavingController::class, 'store'])->name('store');
        Route::get('/{saving}', [SavingController::class, 'show'])->name('show');
        Route::get('/{saving}/edit', [SavingController::class, 'edit'])->name('edit');
        Route::put('/{saving}', [SavingController::class, 'update'])->name('update');
        Route::delete('/{saving}', [SavingController::class, 'destroy'])->name('destroy');
        Route::post('/collect-bulk', [SavingController::class, 'collectBulk'])->name('collect-bulk');
        Route::get('/overdue', [SavingController::class, 'overdue'])->name('overdue');
        Route::post('/generate-reminders', [SavingController::class, 'generateReminders'])->name('generate-reminders');
        Route::post('/mark-multiple-paid', [SavingController::class, 'markMultiplePaid'])->name('mark-multiple-paid');
        Route::get('/report/summary', [SavingController::class, 'report'])->name('report');
        Route::get('/print-receipt/{saving}', [SavingController::class, 'printReceipt'])->name('print-receipt');
        Route::get('/monthly/collection', [SavingController::class, 'monthlyCollection'])->name('monthly.collection');
        Route::post('/monthly/generate', [SavingController::class, 'generateMonthlySavings'])->name('monthly.generate');
        Route::get('/member/{member}/history', [SavingController::class, 'memberHistory'])->name('member.history');
    });
    
    // আয় ব্যবস্থাপনা
    Route::prefix('incomes')->name('incomes.')->group(function () {
        Route::get('/', [IncomeController::class, 'index'])->name('index');
        Route::get('/create', [IncomeController::class, 'create'])->name('create');
        Route::post('/', [IncomeController::class, 'store'])->name('store');
        Route::get('/{income}', [IncomeController::class, 'show'])->name('show');
        Route::get('/{income}/edit', [IncomeController::class, 'edit'])->name('edit');
        Route::put('/{income}', [IncomeController::class, 'update'])->name('update');
        Route::delete('/{income}', [IncomeController::class, 'destroy'])->name('destroy');
        Route::get('/report/summary', [IncomeController::class, 'report'])->name('report');
        Route::get('/{income}/print-receipt', [IncomeController::class, 'printReceipt'])->name('print-receipt');
        Route::get('/category/summary', [IncomeController::class, 'categorySummary'])->name('category.summary');
    });
    
    // ব্যয় ব্যবস্থাপনা
    Route::prefix('expenses')->name('expenses.')->group(function () {
        Route::get('/', [ExpenseController::class, 'index'])->name('index');
        Route::get('/create', [ExpenseController::class, 'create'])->name('create');
        Route::post('/', [ExpenseController::class, 'store'])->name('store');
        Route::get('/{expense}', [ExpenseController::class, 'show'])->name('show');
        Route::get('/{expense}/edit', [ExpenseController::class, 'edit'])->name('edit');
        Route::put('/{expense}', [ExpenseController::class, 'update'])->name('update');
        Route::delete('/{expense}', [ExpenseController::class, 'destroy'])->name('destroy');
        Route::get('/report/summary', [ExpenseController::class, 'report'])->name('report');
        Route::get('/report/monthly', [ExpenseController::class, 'monthlyReport'])->name('monthly-report');
        Route::get('/{expense}/print-voucher', [ExpenseController::class, 'printVoucher'])->name('print-voucher');
        Route::get('/category/summary', [ExpenseController::class, 'categorySummary'])->name('category.summary');
    });
    
    // কমিটি ব্যবস্থাপনা
    Route::prefix('committees')->name('committees.')->group(function () {
        Route::get('/', [CommitteeController::class, 'index'])->name('index');
        Route::get('/create', [CommitteeController::class, 'create'])->name('create');
        Route::post('/', [CommitteeController::class, 'store'])->name('store');
        Route::get('/{committee}', [CommitteeController::class, 'show'])->name('show');
        Route::get('/{committee}/edit', [CommitteeController::class, 'edit'])->name('edit');
        Route::put('/{committee}', [CommitteeController::class, 'update'])->name('update');
        Route::delete('/{committee}', [CommitteeController::class, 'destroy'])->name('destroy');
        Route::post('/{committee}/add-member', [CommitteeController::class, 'addMember'])->name('add-member');
        Route::post('/{committee}/members/{committeeMember}/update', [CommitteeController::class, 'updateMember'])->name('update-member');
        Route::post('/{committee}/members/{committeeMember}/remove', [CommitteeController::class, 'removeMember'])->name('remove-member');
        Route::get('/{committee}/print-card', [CommitteeController::class, 'printCommitteeCard'])->name('print-card');
        Route::get('/current', [CommitteeController::class, 'current'])->name('current');
        Route::get('/report', [CommitteeController::class, 'report'])->name('report');
    });
    
    // মিটিং ব্যবস্থাপনা
    Route::prefix('meetings')->name('meetings.')->group(function () {
        Route::get('/', [MeetingController::class, 'index'])->name('index');
        Route::get('/create', [MeetingController::class, 'create'])->name('create');
        Route::post('/', [MeetingController::class, 'store'])->name('store');
        Route::get('/{meeting}', [MeetingController::class, 'show'])->name('show');
        Route::get('/{meeting}/edit', [MeetingController::class, 'edit'])->name('edit');
        Route::put('/{meeting}', [MeetingController::class, 'update'])->name('update');
        Route::delete('/{meeting}', [MeetingController::class, 'destroy'])->name('destroy');
        Route::post('/{meeting}/attendance', [MeetingController::class, 'takeAttendance'])->name('attendance');
        Route::post('/{meeting}/complete', [MeetingController::class, 'complete'])->name('complete');
        Route::post('/{meeting}/cancel', [MeetingController::class, 'cancel'])->name('cancel');
        Route::get('/{meeting}/print-attendance', [MeetingController::class, 'printAttendance'])->name('print-attendance');
        Route::get('/list/upcoming', [MeetingController::class, 'upcoming'])->name('upcoming');
        Route::post('/generate-weekly', [MeetingController::class, 'generateWeekly'])->name('generate-weekly');
        Route::post('/generate-monthly', [MeetingController::class, 'generateMonthly'])->name('generate-monthly');
        Route::post('/generate-annual', [MeetingController::class, 'generateAnnual'])->name('generate-annual');
    });
    
    // একাউন্টিং রুটস (সরলীকৃত)
    Route::prefix('accounting')->name('accounting.')->group(function () {
        Route::get('/', function() {
            return view('accounting.index', [
                'accountCount' => 5,
                'journalCount' => 12,
                'budgetCount' => 3,
                'recentActivities' => []
            ]);
        })->name('index');
        
        Route::get('/chart-of-accounts', function() {
            $accounts = [
                (object) ['id' => 1, 'code' => '1001', 'name' => 'নগদ টাকা', 'type' => 'Asset', 'balance' => 50000, 'status' => 'Active'],
                (object) ['id' => 2, 'code' => '2001', 'name' => 'ব্যাংক ঋণ', 'type' => 'Liability', 'balance' => 200000, 'status' => 'Active'],
                (object) ['id' => 3, 'code' => '3001', 'name' => 'মূলধন', 'type' => 'Equity', 'balance' => 1500000, 'status' => 'Active'],
                (object) ['id' => 4, 'code' => '4001', 'name' => 'সদস্য সঞ্চয় আয়', 'type' => 'Revenue', 'balance' => 250000, 'status' => 'Active'],
                (object) ['id' => 5, 'code' => '5001', 'name' => 'অফিস খরচ', 'type' => 'Expense', 'balance' => 45000, 'status' => 'Active']
            ];
            $totalBalance = array_sum(array_column($accounts, 'balance'));
            return view('accounting.chart-of-accounts.index', compact('accounts', 'totalBalance'));
        })->name('coa.index');
        
        Route::get('/chart-of-accounts/create', function() {
            return view('accounting.chart-of-accounts.create');
        })->name('coa.create');
        
        Route::post('/chart-of-accounts', function() {
            return redirect()->route('accounting.coa.index')->with('success', 'একাউন্ট সফলভাবে তৈরি হয়েছে!');
        })->name('coa.store');
        
        Route::get('/chart-of-accounts/{id}', function($id) {
            $account = (object) ['id' => $id, 'code' => '1001', 'name' => 'নগদ টাকা', 'type' => 'Asset', 'balance' => 50000, 'status' => 'Active', 'description' => 'অফিসের নগদ টাকা'];
            return view('accounting.chart-of-accounts.show', compact('account'));
        })->name('coa.show');
        
        Route::get('/journal-entries', function() {
            return view('accounting.journal-entries.index', ['entries' => [], 'accounts' => [], 'totalDebit' => 0, 'totalCredit' => 0]);
        })->name('journal.index');
        
        Route::get('/journal-entries/create', function() {
            return view('accounting.journal-entries.create');
        })->name('journal.create');
        
        Route::get('/financial-statements/balance-sheet', function() {
            return view('accounting.financial-statements.balance-sheet', ['assets' => [], 'liabilities' => [], 'equity' => [], 'netIncome' => 0, 'asOfDate' => now()]);
        })->name('financial.balance-sheet');
        
        Route::get('/reports/trial-balance', function() {
            return view('accounting.financial-statements.trial-balance', ['trialBalance' => [], 'startDate' => now()->startOfMonth(), 'endDate' => now()]);
        })->name('reports.trial-balance');
        
        Route::get('/financial-statements', function() {
            return view('accounting.financial-statements.index');
        })->name('financial.index');
        
        Route::get('/budgets', function() {
            return view('accounting.budgets.index', ['budgets' => [], 'fiscalYears' => [], 'departments' => [], 'totalSpent' => 0]);
        })->name('budgets.index');
        
        Route::get('/budgets/create', function() {
            return view('accounting.budgets.create');
        })->name('budgets.create');
    });
    
    // ====================
    // নোটিশ ব্যবস্থাপনা (CRUD অপারেশনস)
    // ====================
    Route::prefix('notices')->name('notices.')->group(function () {
        Route::get('/create', [NoticeController::class, 'create'])->name('create');
        Route::post('/', [NoticeController::class, 'store'])->name('store');
        Route::get('/{notice}/edit', [NoticeController::class, 'edit'])->name('edit');
        Route::put('/{notice}', [NoticeController::class, 'update'])->name('update');
        Route::delete('/{notice}', [NoticeController::class, 'destroy'])->name('destroy');
        Route::post('/{notice}/publish', [NoticeController::class, 'publish'])->name('publish');
        Route::post('/{notice}/archive', [NoticeController::class, 'archive'])->name('archive');
        Route::post('/{notice}/change-status', [NoticeController::class, 'changeStatus'])->name('change-status');
        Route::post('/bulk-delete', [NoticeController::class, 'bulkDelete'])->name('bulk-delete');
        Route::get('/drafts', [NoticeController::class, 'draftList'])->name('drafts');
        Route::get('/expired', [NoticeController::class, 'expiredNotices'])->name('expired');
        Route::get('/archive-list', [NoticeController::class, 'archiveIndex'])->name('archive.list');
        Route::get('/status/{status}', [NoticeController::class, 'filterByStatus'])->name('status');
    });
    
    // ইভেন্ট ব্যবস্থাপনা
    Route::prefix('events')->name('events.')->group(function () {
        Route::get('/', [EventController::class, 'index'])->name('index');
        Route::get('/create', [EventController::class, 'create'])->name('create');
        Route::post('/', [EventController::class, 'store'])->name('store');
        Route::get('/{event}', [EventController::class, 'show'])->name('show');
        Route::get('/{event}/edit', [EventController::class, 'edit'])->name('edit');
        Route::put('/{event}', [EventController::class, 'update'])->name('update');
        Route::delete('/{event}', [EventController::class, 'destroy'])->name('destroy');
        Route::get('/calendar/view', [EventController::class, 'calendar'])->name('calendar');
        Route::get('/{event}/participants', [EventController::class, 'participants'])->name('participants');
        Route::get('/upcoming/list', [EventController::class, 'upcomingEvents'])->name('upcoming');
    });
    
    // রিপোর্ট রাউটস
    Route::prefix('reports')->name('reports.')->group(function () {
        Route::get('/summary', [ReportController::class, 'summaryReport'])->name('summary');
        Route::get('/monthly-loan-saving', [ReportController::class, 'monthlyLoanSavingReport'])->name('monthly-loan-saving');
        Route::get('/monthly', [ReportController::class, 'monthlyReport'])->name('monthly');
        Route::get('/annual', [ReportController::class, 'annualReport'])->name('annual');
        Route::get('/member', [ReportController::class, 'memberReport'])->name('member');
        Route::get('/loan', [ReportController::class, 'loanReport'])->name('loan');
        Route::get('/balance-sheet', [ReportController::class, 'balanceSheet'])->name('balance-sheet');
        Route::get('/income-expense', [ReportController::class, 'incomeExpense'])->name('income-expense');
        Route::get('/member-detailed/{memberId}', [ReportController::class, 'memberDetailed'])->name('member-detailed');
        Route::get('/income-category', [ReportController::class, 'incomeByCategory'])->name('income-category');
        Route::get('/expense-category', [ReportController::class, 'expenseByCategory'])->name('expense-category');
        Route::get('/loan-collection', [ReportController::class, 'loanCollectionReport'])->name('loan-collection');
        Route::get('/monthly-saving', [ReportController::class, 'monthlySavingReport'])->name('monthly-saving');
    });
});

// ====================
// শুধুমাত্র অ্যাডমিন রুটস
// ====================
Route::middleware(['auth', 'checkusertype:admin'])->group(function () {
    
    // অ্যাডমিন ড্যাশবোর্ড
    Route::get('/dashboard/admin', [DashboardController::class, 'adminDashboard'])->name('dashboard.admin');
    Route::get('/dashboard/system-stats', [DashboardController::class, 'systemStats'])->name('dashboard.system-stats');
    
    // ব্যবহারকারী ব্যবস্থাপনা
    Route::resource('users', UserController::class);
    Route::post('/users/{user}/change-status', [UserController::class, 'changeStatus'])->name('users.change-status');
    Route::post('/users/{user}/change-role', [UserController::class, 'changeRole'])->name('users.change-role');
    Route::post('/users/{user}/reset-password', [UserController::class, 'resetPassword'])->name('users.reset-password');
    Route::get('/users/activity/logs', [UserController::class, 'activityLogs'])->name('users.activity.logs');
    
    // সিস্টেম সেটিংস
    Route::prefix('settings')->name('settings.')->group(function () {
        Route::get('/', [SettingController::class, 'index'])->name('index');
        Route::put('/general', [SettingController::class, 'updateGeneral'])->name('general.update');
        Route::put('/financial', [SettingController::class, 'updateFinancial'])->name('financial.update');
        Route::put('/email', [SettingController::class, 'updateEmail'])->name('email.update');
        Route::post('/email/test', [SettingController::class, 'testEmail'])->name('email.test');
        Route::put('/sms', [SettingController::class, 'updateSms'])->name('sms.update');
        Route::put('/logo', [SettingController::class, 'updateLogo'])->name('logo.update');
        Route::delete('/logo', [SettingController::class, 'deleteLogo'])->name('logo.delete');
        Route::post('/backup', [SettingController::class, 'createBackup'])->name('backup.create');
        Route::get('/backup/download/{filename}', [SettingController::class, 'downloadBackup'])->name('backup.download');
        Route::delete('/backup/{filename}', [SettingController::class, 'deleteBackup'])->name('backup.delete');
        Route::get('/logs/audit', [SettingController::class, 'auditLogs'])->name('logs.audit');
        Route::get('/logs/system', [SettingController::class, 'systemLogs'])->name('logs.system');
    });
});

// ====================
// API রুটস (JSON রিটার্ন)
// ====================
Route::prefix('api')->middleware('auth')->group(function () {
    Route::get('dashboard-stats', [DashboardController::class, 'getStats'])->name('api.dashboard.stats');
    Route::get('upcoming-payments', [DashboardController::class, 'getUpcomingPayments'])->name('api.upcoming.payments');
    Route::get('recent-activities', [DashboardController::class, 'getRecentActivities'])->name('api.recent.activities');
    
    Route::prefix('members')->name('api.members.')->group(function () {
        Route::get('search', [MemberController::class, 'apiSearch'])->name('search');
        Route::get('stats/overview', [MemberController::class, 'apiStats'])->name('stats.overview');
        Route::get('{member}/details', [MemberController::class, 'apiDetails'])->name('details');
        Route::get('{member}/savings', [MemberController::class, 'apiSavings'])->name('savings');
        Route::get('{member}/loans', [MemberController::class, 'apiLoans'])->name('loans');
    });
    
    Route::prefix('savings')->name('api.savings.')->group(function () {
        Route::get('member-info/{memberId}', [SavingController::class, 'getMemberInfo'])->name('member.info');
    });
    
    Route::prefix('dashboard')->name('api.dashboard.')->group(function () {
        Route::get('quick-stats', [DashboardController::class, 'quickStats'])->name('quick.stats');
        Route::get('gender-stats', [DashboardController::class, 'genderStats'])->name('gender.stats');
    });
    
    Route::prefix('notices')->name('api.notices.')->group(function () {
        Route::get('active-count', [NoticeController::class, 'getActiveCount'])->name('active-count');
        Route::get('recent', [NoticeController::class, 'getRecent'])->name('recent');
    });
    
    Route::prefix('member-ledger')->name('api.member-ledger.')->group(function () {
        Route::get('search-members', [MemberLedgerController::class, 'searchMembers'])->name('search-members');
        Route::get('member-transactions/{memberId}', [MemberLedgerController::class, 'getMemberTransactions'])->name('member-transactions');
        Route::get('member-summary/{memberId}', [MemberLedgerController::class, 'getMemberSummary'])->name('member-summary');
    });
});

// ====================
// ডিবাগ রুটস (শুধুমাত্র লোকাল এনভায়রনমেন্টে)
// ====================
if (app()->environment('local')) {
    Route::get('/debug-middleware-test', function() {
        return response()->json([
            'authenticated' => auth()->check(),
            'user' => auth()->user(),
        ]);
    })->middleware('auth')->name('debug.middleware.test');

    Route::get('/debug-user-type', function() {
        $user = auth()->user();
        return response()->json([
            'user' => $user ? [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'user_type' => $user->user_type,
            ] : null
        ]);
    })->middleware('auth');

    Route::get('/debug/check-permissions', function() {
        return response()->json([
            'storage_framework_sessions_writable' => is_writable(storage_path('framework/sessions')),
            'storage_framework_cache_writable' => is_writable(storage_path('framework/cache')),
            'public_images_writable' => is_writable(public_path('images')),
        ]);
    });

    Route::get('/debug-test', function() {
        return view('debug.test');
    });
}

// ====================
// লেজার জেনারেট রুটস
// ====================
Route::get('/generate-ledgers-form', [MemberLedgerController::class, 'showGenerateForm'])
    ->middleware(['auth', 'checkusertype:committee,admin'])
    ->name('generate.ledgers.form');

Route::post('/generate-ledgers-from-existing', [MemberLedgerController::class, 'generateFromExisting'])
    ->middleware(['auth', 'checkusertype:committee,admin'])
    ->name('generate.ledgers.from.existing');

// ====================
// রিডাইরেক্ট রুটস
// ====================
Route::get('/public/accounting/chart-of-accounts', function() {
    return auth()->check() ? redirect()->route('accounting.coa.index') : redirect()->route('login');
});

Route::get('/public/accounting/journal-entries', function() {
    return auth()->check() ? redirect()->route('accounting.journal.index') : redirect()->route('login');
});

Route::get('/public/accounting/financial-statements/balance-sheet', function() {
    return auth()->check() ? redirect()->route('accounting.financial.balance-sheet') : redirect()->route('login');
});

Route::get('/public/accounting/reports/trial-balance', function() {
    return auth()->check() ? redirect()->route('accounting.reports.trial-balance') : redirect()->route('login');
});

Route::get('/public/member-ledger', function() {
    return auth()->check() ? redirect()->route('member-ledger.index') : redirect()->route('login');
});

// ====================
// Fallback রুট
// ====================
Route::fallback(function () {
    if (auth()->check()) {
        return redirect()->route('dashboard');
    }
    return redirect()->route('login');
});