<?php
// ===== FILE: routes/web.php =====
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\{
    AnggotaController,
    MutasiController,
    KegiatanController,
    KegiatanHierarchicalController,
    TakwimController,
    LaporanController,
    DashboardController,
    StatistikController,
    AuthController,
    UserManagementController,
    PenilaianPesertaController,
    UpaController,
    UpaGroupActivityController,
    UpaAgendaMasterController,
    JenisKegiatanController,
    KeahlianController,
    IndikatorTakwimController,
    AktivitasLuarController,
    RekomposisiUpaController,
    SuratPenempatanController,
    YaumiyahController,
    PerpindahanController,
    PerpindahanAnggotaController,
    DpcController,
    KomposisiController
};

/*
|--------------------------------------------------------------------------
| Web Routes - Complete PKS System
|--------------------------------------------------------------------------
*/

// ===== MOBILE ROUTES (User Interface) =====
Route::prefix('mobile')->name('mobile.')->group(function () {
    // Mobile Dashboard
    Route::get('/', [App\Http\Controllers\MobileController::class, 'dashboard'])->name('dashboard');
    Route::post('/select-anggota', [App\Http\Controllers\MobileController::class, 'selectAnggota'])->name('select-anggota');
    
    // Mobile Attendance
    Route::get('/attendance', [App\Http\Controllers\MobileController::class, 'attendance'])->name('attendance');
    Route::get('/attendance/{kegiatan}', [App\Http\Controllers\MobileController::class, 'attendanceDetail'])->name('attendance.detail');
    Route::post('/attendance/checkin', [App\Http\Controllers\MobileController::class, 'checkin'])->name('attendance.checkin');
    Route::post('/attendance/checkout', [App\Http\Controllers\MobileController::class, 'checkout'])->name('attendance.checkout');
    
    // Mobile Mutasi
    Route::get('/mutasi', [App\Http\Controllers\MobileController::class, 'mutasi'])->name('mutasi');
    Route::get('/mutasi/create', [App\Http\Controllers\MobileController::class, 'createMutasi'])->name('mutasi.create');
    Route::post('/mutasi/submit', [App\Http\Controllers\MobileController::class, 'submitMutasi'])->name('mutasi.submit');
    Route::get('/mutasi/{mutasi}', [App\Http\Controllers\MobileController::class, 'showMutasi'])->name('mutasi.show');
    
    // Mobile Profile
    Route::get('/profile', [App\Http\Controllers\MobileController::class, 'profile'])->name('profile');
    Route::post('/profile/update', [App\Http\Controllers\MobileController::class, 'updateProfile'])->name('profile.update');
});

// ===== AJAX ROUTES (No Authentication Required) =====
Route::get('/rekomposisi-upa/anggota-by-dpc', [RekomposisiUpaController::class, 'getAnggotaByDpc'])->name('rekomposisi-upa.anggota-by-dpc');
Route::get('/rekomposisi-upa/pembimbing-by-dpc', [RekomposisiUpaController::class, 'getPembimbingByDpc'])->name('rekomposisi-upa.pembimbing-by-dpc');
Route::get('/rekomposisi-upa/{rekomposisiUpa}/pdf', [RekomposisiUpaController::class, 'generatePDF'])->name('rekomposisi-upa.pdf');
Route::get('/rekomposisi-upa/{rekomposisiUpa}/print', [RekomposisiUpaController::class, 'printSK'])->name('rekomposisi-upa.print');

// Surat Penempatan AJAX Routes
Route::get('/surat-penempatan/anggota-by-dpc', [SuratPenempatanController::class, 'getAnggotaByDpc'])->name('surat-penempatan.anggota-by-dpc');
Route::get('/surat-penempatan/upa-by-dpc', [SuratPenempatanController::class, 'getUpaByDpc'])->name('surat-penempatan.upa-by-dpc');
Route::get('/surat-penempatan/pembimbing-by-upa', [SuratPenempatanController::class, 'getPembimbingByUpa'])->name('surat-penempatan.pembimbing-by-upa');

// ===== AUTHENTICATION ROUTES =====
Route::middleware('guest')->group(function () {
    Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [AuthController::class, 'login']);
});

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
Route::post('/change-password', [AuthController::class, 'changePassword'])->name('change-password');


// Test routes removed - system is working properly

// Moved IndikatorTakwim routes to protected middleware group

// ===== AJAX ROUTES (No Auth Required) =====
Route::get('/mutasi/get-dpc-by-dpd', [MutasiController::class, 'getDpcByDpd'])->name('mutasi.get-dpc-by-dpd');
Route::get('/mutasi/get-anggota-details', [MutasiController::class, 'getAnggotaDetails'])->name('mutasi.get-anggota-details');

// ===== PROTECTED ROUTES =====
Route::middleware(['auth', 'session.security'])->group(function () {
    // Dashboard
Route::get('/', function () {
    return redirect()->route('dashboard');
});

    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');

    // ===== USER MANAGEMENT ROUTES =====
    // Hanya superadmin yang bisa akses user management
    Route::middleware(['role:superadmin'])->group(function () {
        Route::resource('user-management', UserManagementController::class);
        Route::post('/user-management/{user_management}/toggle-status', [UserManagementController::class, 'toggleStatus'])->name('user-management.toggle-status');
        
        // Penilaian Peserta Takwim Routes
        Route::resource('penilaian-peserta', PenilaianPesertaController::class)->parameters([
            'penilaian-peserta' => 'penilaian'
        ]);
        Route::get('/penilaian-peserta/laporan', [PenilaianPesertaController::class, 'laporan'])->name('penilaian-peserta.laporan');
    });

    // ===== UPA ROUTES =====
    Route::resource('upa', UpaController::class)->parameters([
        'upa' => 'upa'
    ]);
    Route::post('/upa/{upa}/add-member', [UpaController::class, 'addMember'])->name('upa.add-member');
    Route::patch('/upa/{upa}/update-member-jabatan', [UpaController::class, 'updateMemberJabatan'])->name('upa.update-member-jabatan');
    Route::patch('/upa/{upa}/update-pembimbing', [UpaController::class, 'updatePembimbing'])->name('upa.update-pembimbing');
    
    // API routes for dropdown alamat
    Route::get('/api/provinsi', [UpaController::class, 'getProvinsi'])->name('api.provinsi');
    Route::get('/api/kota', [UpaController::class, 'getKota'])->name('api.kota');
    Route::get('/api/kecamatan', [UpaController::class, 'getKecamatan'])->name('api.kecamatan');
    Route::get('/api/kelurahan', [UpaController::class, 'getKelurahan'])->name('api.kelurahan');

    // ===== UPA GROUP ACTIVITY ROUTES =====
    // Definisikan rute spesifik terlebih dahulu agar tidak tertangkap oleh wildcard resource
    Route::get('upa-group-activity/export', [UpaGroupActivityController::class, 'export'])->name('upa-group-activity.export');
    Route::resource('upa-group-activity', UpaGroupActivityController::class)->parameters([
        'upa-group-activity' => 'upaGroupActivity'
    ]);
    
    // API routes for UPA Group Activity
    Route::get('/api/anggota-upa', [UpaGroupActivityController::class, 'getAnggotaUpa'])->name('api.anggota-upa');
    Route::get('/api/pembimbing-upa', [UpaGroupActivityController::class, 'getPembimbingUpa'])->name('api.pembimbing-upa');

    // ===== UPA AGENDA MASTER ROUTES =====
    Route::resource('upa-agenda-master', UpaAgendaMasterController::class)->parameters([
        'upa-agenda-master' => 'upaAgendaMaster'
    ]);
    Route::post('/upa-agenda-master/{upaAgendaMaster}/toggle-status', [UpaAgendaMasterController::class, 'toggleStatus'])->name('upa-agenda-master.toggle-status');

    // ===== MASTER DATA ROUTES =====
    Route::resource('jenis-kegiatan', JenisKegiatanController::class)->parameters([
        'jenis-kegiatan' => 'jenisKegiatan'
    ]);

    Route::resource('keahlian', KeahlianController::class)->parameters([
        'keahlian' => 'keahlian'
    ]);

    Route::resource('indikator-takwim', IndikatorTakwimController::class)->parameters([
        'indikator-takwim' => 'indikatorTakwim'
    ]);

    Route::resource('aktivitas-luar', AktivitasLuarController::class)->parameters([
        'aktivitas-luar' => 'aktivitasLuar'
    ]);

    // ===== DPC ROUTES =====
    Route::resource('dpc', DpcController::class)->parameters([
        'dpc' => 'dpc'
    ]);
    Route::post('/dpc/{dpc}/toggle-status', [DpcController::class, 'toggleStatus'])->name('dpc.toggle-status');


    // ===== ANGGOTA ROUTES =====
    Route::resource('anggota', AnggotaController::class)->parameters([
        'anggota' => 'anggota'
    ])->except(['show', 'edit', 'update', 'destroy']);
    
    // Additional Anggota Routes (harus sebelum slug routes)
    Route::prefix('anggota')->name('anggota.')->group(function () {
        Route::get('/statistik', [AnggotaController::class, 'statistik'])->name('statistik');
        Route::get('/export', [AnggotaController::class, 'export'])->name('export');
        Route::post('/import', [AnggotaController::class, 'import'])->name('import');
        Route::get('/api/search', [AnggotaController::class, 'apiSearch'])->name('api.search');
        
        // Submenu routes untuk anggota aktif dan non aktif
        Route::get('/aktif', [AnggotaController::class, 'indexAktif'])->name('aktif');
        Route::get('/non-aktif', [AnggotaController::class, 'indexNonAktif'])->name('non-aktif');
    });

    // ===== ANGGOTA KEANGGOTAAN ROUTES =====
    Route::prefix('anggota')->name('anggota.keanggotaan.')->group(function () {
        Route::get('/{anggota}/keanggotaan', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'show'])->name('show');
        Route::get('/{anggota}/keanggotaan/edit', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'edit'])->name('edit');
        Route::put('/{anggota}/keanggotaan', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'update'])->name('update');
        Route::get('/{anggota}/keanggotaan/history', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'getHistory'])->name('history');
        Route::get('/{anggota}/keanggotaan/export', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'exportHistory'])->name('export');
        Route::get('/api/upa-options', [App\Http\Controllers\AnggotaKeanggotaanController::class, 'getUpaOptions'])->name('api.upa-options');
    });
    
    // Route untuk update foto
    Route::patch('/anggota/{anggota}/update-foto', [AnggotaController::class, 'updateFoto'])->name('anggota.update-foto');
    
    // Custom routes dengan slug (harus di akhir)
    Route::get('/anggota/{anggota}', [AnggotaController::class, 'show'])->name('anggota.show');
    Route::get('/anggota/{anggota}/edit', [AnggotaController::class, 'edit'])->name('anggota.edit');
    Route::put('/anggota/{anggota}', [AnggotaController::class, 'update'])->name('anggota.update');
    Route::delete('/anggota/{anggota}', [AnggotaController::class, 'destroy'])->name('anggota.destroy');
    Route::get('/anggota/{anggota}/print', [AnggotaController::class, 'print'])->name('anggota.print');

    Route::get('/statistik', [StatistikController::class, 'index'])->name('statistik');

    // ===== KOMPOSISI ROUTES =====
Route::prefix('komposisi')->name('komposisi.')->group(function () {
    Route::get('/', [KomposisiController::class, 'index'])->name('index');
    Route::get('/dpc/{dpc}', [KomposisiController::class, 'showDpc'])->name('show-dpc');
    Route::get('/upa/{upa}', [KomposisiController::class, 'showUpa'])->name('show-upa');
    Route::get('/dpc/{dpc}/print', [KomposisiController::class, 'printDpc'])->name('print-dpc');
    Route::get('/upa/{upa}/print', [KomposisiController::class, 'printUpa'])->name('print-upa');
    
    // AJAX routes for cascading filters
    Route::get('/get-dpc-by-dpd', [KomposisiController::class, 'getDpcByDpd'])->name('get-dpc-by-dpd');
    Route::get('/get-upa-by-dpc', [KomposisiController::class, 'getUpaByDpc'])->name('get-upa-by-dpc');
    Route::get('/print-all', [KomposisiController::class, 'printAll'])->name('print-all');
    Route::get('/print-sk', [KomposisiController::class, 'printSk'])->name('print-sk');
});

    // ===== MUTASI ROUTES =====
    Route::resource('mutasi', MutasiController::class)->parameters([
        'mutasi' => 'mutasi'
    ]);

    // Additional Mutasi Routes
    Route::prefix('mutasi')->name('mutasi.')->group(function () {
        Route::post('/{mutasi}/approve', [MutasiController::class, 'approve'])->name('approve');
        Route::post('/{mutasi}/reject', [MutasiController::class, 'reject'])->name('reject');
        Route::get('/export', [MutasiController::class, 'export'])->name('export');
        Route::get('/{mutasi}/print-surat', [MutasiController::class, 'printSurat'])->name('print-surat');
        Route::get('/keranjang', [MutasiController::class, 'keranjangMutasi'])->name('keranjang');
        Route::post('/kembalikan-status/{anggota}', [MutasiController::class, 'kembalikanStatus'])->name('kembalikan-status');
    });

    // ===== PERPINDAHAN ANGGOTA ROUTES =====
    Route::resource('perpindahan', PerpindahanController::class)->parameters([
        'perpindahan' => 'perpindahan'
    ]);

    // Additional Perpindahan Routes
    Route::prefix('perpindahan')->name('perpindahan.')->group(function () {
        Route::post('/{perpindahan}/approve', [PerpindahanController::class, 'approve'])->name('approve');
        Route::post('/{perpindahan}/reject', [PerpindahanController::class, 'reject'])->name('reject');
        Route::get('/print/surat-resmi', [PerpindahanController::class, 'printSuratResmi'])->name('print.surat-resmi');
        Route::get('/{perpindahan}/print/surat-penempatan', [PerpindahanController::class, 'printSuratPenempatan'])->name('print.surat-penempatan');
    });
    
    // ===== PERPINDAHAN ANGGOTA UNIFIED SYSTEM ROUTES =====
    Route::resource('perpindahan-anggota', PerpindahanAnggotaController::class);
    
    // Additional Perpindahan Anggota Routes
    Route::prefix('perpindahan-anggota')->name('perpindahan-anggota.')->group(function () {
        Route::get('/{perpindahanAnggota}/download-surat', [PerpindahanAnggotaController::class, 'downloadSurat'])->name('download-surat');
    });

    // AJAX endpoints untuk perpindahan anggota
    Route::get('/perpindahan-anggota-ajax/upa-by-dpc', [PerpindahanAnggotaController::class, 'getUpaByDpc'])->name('perpindahan-anggota.ajax.upa-by-dpc');
    Route::get('/perpindahan-anggota-ajax/anggota-by-upa', [PerpindahanAnggotaController::class, 'getAnggotaByUpa'])->name('perpindahan-anggota.ajax.anggota-by-upa');
    Route::get('/perpindahan-anggota-ajax/pembimbing-by-upa', [PerpindahanAnggotaController::class, 'getPembimbingByUpa'])->name('perpindahan-anggota.ajax.pembimbing-by-upa');

    // ===== KEGIATAN ROUTES =====
    // Hierarchical kegiatan routes (MUST BE BEFORE resource routes)
    Route::prefix('kegiatan')->name('kegiatan.')->group(function () {
        Route::get('create-hierarchical', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'create'])->name('hierarchical.create');
        Route::post('store-hierarchical', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'store'])->name('hierarchical.store');
        
        // API routes for hierarchical selection
        Route::get('api/dpc-by-dpd', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'getDpcByDpd'])->name('api.dpc-by-dpd');
        Route::get('api/upa-by-dpc', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'getUpaByDpc'])->name('api.upa-by-dpc');
        Route::get('api/anggota-by-upa', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'getAnggotaByUpa'])->name('api.anggota-by-upa');
        Route::get('api/anggota-by-hierarchy', [\App\Http\Controllers\KegiatanHierarchicalController::class, 'getAnggotaByHierarchy'])->name('api.anggota-by-hierarchy');
    });

    Route::resource('kegiatan', KegiatanController::class)->parameters([
        'kegiatan' => 'kegiatan'
    ]);

    // Additional Kegiatan Routes
    Route::prefix('kegiatan')->name('kegiatan.')->group(function () {
        Route::get('/{kegiatan}/absensi', [KegiatanController::class, 'absensi'])->name('absensi');
        Route::post('/{kegiatan}/absensi', [KegiatanController::class, 'storeAbsensi'])->name('absensi.store');
        Route::get('/export', [KegiatanController::class, 'export'])->name('export');
    });

    // ===== TAKWIM ROUTES =====
    Route::resource('takwim', TakwimController::class)->parameters([
        'takwim' => 'takwim'
    ]);

    // Additional Takwim Routes
    Route::prefix('takwim')->name('takwim.')->group(function () {
        Route::post('/{takwim}/peserta', [TakwimController::class, 'addPeserta'])->name('add-peserta');
        Route::delete('/{takwim}/peserta/{anggota}', [TakwimController::class, 'removePeserta'])->name('remove-peserta');
    });

    // ===== STATISTIK ROUTES =====
    Route::prefix('statistik')->name('statistik.')->group(function () {
        Route::get('/', [StatistikController::class, 'index'])->name('index');
        Route::get('/anggota', [StatistikController::class, 'anggota'])->name('anggota');
        Route::get('/anggota/export', [StatistikController::class, 'exportAnggota'])->name('anggota.export');
        Route::get('/kegiatan', [StatistikController::class, 'kegiatan'])->name('kegiatan');
        Route::get('/mutasi', [StatistikController::class, 'mutasi'])->name('mutasi');
        Route::get('/takwim', [StatistikController::class, 'takwim'])->name('takwim');
        Route::get('/yaumiyah', [StatistikController::class, 'yaumiyah'])->name('yaumiyah');
        Route::get('/upa-activity', [StatistikController::class, 'upaActivity'])->name('upa-activity');
    });

    // ===== REKOMPOSISI UPA ROUTES =====
    Route::resource('rekomposisi-upa', RekomposisiUpaController::class);
    Route::post('/rekomposisi-upa/{rekomposisiUpa}/approve', [RekomposisiUpaController::class, 'approve'])->name('rekomposisi-upa.approve');
    Route::post('/rekomposisi-upa/{rekomposisiUpa}/publish', [RekomposisiUpaController::class, 'publish'])->name('rekomposisi-upa.publish');

    // ===== SURAT PENEMPATAN UPA ROUTES =====
    Route::resource('surat-penempatan', SuratPenempatanController::class)->only(['index', 'create', 'show']);
    Route::post('/surat-penempatan/generate', [SuratPenempatanController::class, 'generate'])->name('surat-penempatan.generate');
    Route::post('/surat-penempatan/generate-pdf', [SuratPenempatanController::class, 'generatePDF'])->name('surat-penempatan.generate-pdf');
    Route::post('/surat-penempatan/transfer', [SuratPenempatanController::class, 'transferAnggota'])->name('surat-penempatan.transfer');
    Route::get('/surat-penempatan/{id}/print', [SuratPenempatanController::class, 'print'])->name('surat-penempatan.print');

    // ===== LAPORAN ROUTES =====
    Route::prefix('laporan')->name('laporan.')->group(function () {
        Route::get('/', [LaporanController::class, 'index'])->name('index');
        Route::get('/anggota', [LaporanController::class, 'anggota'])->name('anggota');
        Route::get('/mutasi', [LaporanController::class, 'mutasi'])->name('mutasi');
        Route::get('/kegiatan', [LaporanController::class, 'kegiatan'])->name('kegiatan');
        Route::get('/kehadiran', [LaporanController::class, 'kehadiran'])->name('kehadiran');
        Route::get('/takwim', [LaporanController::class, 'takwim'])->name('takwim');
        
        // Export Laporan
        Route::get('/export/anggota', [LaporanController::class, 'exportAnggota'])->name('export.anggota');
        Route::get('/export/mutasi', [LaporanController::class, 'exportMutasi'])->name('export.mutasi');
        Route::get('/export/kegiatan', [LaporanController::class, 'exportKegiatan'])->name('export.kegiatan');
    });

    // ===== YAUMAIYAH ROUTES =====
    Route::prefix('yaumiyah')->name('yaumiyah.')->group(function () {
        Route::get('/', [YaumiyahController::class, 'index'])->name('index');
        Route::get('/export', [YaumiyahController::class, 'export'])->name('export');
        Route::get('/records', [YaumiyahController::class, 'records'])->name('records');
        Route::post('/records', [YaumiyahController::class, 'storeRecords'])->name('records.store');
        Route::get('/records-list', [YaumiyahController::class, 'recordsList'])->name('records.list');
        Route::get('/records-detail', [YaumiyahController::class, 'recordsDetail'])->name('records.detail');
        Route::get('/reports', [YaumiyahController::class, 'reports'])->name('reports');
        
        // Master Activities Routes
        Route::prefix('activities')->name('activities.')->group(function () {
            Route::get('/', [YaumiyahController::class, 'activities'])->name('index');
            Route::get('/create', [YaumiyahController::class, 'create'])->name('create');
            Route::post('/', [YaumiyahController::class, 'store'])->name('store');
            Route::get('/{activity}', [YaumiyahController::class, 'show'])->name('show');
            Route::get('/{activity}/edit', [YaumiyahController::class, 'edit'])->name('edit');
            Route::put('/{activity}', [YaumiyahController::class, 'update'])->name('update');
            Route::delete('/{activity}', [YaumiyahController::class, 'destroy'])->name('destroy');
        });
    });

    // ===== YAUMAIYAH API ROUTES (for member portal) =====
    Route::prefix('api/yaumiyah')->name('api.yaumiyah.')->group(function () {
        Route::get('/activities', [YaumiyahController::class, 'apiActivities'])->name('activities');
        Route::get('/records', [YaumiyahController::class, 'apiRecords'])->name('records');
        Route::post('/records', [YaumiyahController::class, 'apiStoreRecords'])->name('records.store');
    });

    // ===== API ROUTES =====
    Route::prefix('api')->name('api.')->group(function () {
        Route::get('/anggota/search', [AnggotaController::class, 'apiSearch'])->name('anggota.search');
        Route::get('/anggota-paginated', [KegiatanController::class, 'getAnggotaPaginated'])->name('anggota.paginated');
        Route::get('/struktur-organisasi', function() {
            return response()->json(\App\Models\StrukturOrganisasi::all());
        })->name('struktur');
    });

    Route::get('/anggota/{anggota}/debug', function(App\Models\Anggota $anggota) {
        dd([
            'anggota' => $anggota->toArray(),
            'mutasi_count' => $anggota->mutasi()->count(),
            'absensi_count' => $anggota->absensiKegiatan()->count(),
            'umur' => $anggota->umur,
            'alamat_lengkap' => $anggota->alamat_lengkap
        ]);
    })->name('anggota.debug');

    Route::get('/anggota/{anggota}/simple', function(App\Models\Anggota $anggota) {
        return view('anggota.show-simple', compact('anggota'));
    })->name('anggota.show-simple');

    // Tambahkan routes import yang missing:
    Route::post('/anggota/import/preview', [AnggotaController::class, 'importPreview'])
         ->name('anggota.import.preview');
    
    Route::post('/anggota/import/process', [AnggotaController::class, 'importProcess'])
         ->name('anggota.import.process');
    
    Route::get('/anggota/import', [AnggotaController::class, 'importForm'])
         ->name('anggota.import');

    // route untuk update kehadiran
    Route::post('/kegiatan/{id}/update-kehadiran', [KegiatanController::class, 'updateKehadiran'])
        ->name('kegiatan.update-kehadiran');
    
    // API routes untuk cascading dropdown
    Route::get('/api/dpc-by-dpd/{dpdId}', function($dpdId) {
        $dpc = \App\Models\Dpc::where('dpd_id', $dpdId)->active()->get();
        return response()->json($dpc);
    });
    
    Route::get('/api/upa-by-dpc/{dpcIds}', function($dpcIds) {
        // Handle multiple DPC IDs separated by comma
        $dpcIdArray = explode(',', $dpcIds);
        
        $upa = \App\Models\RefGrupUpa::whereHas('anggota', function($query) use ($dpcIdArray) {
            $query->whereIn('dpc_id', $dpcIdArray);
        })->active()->get();
        
        return response()->json($upa);
    });
    
    // API routes untuk anggota cascading dropdown
    Route::get('/api/anggota/dpc-by-dpd', [AnggotaController::class, 'getDpcByDpd'])->name('api.anggota.dpc-by-dpd');
    Route::get('/api/anggota/upa-by-dpc', [AnggotaController::class, 'getUpaByDpc'])->name('api.anggota.upa-by-dpc');
    Route::get('/api/anggota/next-nia', [AnggotaController::class, 'getNextNIA'])->name('api.anggota.next-nia');
    
    // Debug routes untuk testing cascading dropdown
    Route::get('/debug/dpd-data', function() {
        $dpds = \App\Models\Dpd::active()->get(['dpd_id', 'nama_dpd']);
        return response()->json($dpds);
    });
    
    Route::get('/debug/dpc-by-dpd/{dpdId}', function($dpdId) {
        $dpc = \App\Models\Dpc::where('dpd_id', $dpdId)
                              ->where('is_active', true)
                              ->get(['dpc_id', 'nama_dpc', 'dpd_id']);
        return response()->json([
            'dpd_id' => $dpdId,
            'dpc_count' => $dpc->count(),
            'dpc_list' => $dpc
        ]);
    });
    
    // Check-in routes (public access for QR code scanning)
    Route::prefix('checkin')->name('checkin.')->group(function () {
        Route::get('/{kegiatanId}', [App\Http\Controllers\CheckinController::class, 'index'])->name('index');
        Route::post('/{kegiatanId}/search', [App\Http\Controllers\CheckinController::class, 'searchAnggota'])->name('search');
        Route::post('/{kegiatanId}/checkin', [App\Http\Controllers\CheckinController::class, 'checkIn'])->name('checkin');
        Route::get('/{kegiatanId}/stats', [App\Http\Controllers\CheckinController::class, 'getStats'])->name('stats');
        Route::get('/{kegiatanId}/qr', [App\Http\Controllers\CheckinController::class, 'generateQR'])->name('qr');
    });
    
    // Test route untuk surat mutasi di browser
    Route::get('/test-surat-mutasi', function() {
        // Ambil data mutasi pertama yang sudah disetujui
        $mutasi = \App\Models\Mutasi::with(['anggota', 'strukturKe'])
            ->where('status_mutasi', 'Disetujui')
            ->first();
            
        if (!$mutasi) {
            // Jika tidak ada mutasi yang disetujui, buat data dummy
            $mutasi = new \App\Models\Mutasi();
            $mutasi->nomor_sk = '006/D/Mts/A1-04-PKS/IX/2025';
            $mutasi->tanggal_mutasi = now();
            $mutasi->alamat_tujuan = 'Jakarta Selatan';
            $mutasi->alasan_mutasi = 'Pindah domisili';
            $mutasi->catatan = 'Test surat mutasi';
            
            // Buat data anggota dummy
            $anggota = new \App\Models\Anggota();
            $anggota->nama_lengkap = 'John Doe';
            $anggota->no_telepon = '08123456789';
            $anggota->tempat_lahir = 'Jakarta';
            $anggota->tanggal_lahir = '1990-01-01';
            $anggota->jenjang_anggota = 'Kader';
            $anggota->pendidikan = 'S1';
            $anggota->pembimbing_nama = 'Ahmad Yani';
            $anggota->pembimbing_telepon = '08123456789';
            
            $mutasi->anggota = $anggota;
            
            // Buat data struktur dummy
            $struktur = new \App\Models\StrukturOrganisasi();
            $struktur->nama_struktur = 'DPC Bandung';
            $mutasi->strukturKe = $struktur;
        }
        
        $data = [
            'nomor_surat' => $mutasi->nomor_sk ?? '006/D/Mts/A1-04-PKS/IX/2025',
            'tanggal' => now()->format('d-m-Y'),
            'mutasi' => $mutasi,
            'anggota' => $mutasi->anggota,
            'dpc_tujuan' => $mutasi->strukturKe,
            'ketua_kaderisasi' => 'H. Indarmawan, Ak'
        ];
        
        return view('surat.mutasi-keluar', $data);
    })->name('test.surat-mutasi');
    
    // Test route untuk surat mutasi sederhana (tanpa gambar)
    Route::get('/test-surat-mutasi-simple', function() {
        // Ambil data mutasi pertama yang sudah disetujui
        $mutasi = \App\Models\Mutasi::with(['anggota', 'strukturKe'])
            ->where('status_mutasi', 'Disetujui')
            ->first();
            
        if (!$mutasi) {
            // Jika tidak ada mutasi yang disetujui, buat data dummy
            $mutasi = new \App\Models\Mutasi();
            $mutasi->nomor_sk = '006/D/Mts/A1-04-PKS/IX/2025';
            $mutasi->tanggal_mutasi = now();
            $mutasi->alamat_tujuan = 'Jakarta Selatan';
            $mutasi->alasan_mutasi = 'Pindah domisili';
            $mutasi->catatan = 'Test surat mutasi';
            
            // Buat data anggota dummy
            $anggota = new \App\Models\Anggota();
            $anggota->nama_lengkap = 'John Doe';
            $anggota->no_telepon = '08123456789';
            $anggota->tempat_lahir = 'Jakarta';
            $anggota->tanggal_lahir = '1990-01-01';
            $anggota->jenjang_anggota = 'Kader';
            $anggota->pendidikan = 'S1';
            $anggota->pembimbing_nama = 'Ahmad Yani';
            $anggota->pembimbing_telepon = '08123456789';
            
            $mutasi->anggota = $anggota;
            
            // Buat data struktur dummy
            $struktur = new \App\Models\StrukturOrganisasi();
            $struktur->nama_struktur = 'DPC Bandung';
            $mutasi->strukturKe = $struktur;
        }
        
        $data = [
            'nomor_surat' => $mutasi->nomor_sk ?? '006/D/Mts/A1-04-PKS/IX/2025',
            'tanggal' => now()->format('d-m-Y'),
            'mutasi' => $mutasi,
            'anggota' => $mutasi->anggota,
            'dpc_tujuan' => $mutasi->strukturKe,
            'ketua_kaderisasi' => 'H. Indarmawan, Ak'
        ];
        
        return view('surat.mutasi-keluar-simple', $data);
    })->name('test.surat-mutasi-simple');
    
    // Test route untuk generate PDF sederhana
    Route::get('/test-pdf-simple', function() {
        // Ambil data mutasi pertama yang sudah disetujui
        $mutasi = \App\Models\Mutasi::with(['anggota', 'strukturKe'])
            ->where('status_mutasi', 'Disetujui')
            ->first();
            
        if (!$mutasi) {
            // Jika tidak ada mutasi yang disetujui, buat data dummy
            $mutasi = new \App\Models\Mutasi();
            $mutasi->nomor_sk = '006/D/Mts/A1-04-PKS/IX/2025';
            $mutasi->tanggal_mutasi = now();
            $mutasi->alamat_tujuan = 'Jakarta Selatan';
            $mutasi->alasan_mutasi = 'Pindah domisili';
            $mutasi->catatan = 'Test surat mutasi';
            
            // Buat data anggota dummy
            $anggota = new \App\Models\Anggota();
            $anggota->nama_lengkap = 'John Doe';
            $anggota->no_telepon = '08123456789';
            $anggota->tempat_lahir = 'Jakarta';
            $anggota->tanggal_lahir = '1990-01-01';
            $anggota->jenjang_anggota = 'Kader';
            $anggota->pendidikan = 'S1';
            $anggota->pembimbing_nama = 'Ahmad Yani';
            $anggota->pembimbing_telepon = '08123456789';
            
            $mutasi->anggota = $anggota;
            
            // Buat data struktur dummy
            $struktur = new \App\Models\StrukturOrganisasi();
            $struktur->nama_struktur = 'DPC Bandung';
            $mutasi->strukturKe = $struktur;
        }
        
        $data = [
            'nomor_surat' => $mutasi->nomor_sk ?? '006/D/Mts/A1-04-PKS/IX/2025',
            'tanggal' => now()->format('d-m-Y'),
            'mutasi' => $mutasi,
            'anggota' => $mutasi->anggota,
            'dpc_tujuan' => $mutasi->strukturKe,
            'ketua_kaderisasi' => 'H. Indarmawan, Ak'
        ];
        
        $pdf = PDF::loadView('surat.mutasi-keluar-simple', $data);
        $pdf->setPaper('A4', 'portrait');
        $pdf->setOptions([
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled' => false,
            'isPhpEnabled' => false,
            'isJavascriptEnabled' => false,
            'defaultFont' => 'Arial',
            'dpi' => 150,
            'enable_font_subsetting' => false,
            'isFontSubsettingEnabled' => false,
        ]);
        
        return $pdf->download("Surat_Mutasi_Keluar_Simple.pdf");
    })->name('test.pdf-simple');
    
    // Test route untuk generate PDF dengan base64 images
    Route::get('/test-pdf-base64', function() {
        // Ambil data mutasi pertama yang sudah disetujui
        $mutasi = \App\Models\Mutasi::with(['anggota', 'strukturKe'])
            ->where('status_mutasi', 'Disetujui')
            ->first();
            
        if (!$mutasi) {
            // Jika tidak ada mutasi yang disetujui, buat data dummy
            $mutasi = new \App\Models\Mutasi();
            $mutasi->nomor_sk = '006/D/Mts/A1-04-PKS/IX/2025';
            $mutasi->tanggal_mutasi = now();
            $mutasi->alamat_tujuan = 'Jakarta Selatan';
            $mutasi->alasan_mutasi = 'Pindah domisili';
            $mutasi->catatan = 'Test surat mutasi';
            
            // Buat data anggota dummy
            $anggota = new \App\Models\Anggota();
            $anggota->nama_lengkap = 'John Doe';
            $anggota->no_telepon = '08123456789';
            $anggota->tempat_lahir = 'Jakarta';
            $anggota->tanggal_lahir = '1990-01-01';
            $anggota->jenjang_anggota = 'Kader';
            $anggota->pendidikan = 'S1';
            $anggota->pembimbing_nama = 'Ahmad Yani';
            $anggota->pembimbing_telepon = '08123456789';
            
            $mutasi->anggota = $anggota;
            
            // Buat data struktur dummy
            $struktur = new \App\Models\StrukturOrganisasi();
            $struktur->nama_struktur = 'DPC Bandung';
            $mutasi->strukturKe = $struktur;
        }
        
        $data = [
            'nomor_surat' => $mutasi->nomor_sk ?? '006/D/Mts/A1-04-PKS/IX/2025',
            'tanggal' => now()->format('d-m-Y'),
            'mutasi' => $mutasi,
            'anggota' => $mutasi->anggota,
            'dpc_tujuan' => $mutasi->strukturKe,
            'ketua_kaderisasi' => 'H. Indarmawan, Ak'
        ];
        
        $pdf = PDF::loadView('surat.mutasi-keluar-base64', $data);
        $pdf->setPaper('A4', 'portrait');
        $pdf->setOptions([
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled' => false,
            'isPhpEnabled' => false,
            'isJavascriptEnabled' => false,
            'defaultFont' => 'Arial',
            'dpi' => 150,
            'enable_font_subsetting' => false,
            'isFontSubsettingEnabled' => false,
        ]);
        
        return $pdf->download("Surat_Mutasi_Keluar_Base64.pdf");
    })->name('test.pdf-base64');
    
    // Test route untuk debug UPA data
    Route::get('/test-upa-data', function() {
        $upas = \App\Models\Upa::with(['dpc'])->where('status', 'Aktif')->get();
        return response()->json([
            'total_upas' => $upas->count(),
            'upas' => $upas->map(function($upa) {
                return [
                    'upa_id' => $upa->upa_id,
                    'nama_upa' => $upa->nama_upa,
                    'kode_upa' => $upa->kode_upa,
                    'dpc_id' => $upa->dpc_id,
                    'dpc_nama' => $upa->dpc ? $upa->dpc->nama_dpc : 'N/A'
                ];
            })
        ]);
    })->name('test.upa-data');
    
    // Test route untuk debug anggota UPA
    Route::get('/test-anggota-upa', function() {
        $kodeUpa = request('kode_upa', 'UPA001');
        $upa = \App\Models\Upa::where('kode_upa', $kodeUpa)->first();
        
        if (!$upa) {
            return response()->json(['error' => 'UPA not found']);
        }
        
        $anggota = \App\Models\Anggota::where('upa_id', $upa->upa_id)
                                     ->where('status_keanggotaan', 'Aktif')
                                     ->orderBy('nama_lengkap')
                                     ->get(['id', 'nama_lengkap', 'no_telepon']);
        
        return response()->json([
            'kode_upa' => $kodeUpa,
            'upa_id' => $upa->upa_id,
            'total_anggota' => $anggota->count(),
            'anggota' => $anggota
        ]);
    })->name('test.anggota-upa');
    
    // Test route untuk debug API endpoint
    Route::get('/test-api-debug', function() {
        $controller = new \App\Http\Controllers\UpaGroupActivityController();
        $request = new \Illuminate\Http\Request(['kode_upa' => 'UPA001']);
        
        try {
            $response = $controller->getAnggotaUpa($request);
            return response()->json([
                'status' => 'success',
                'data' => $response->getData()
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    })->name('test.api-debug');
    
    // Test route untuk surat penempatan
    Route::get('/test-surat-penempatan', function() {
        // Ambil data anggota pertama yang aktif
        $anggota = \App\Models\Anggota::with(['refJenjang', 'dpc', 'upa', 'refGrupUpa'])
            ->where('status_keanggotaan', 'Aktif')
            ->first();
            
        if (!$anggota) {
            // Buat data dummy jika tidak ada anggota
            $anggota = new \App\Models\Anggota();
            $anggota->nomor_identitas_anggota = '123456';
            $anggota->nama_lengkap = 'ABCD';
            $anggota->no_telepon = '0813665466644';
            $anggota->jenjang_anggota = 'Madya';
            $anggota->dpc = new \App\Models\Dpc();
            $anggota->dpc->nama_dpc = 'DPC Kramat Jati';
        }
        
        // Ambil UPA pertama
        $upa = \App\Models\Upa::with(['dpc', 'pembimbingAktif'])->first();
        if (!$upa) {
            $upa = new \App\Models\Upa();
            $upa->kode_upa = 'UPA001';
            $upa->nama_upa = 'UPA Cipayung';
            $upa->dpc = new \App\Models\Dpc();
            $upa->dpc->nama_dpc = 'Cipayung';
        }
        
        // Buat data pembimbing
        $pembimbingBaru = new \App\Models\Anggota();
        $pembimbingBaru->nama_lengkap = 'XYZ';
        $pembimbingBaru->no_telepon = '081512245644';
        
        $pembimbingLama = new \App\Models\Anggota();
        $pembimbingLama->nama_lengkap = 'ABCD';
        $pembimbingLama->no_telepon = '08264654644';
        
        $data = [
            'nomor_surat' => '002/D/Mts/A1-04-PKS/VII/2025',
            'tanggal' => now()->format('d-m-Y'),
            'anggota' => $anggota,
            'upa' => $upa,
            'pembimbing_baru' => $pembimbingBaru,
            'pembimbing_lama' => $pembimbingLama,
            'tahun_pelantikan' => '2025-06-21',
            'catatan' => '',
            'ketua_kaderisasi' => 'H. Indarmawan, Ak'
        ];
        
        return view('surat.penempatan-upa', $data);
    })->name('test.surat-penempatan');
}); // End of auth middleware group