<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;

// Frontend routes removed - keeping only admin panel
// Redirect root to login page
Route::get('/', function () {
    return redirect('/login');
});

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

    // Password Reset Routes
    Route::get('/forgot-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'showLinkRequestForm'])->name('password.request');
    Route::post('/forgot-password', [App\Http\Controllers\Auth\ForgotPasswordController::class, 'sendResetLinkEmail'])->name('password.email');
    Route::get('/reset-password/{token}', [App\Http\Controllers\Auth\ResetPasswordController::class, 'showResetForm'])->name('password.reset');
    Route::post('/reset-password', [App\Http\Controllers\Auth\ResetPasswordController::class, 'reset'])->name('password.update');
});

Route::middleware('auth')->group(function () {
    Route::post('/logout', [LoginController::class, 'logout'])->name('logout');
    Route::get('/home', [App\Http\Controllers\DashboardController::class, 'index'])->name('home');

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

// Admin and Staff Routes (Admin, Loan Manager, Front Office)
Route::middleware(['auth', 'role:Admin|Loan Manager|Front Office'])->group(function () {
    // Sacco Management Routes
    Route::resource('memberships', App\Http\Controllers\MembershipController::class);
    Route::post('memberships/{membership}/pay-registration-fee', [App\Http\Controllers\MembershipController::class, 'payRegistrationFee'])->name('memberships.pay-registration-fee');
    Route::post('memberships/{membership}/pay-cash-registration-fee', [App\Http\Controllers\MembershipController::class, 'payCashRegistrationFee'])->name('memberships.pay-cash-registration-fee');
    Route::post('memberships/{membership}/generate-credentials', [App\Http\Controllers\MembershipController::class, 'generateCredentials'])->name('memberships.generate-credentials');
    Route::post('memberships/bulk-generate-credentials', [App\Http\Controllers\MembershipController::class, 'bulkGenerateCredentials'])->name('memberships.bulk-generate-credentials');
    Route::get('memberships-export-pdf', [App\Http\Controllers\MembershipController::class, 'exportPdf'])->name('memberships.export.pdf');
    Route::get('memberships-export-excel', [App\Http\Controllers\MembershipController::class, 'exportExcel'])->name('memberships.export.excel');
    Route::get('memberships/{membership}/export-activities-csv', [App\Http\Controllers\MembershipController::class, 'exportMemberActivitiesCsv'])->name('memberships.export-member-activities.csv');
    Route::get('memberships/{membership}/export-activities-excel', [App\Http\Controllers\MembershipController::class, 'exportMemberActivitiesExcel'])->name('memberships.export-member-activities.excel');
    Route::get('memberships/{membership}/export-activities-pdf', [App\Http\Controllers\MembershipController::class, 'exportMemberActivitiesPdf'])->name('memberships.export-member-activities.pdf');
    Route::get('memberships-export-csv', [App\Http\Controllers\MembershipController::class, 'exportCsv'])->name('memberships.export.csv');
    Route::resource('users', App\Http\Controllers\UserController::class);
    Route::patch('users/{user}/verify', [App\Http\Controllers\UserController::class, 'verify'])->name('users.verify');
    Route::post('users/{user}/transfer', [App\Http\Controllers\UserController::class, 'transfer'])->name('users.transfer');
    Route::post('users/{user}/send-message', [App\Http\Controllers\UserController::class, 'sendMessage'])->name('users.send-message');
    Route::get('users-export-pdf', [App\Http\Controllers\UserController::class, 'exportPdf'])->name('users.export.pdf');
    Route::get('users-export-excel', [App\Http\Controllers\UserController::class, 'exportExcel'])->name('users.export.excel');
    Route::get('users-export-csv', [App\Http\Controllers\UserController::class, 'exportCsv'])->name('users.export.csv');
    Route::resource('branches', App\Http\Controllers\BranchController::class);
    Route::get('branches-export-pdf', [App\Http\Controllers\BranchController::class, 'exportPdf'])->name('branches.export.pdf');
    Route::get('branches-export-excel', [App\Http\Controllers\BranchController::class, 'exportExcel'])->name('branches.export.excel');
    Route::get('branches-export-csv', [App\Http\Controllers\BranchController::class, 'exportCsv'])->name('branches.export.csv');
    Route::resource('shares', App\Http\Controllers\ShareController::class);
    Route::get('shares-export-pdf', [App\Http\Controllers\ShareController::class, 'exportPdf'])->name('shares.export.pdf');
    Route::get('shares-export-excel', [App\Http\Controllers\ShareController::class, 'exportExcel'])->name('shares.export.excel');
    Route::get('shares-export-csv', [App\Http\Controllers\ShareController::class, 'exportCsv'])->name('shares.export.csv');
    Route::get('shares-export-pdf', [App\Http\Controllers\ShareController::class, 'exportPdf'])->name('shares.export.pdf');
    Route::get('shares-export-excel', [App\Http\Controllers\ShareController::class, 'exportExcel'])->name('shares.export.excel');
    Route::get('shares-export-csv', [App\Http\Controllers\ShareController::class, 'exportCsv'])->name('shares.export.csv');
    Route::resource('loans', App\Http\Controllers\LoanController::class);
    Route::patch('loans/{loan}/approve', [App\Http\Controllers\LoanController::class, 'approve'])->name('loans.approve');
    Route::patch('loans/{loan}/reject', [App\Http\Controllers\LoanController::class, 'reject'])->name('loans.reject');
    Route::post('loans/{loan}/repay', [App\Http\Controllers\LoanController::class, 'repay'])->name('loans.repay');
    Route::post('loans/{loan}/repay/mpesa', [App\Http\Controllers\LoanController::class, 'repayMpesa'])->name('loans.repay.mpesa');
    Route::prefix('loans/guarantees')->group(function () {
        Route::patch('{guarantee}/approve', [App\Http\Controllers\LoanController::class, 'approveGuarantee'])->name('loans.guarantees.approve');
        Route::patch('{guarantee}/reject', [App\Http\Controllers\LoanController::class, 'rejectGuarantee'])->name('loans.guarantees.reject');
    });
    Route::post('loans/check-defaults', [App\Http\Controllers\LoanController::class, 'checkDefaults'])->name('loans.check-defaults');
    Route::get('loans-export-csv', [App\Http\Controllers\LoanController::class, 'exportCsv'])->name('loans.export.csv');
    Route::get('loans-export-excel', [App\Http\Controllers\LoanController::class, 'exportExcel'])->name('loans.export.excel');
    Route::get('loans-export-pdf', [App\Http\Controllers\LoanController::class, 'exportPdf'])->name('loans.export.pdf');
    Route::get('loans/{loan}/download-details', [App\Http\Controllers\LoanController::class, 'downloadDetails'])->name('loans.download.details');
    Route::get('loans/{loan}/download-schedule', [App\Http\Controllers\LoanController::class, 'downloadSchedule'])->name('loans.download.schedule');
    Route::get('api/members', [App\Http\Controllers\LoanController::class, 'getMembers'])->name('api.members');
    Route::resource('savings', App\Http\Controllers\SavingController::class);
    Route::patch('savings/{saving}/withdraw', [App\Http\Controllers\SavingController::class, 'withdraw'])->name('savings.withdraw');
    Route::patch('savings/{saving}/mature', [App\Http\Controllers\SavingController::class, 'mature'])->name('savings.mature');
    Route::get('savings/{saving}/deposit', [App\Http\Controllers\SavingController::class, 'showDepositForm'])->name('savings.deposit.form');
    Route::post('savings/{saving}/deposit', [App\Http\Controllers\SavingController::class, 'deposit'])->name('savings.deposit');
    Route::get('savings/{saving}/withdraw', [App\Http\Controllers\SavingController::class, 'showWithdrawalForm'])->name('savings.withdraw.form');
    Route::post('savings/{saving}/withdraw', [App\Http\Controllers\SavingController::class, 'processWithdrawal'])->name('savings.withdraw.process');
    Route::get('savings/transaction/{transaction}/receipt', [App\Http\Controllers\SavingController::class, 'showReceipt'])->name('savings.transaction.receipt');
    Route::get('savings/transaction/{transaction}/print', [App\Http\Controllers\SavingController::class, 'printReceipt'])->name('savings.transaction.print');
    Route::get('savings-export-pdf', [App\Http\Controllers\SavingController::class, 'exportPdf'])->name('savings.export.pdf');
    Route::get('savings-export-excel', [App\Http\Controllers\SavingController::class, 'exportExcel'])->name('savings.export.excel');
    Route::get('savings-export-csv', [App\Http\Controllers\SavingController::class, 'exportCsv'])->name('savings.export.csv');
    Route::get('savings/{saving}/download-plan', [App\Http\Controllers\SavingController::class, 'downloadSavingsPlan'])->name('savings.download.plan');
    Route::resource('transactions', App\Http\Controllers\TransactionController::class);
    Route::resource('dividends', App\Http\Controllers\DividendController::class);
    Route::resource('mpesa-credentials', App\Http\Controllers\MpesaCredentialController::class);
// CMS routes removed
    Route::resource('occupations', App\Http\Controllers\OccupationController::class);
    Route::patch('occupations/{occupation}/toggle-status', [App\Http\Controllers\OccupationController::class, 'toggleStatus'])->name('occupations.toggle-status');
    Route::get('occupations-export-pdf', [App\Http\Controllers\OccupationController::class, 'exportPdf'])->name('occupations.export.pdf');
    Route::get('occupations-export-excel', [App\Http\Controllers\OccupationController::class, 'exportExcel'])->name('occupations.export.excel');
    Route::get('occupations-export-csv', [App\Http\Controllers\OccupationController::class, 'exportCsv'])->name('occupations.export.csv');

    // System Settings Routes
    Route::get('system-settings', [App\Http\Controllers\SystemSettingController::class, 'index'])->name('system-settings.index');
    Route::put('system-settings', [App\Http\Controllers\SystemSettingController::class, 'update'])->name('system-settings.update');
    Route::get('system-settings/export-database', [App\Http\Controllers\SystemSettingController::class, 'exportDatabase'])->name('system-settings.export-database');
    Route::post('system-settings/import-database', [App\Http\Controllers\SystemSettingController::class, 'importDatabase'])->name('system-settings.import-database');

    // Communications Routes
    Route::resource('communications', App\Http\Controllers\CommunicationController::class);
    Route::post('communications/{communication}/send', [App\Http\Controllers\CommunicationController::class, 'send'])->name('communications.send');

    // Money Market Routes
    Route::resource('money-market-accounts', App\Http\Controllers\MoneyMarketAccountController::class);
    Route::post('money-market-accounts/{moneyMarketAccount}/withdraw', [App\Http\Controllers\MoneyMarketAccountController::class, 'withdraw'])->name('money-market-accounts.withdraw');
    Route::post('money-market-accounts/{moneyMarketAccount}/mark-matured', [App\Http\Controllers\MoneyMarketAccountController::class, 'markMatured'])->name('money-market-accounts.mark-matured');
    Route::post('money-market-accounts/update-interest', [App\Http\Controllers\MoneyMarketAccountController::class, 'updateInterest'])->name('money-market-accounts.update-interest');
    Route::get('money-market-accounts-export-pdf', [App\Http\Controllers\MoneyMarketAccountController::class, 'exportPdf'])->name('money-market-accounts.export.pdf');
    Route::get('money-market-accounts-export-excel', [App\Http\Controllers\MoneyMarketAccountController::class, 'exportExcel'])->name('money-market-accounts.export.excel');
    Route::get('money-market-accounts-export-csv', [App\Http\Controllers\MoneyMarketAccountController::class, 'exportCsv'])->name('money-market-accounts.export.csv');

    // Currency Management Routes
    Route::resource('currencies', App\Http\Controllers\CurrencyController::class);
    Route::patch('currencies/{currency}/set-primary', [App\Http\Controllers\CurrencyController::class, 'setPrimary'])->name('currencies.set-primary');
    Route::patch('currencies/{currency}/toggle-status', [App\Http\Controllers\CurrencyController::class, 'toggleStatus'])->name('currencies.toggle-status');

    // System Configurations Routes
    Route::resource('system-configurations', App\Http\Controllers\SystemConfigurationController::class)->only(['index', 'update']);

    // M-Pesa Callbacks
    Route::post('/mpesa/registration-fee/callback', [App\Http\Controllers\MpesaController::class, 'registrationFeeCallback'])->name('mpesa.registration-fee.callback');
    Route::post('/mpesa/loan-payment/callback', [App\Http\Controllers\MpesaController::class, 'loanPaymentCallback'])->name('mpesa.loan.payment.callback');
    Route::post('/mpesa/savings-deposit/callback', [App\Http\Controllers\MpesaController::class, 'savingsDepositCallback'])->name('mpesa.savings.deposit.callback');

    // M-Pesa Credentials Testing
    Route::post('mpesa-credentials/{mpesaCredential}/test-connection', [App\Http\Controllers\MpesaCredentialController::class, 'testConnection'])->name('mpesa-credentials.test-connection');

    // Reports
    Route::get('reports', [App\Http\Controllers\ReportController::class, 'index'])->name('reports.index');

    // Transaction Exports
    Route::get('transactions-export-csv', [App\Http\Controllers\TransactionController::class, 'exportCsv'])->name('transactions.export.csv');
    Route::get('transactions-export-excel', [App\Http\Controllers\TransactionController::class, 'exportExcel'])->name('transactions.export.excel');
    Route::get('transactions-export-pdf', [App\Http\Controllers\TransactionController::class, 'exportPdf'])->name('transactions.export.pdf');

    // Real-time Activities
    Route::get('transactions/real-time-activities', [App\Http\Controllers\TransactionController::class, 'getRealTimeActivities'])->name('transactions.real-time-activities');

    // Real-time Dashboard Data
    Route::get('dashboard/real-time-data', [App\Http\Controllers\DashboardController::class, 'getRealTimeDashboardData'])->name('dashboard.real-time-data');

// Frontend API routes removed
});

// Member Routes (for regular users/members)

// Temporary test route for dashboard (remove after testing)
Route::get('/test-dashboard', function () {
    // Mock data for testing
    $stats = [
        'total_members' => 150,
        'active_members' => 142,
        'pending_members' => 8,
        'new_members_this_month' => 12,
        'total_loans' => 45,
        'active_loans' => 38,
        'pending_loans' => 7,
        'approved_loans' => 38,
        'total_loan_amount' => 2500000,
        'loans_this_month' => 8,
        'total_savings_accounts' => 135,
        'active_savings_accounts' => 128,
        'total_savings_balance' => 1800000,
        'savings_deposits_this_month' => 150000,
        'total_transactions' => 1250,
        'completed_transactions' => 1180,
        'pending_transactions' => 70,
        'monthly_revenue' => 450000,
        'total_branches' => 5,
        'active_branches' => 5,
        'recent_activities' => collect([
            (object)['action' => 'New Member Registration', 'details' => 'John Doe joined the sacco', 'icon' => 'fas fa-user-plus', 'color' => 'success', 'amount' => 0, 'timestamp' => now()],
            (object)['action' => 'Loan Application', 'details' => 'Jane Smith applied for a loan', 'icon' => 'fas fa-hand-holding-usd', 'color' => 'warning', 'amount' => 50000, 'timestamp' => now()->subMinutes(5)],
        ]),
        'monthly_trends' => [
            ['month' => 'Apr 2025', 'memberships' => 8, 'loans' => 3, 'transactions' => 25000, 'savings' => 12000],
            ['month' => 'May 2025', 'memberships' => 12, 'loans' => 5, 'transactions' => 35000, 'savings' => 18000],
            ['month' => 'Jun 2025', 'memberships' => 15, 'loans' => 7, 'transactions' => 42000, 'savings' => 22000],
            ['month' => 'Jul 2025', 'memberships' => 18, 'loans' => 9, 'transactions' => 48000, 'savings' => 25000],
            ['month' => 'Aug 2025', 'memberships' => 22, 'loans' => 12, 'transactions' => 55000, 'savings' => 28000],
            ['month' => 'Sep 2025', 'memberships' => 25, 'loans' => 15, 'transactions' => 62000, 'savings' => 32000],
        ],
        'system_health' => [
            'transaction_success_rate' => 94,
            'loan_utilization_rate' => 76,
            'active_members_percentage' => 95,
            'system_uptime' => '99.9%',
            'last_backup' => '2 hours ago'
        ],
        'top_branches' => collect([
            ['name' => 'Main Branch', 'members' => 45, 'savings' => 650000, 'loans' => 1200000, 'performance_score' => 85],
            ['name' => 'Westlands Branch', 'members' => 38, 'savings' => 520000, 'loans' => 950000, 'performance_score' => 78],
            ['name' => 'Kilimani Branch', 'members' => 32, 'savings' => 480000, 'loans' => 850000, 'performance_score' => 72],
        ]),
        'loan_performance' => [
            'total_loan_portfolio' => 2500000,
            'total_repayments' => 1850000,
            'repayment_rate' => 74,
            'on_time_payment_rate' => 89,
            'average_loan_size' => 65000
        ]
    ];

    return view('dashboards.admin', compact('stats'));
})->name('test-dashboard');

// Member Routes (for regular users/members)
Route::middleware(['auth', 'role:Member'])->prefix('member')->name('member.')->group(function () {
    // Dashboard
    Route::get('/dashboard', [App\Http\Controllers\Member\DashboardController::class, 'index'])->name('dashboard');

    // Profile Management
    Route::get('/profile', [App\Http\Controllers\Member\DashboardController::class, 'profile'])->name('profile');
    Route::put('/profile', [App\Http\Controllers\Member\DashboardController::class, 'updateProfile'])->name('profile.update');

    // Loans Management
    Route::resource('loans', App\Http\Controllers\Member\LoanController::class);
    Route::post('loans/{loan}/pay', [App\Http\Controllers\Member\LoanController::class, 'payLoan'])->name('loans.pay');
    Route::get('loans-export-pdf', [App\Http\Controllers\Member\LoanController::class, 'exportPdf'])->name('loans.export');

    // Savings Management
    Route::resource('savings', App\Http\Controllers\Member\SavingController::class);
    Route::post('savings/{saving}/deposit', [App\Http\Controllers\Member\SavingController::class, 'deposit'])->name('savings.deposit');
    Route::post('savings/{saving}/withdraw', [App\Http\Controllers\Member\SavingController::class, 'withdraw'])->name('savings.withdraw');

    // Money Market Management
    Route::resource('money-market', App\Http\Controllers\Member\MoneyMarketController::class)->only(['index', 'show']);
    Route::post('money-market/{moneyMarketAccount}/request-withdrawal', [App\Http\Controllers\Member\MoneyMarketController::class, 'requestWithdrawal'])->name('money-market.request-withdrawal');
    Route::get('money-market-calculator', [App\Http\Controllers\Member\MoneyMarketController::class, 'calculator'])->name('money-market.calculator');
    Route::post('money-market-calculate', [App\Http\Controllers\Member\MoneyMarketController::class, 'calculate'])->name('money-market.calculate');

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