<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\PasienController;
use App\Http\Controllers\PasienRiwayatController;
use App\Http\Controllers\DokterController;
use App\Http\Controllers\PemeriksaanKesehatanController;
use App\Http\Controllers\FaceRecognitionController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PengaturanController;
use App\Http\Controllers\LaporanController;
// use App\Http\Controllers\NotifikasiController; // TODO: buat controller ini
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\DokterDashboardController;
use App\Http\Controllers\AdminDashboardController;
use App\Http\Controllers\KonsultasiController;   // ← TAMBAHAN
use App\Http\Controllers\PembayaranController;   // ← TAMBAHAN
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\LoginStatusController;
use App\Http\Controllers\Auth\LockedUsersController;
use App\Http\Controllers\AiChatController;

/*
|--------------------------------------------------------------------------
| Public Routes
|--------------------------------------------------------------------------
*/
Route::middleware('throttle:30,1')->post('/ai/chat', [AiChatController::class, 'chat'])->name('ai.chat');
Route::get('/auth/google', [AuthenticatedSessionController::class, 'redirectToGoogle'])
    ->name('auth.google');

Route::get('/auth/google/callback', [AuthenticatedSessionController::class, 'handleGoogleCallback'])
    ->name('auth.google.callback');

Route::get('/', [WelcomeController::class, 'index'])->name('welcome');
Route::post('/login/status', [LoginStatusController::class, 'check'])
    ->middleware('guest')
    ->name('login.status');
/*
|--------------------------------------------------------------------------
| Dashboard Route - Role Based Redirect (Email Must Be Verified)
|--------------------------------------------------------------------------
*/
Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware(['auth', 'verified'])
    ->name('dashboard');

/*
|--------------------------------------------------------------------------
| Profile Routes
|--------------------------------------------------------------------------
*/
Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
    Route::patch('/profile/toggle-2fa', [ProfileController::class, 'toggleTwoFactor'])
    ->name('profile.toggle-2fa');
    // In-App Notifications API for Polling
    Route::prefix('notifications')->name('notifications.')->group(function () {
        Route::get('/unread', [NotificationController::class, 'unread'])->name('unread');
        Route::post('/{id}/mark-as-read', [NotificationController::class, 'markAsRead'])->name('mark-as-read');
        Route::post('/mark-all-as-read', [NotificationController::class, 'markAllAsRead'])->name('mark-all-as-read');
    });
});

/*
|--------------------------------------------------------------------------
| ADMIN Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:admin,super_admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/locked-users',         [LockedUsersController::class, 'index'])  ->name('locked-users.index');
    Route::get('/locked-users/status',  [LockedUsersController::class, 'status']) ->name('locked-users.status');
    Route::post('/locked-users/unlock', [LockedUsersController::class, 'unlock']) ->name('locked-users.unlock');
});
 
Route::middleware(['auth', 'role:admin'])->prefix('admin')->name('admin.')->group(function () {

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

    // User Management
    Route::resource('users', UserController::class);
    Route::post('users/{user}/toggle-status', [UserController::class, 'toggleStatus'])->name('users.toggle-status');

    // Dokter Management
    Route::resource('dokter', DokterController::class);
    Route::get('dokter/{dokter}/jadwal',          [DokterController::class, 'jadwal'])      ->name('dokter.jadwal');
    Route::post('dokter/{dokter}/assign-pasien',  [DokterController::class, 'assignPasien'])->name('dokter.assign-pasien');
    Route::get('dokter/statistik/overview',       [DokterController::class, 'statistik'])   ->name('dokter.statistik');

    // Pengaturan
    Route::prefix('pengaturan')->name('pengaturan.')->group(function () {
        Route::get('/',                 [PengaturanController::class, 'index'])         ->name('index');
        Route::put('/update',           [PengaturanController::class, 'update'])        ->name('update');
        Route::post('/test-whatsapp',   [PengaturanController::class, 'testWhatsapp'])  ->name('test-whatsapp');
        Route::post('/test-ai',         [PengaturanController::class, 'testAi'])        ->name('test-ai');
        Route::post('/test-face-ai',    [PengaturanController::class, 'testFaceAi'])    ->name('test-face-ai');
    });

    // Laporan & Statistik
    Route::prefix('laporan')->name('laporan.')->group(function () {
        Route::get('/',         [LaporanController::class, 'index'])        ->name('index');
        Route::get('/harian',   [LaporanController::class, 'harian'])       ->name('harian');
        Route::get('/bulanan',  [LaporanController::class, 'bulanan'])      ->name('bulanan');
        Route::get('/pasien',   [LaporanController::class, 'laporanPasien'])->name('pasien');
        Route::get('/dokter',   [LaporanController::class, 'laporanDokter'])->name('dokter');
        Route::post('/export',  [LaporanController::class, 'export'])       ->name('export');
    });

    // Notifikasi - TODO: buat NotifikasiController dulu
    // Route::prefix('notifikasi')->name('notifikasi.')->group(function () { ... });

    // ── KONSULTASI (Admin) ────────────────────────────────────────────────────
    // Alur admin: lihat semua konsultasi, buat konsultasi baru, lihat detail
    Route::prefix('konsultasi')->name('konsultasi.')->group(function () {
        Route::get('/',         [KonsultasiController::class, 'adminIndex'])  ->name('index');
        Route::get('/buat',     [KonsultasiController::class, 'adminCreate']) ->name('create');
        Route::post('/buat',    [KonsultasiController::class, 'adminStore'])  ->name('store');
        Route::get('/{id}',     [KonsultasiController::class, 'adminShow'])   ->name('show');
    });

    // ── PEMBAYARAN (Admin) ────────────────────────────────────────────────────
    // Alur admin: lihat semua tagihan, buat tagihan dari konsultasi SELESAI_KONSUL,
    //             konfirmasi bayar, batalkan, cetak kuitansi
    Route::prefix('pembayaran')->name('pembayaran.')->group(function () {
    Route::get('/',                              [PembayaranController::class, 'index'])            ->name('index');
    Route::get('/konsultasi-selesai',            [PembayaranController::class, 'konsultasiSelesai'])->name('konsultasi-selesai'); // ← BARU
    Route::get('/buat/{konsultasiId}',           [PembayaranController::class, 'create'])           ->name('create');
    Route::post('/buat',                         [PembayaranController::class, 'store'])             ->name('store');
    Route::get('/{id}',                          [PembayaranController::class, 'show'])              ->name('show');
    Route::post('/{id}/konfirmasi',              [PembayaranController::class, 'konfirmasi'])        ->name('konfirmasi');
    Route::post('/{id}/batal',                   [PembayaranController::class, 'batal'])             ->name('batal');
    Route::post('/{id}/upload-bukti',            [PembayaranController::class, 'uploadBuktiBayar']) ->name('upload-bukti');
    Route::get('/{id}/kuitansi',                 [PembayaranController::class, 'kuitansi'])          ->name('kuitansi');
});
 
});

/*
|--------------------------------------------------------------------------
| DOKTER Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:dokter'])->prefix('dokter')->name('dokter.')->group(function () {

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

    // ── KONSULTASI (Dokter) ───────────────────────────────────────────────────
    // Alur dokter: lihat daftar konsultasi yang ditugaskan,
    //              isi hasil (diagnosa, resep, berkas), tandai selesai
    Route::prefix('konsultasi')->name('konsultasi.')->group(function () {
        Route::get('/',                     [KonsultasiController::class, 'dokterIndex'])   ->name('index');
        Route::get('/{id}/edit',            [KonsultasiController::class, 'dokterEdit'])    ->name('edit');
        Route::put('/{id}',                 [KonsultasiController::class, 'dokterUpdate'])  ->name('update');
        Route::post('/{id}/serahkan',       [KonsultasiController::class, 'serahkanBerkas'])->name('serahkan');
    });

    // Pasien yang Ditangani (halaman lama — tetap ada untuk kompatibilitas)
    Route::get('/pasien-saya',              [DokterDashboardController::class, 'myPatients'])           ->name('my-patients');
    Route::get('/pasien/{pasien}',          [DokterDashboardController::class, 'pasienDetail'])         ->name('pasien.detail');

    // Update Penanganan Pasien (halaman lama — tetap ada, tapi tidak dipakai untuk alur konsultasi)
    Route::get('/pasien/{pasien}/update-penanganan',  [DokterDashboardController::class, 'updatePenangananForm']) ->name('pasien.update-penanganan');
    Route::put('/pasien/{pasien}/update-penanganan',  [DokterDashboardController::class, 'updatePenangananStore'])->name('pasien.update-penanganan.store');

    // Jadwal Kontrol
    Route::get('/jadwal-kontrol',                           [DokterDashboardController::class, 'jadwalKontrol'])      ->name('jadwal-kontrol');
    Route::post('/jadwal-kontrol/{dokterPasien}',           [DokterDashboardController::class, 'updateJadwalKontrol'])->name('update-jadwal');

    // Review Pemeriksaan & Analisis AI
    Route::get('/review',                   [DokterDashboardController::class, 'reviewList'])   ->name('review.index');
    Route::get('/review/{pemeriksaan}',     [DokterDashboardController::class, 'reviewShow'])   ->name('review.show');
    Route::post('/review/{pemeriksaan}',    [DokterDashboardController::class, 'reviewStore'])  ->name('review.store');

    Route::get('/pemeriksaan/{pemeriksaan}/review',  [PemeriksaanKesehatanController::class, 'reviewForm'])    ->name('pemeriksaan.review.form');
    Route::post('/pemeriksaan/{pemeriksaan}/review', [PemeriksaanKesehatanController::class, 'reviewDokter'])  ->name('pemeriksaan.review.store');
    Route::get('pemeriksaan/{id}',                   [PemeriksaanKesehatanController::class, 'show'])          ->name('pemeriksaan.show');

    // Auto Assign
    Route::post('/auto-assign', [DokterDashboardController::class, 'autoAssignPatients'])->name('auto-assign');

    // Analisis AI
    Route::get('/analisis-ai',                  [DokterDashboardController::class, 'analisisAiList'])   ->name('analisis-ai.index');
    Route::get('/analisis-ai/{analisisAi}',     [DokterDashboardController::class, 'analisisAiShow'])   ->name('analisis-ai.show');
    Route::post('/analisis-ai/{analisisAi}/review', [DokterDashboardController::class, 'analisisAiReview'])->name('analisis-ai.review');
});

/*
|--------------------------------------------------------------------------
| PETUGAS Routes
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:petugas,admin,super_admin'])->prefix('petugas')->name('petugas.')->group(function () {

    // ⚠️ WAJIB di atas resource semua
    Route::get('pasien/datatables',           [PasienController::class, 'datatables'])        ->name('pasien.datatables');
    Route::get('pasien/{pasien}/assign',      [PasienController::class, 'assignForm'])        ->name('pasien.assign');
    Route::post('pasien/{pasien}/assign',     [PasienController::class, 'assignToDokter'])    ->name('pasien.assign.store');
    Route::get('pasien/{pasien}/statistik',   [PasienController::class, 'statistik'])         ->name('pasien.statistik');
    Route::get('pasien/{pasien}/riwayat',     [PasienController::class, 'riwayatPemeriksaan'])->name('pasien.riwayat');
    Route::get('pasien/{pasien}/register-face',  [FaceRecognitionController::class, 'showRegisterForm']) ->name('pasien.register-face');
    Route::post('pasien/{pasien}/register-face', [FaceRecognitionController::class, 'registerFace'])     ->name('pasien.register-face.store');
    Route::get('pasien/{pasien}/face-status',    [FaceRecognitionController::class, 'faceStatus'])       ->name('pasien.face-status');

    // Resource PALING BAWAH SENDIRI
    Route::resource('pasien', PasienController::class);
    
    // Pemeriksaan
    Route::prefix('pemeriksaan')->name('pemeriksaan.')->group(function () {
        Route::get('/',                         [PemeriksaanKesehatanController::class, 'index'])          ->name('index');
        Route::get('/datatables',               [PemeriksaanKesehatanController::class, 'datatables'])     ->name('datatables');
        Route::get('/dashboard',                [PemeriksaanKesehatanController::class, 'dashboard'])      ->name('dashboard');
        Route::get('/manual/create',            [PemeriksaanKesehatanController::class, 'createManual'])   ->name('manual.create');
        Route::post('/manual/store',            [PemeriksaanKesehatanController::class, 'storeManual'])    ->name('manual.store');
        Route::post('/scan-face',               [FaceRecognitionController::class, 'scanFaceForCheckup'])  ->name('scan-face');
        Route::get('/{pemeriksaan}',            [PemeriksaanKesehatanController::class, 'show'])            ->name('show');
        Route::post('/{pemeriksaan}/analyze',   [PemeriksaanKesehatanController::class, 'generateAnalisis'])->name('analyze');
        Route::post('/{pemeriksaan}/send-notification', [PemeriksaanKesehatanController::class, 'sendNotification'])->name('send-notification');
    });

    // Face Recognition Utilities
    Route::prefix('face')->name('face.')->group(function () {
        Route::post('/identify', [FaceRecognitionController::class, 'identifyFace'])->name('identify');
        Route::post('/verify',   [FaceRecognitionController::class, 'verifyFace'])  ->name('verify');
    });
});

/*
|--------------------------------------------------------------------------
| API Routes (Internal)
|--------------------------------------------------------------------------
*/
Route::prefix('api/v1')->name('api.')->group(function () {
    Route::prefix('face')->name('face.')->group(function () {
        Route::post('/extract-embedding',   [FaceRecognitionController::class, 'extractEmbedding'])  ->name('extract');
        Route::post('/identify',            [FaceRecognitionController::class, 'identifyFaceApi'])   ->name('identify');
        Route::get('/embeddings',           [FaceRecognitionController::class, 'getAllEmbeddings'])  ->name('embeddings');
    });
});

/*
|--------------------------------------------------------------------------
| Webhook Routes
|--------------------------------------------------------------------------
*/
// Webhook routes - TODO: buat NotifikasiController dulu
// Route::prefix('webhook')->name('webhook.')->group(function () { ... });

/*
|--------------------------------------------------------------------------
| Riwayat Penghapusan Pasien Routes (Admin + Petugas)
|--------------------------------------------------------------------------
*/
Route::middleware(['auth', 'role:petugas,admin,super_admin'])->prefix('pasien')->name('pasien.')->group(function () {
    Route::prefix('riwayat-penghapusan')->name('riwayat-penghapusan.')->group(function () {
        Route::get('/', [PasienRiwayatController::class, 'index'])->name('index');
        Route::get('/datatable', [PasienRiwayatController::class, 'datatable'])->name('datatable');
        Route::get('/{riwayatPenghapusan}', [PasienRiwayatController::class, 'show'])->name('show');
        Route::post('/{riwayatPenghapusan}/restore', [PasienRiwayatController::class, 'restore'])->name('restore');
        Route::post('/{riwayatPenghapusan}/hard-delete', [PasienRiwayatController::class, 'hardDelete'])->name('hard-delete');
    });
});

/*
|--------------------------------------------------------------------------
| Wilayah / IndoRegion Routes
|--------------------------------------------------------------------------
*/
Route::prefix('wilayah')->group(function () {
    Route::get('/regency/{province_id}', function ($province_id) {
        return response()->json(\App\Models\Regency::where('province_id', $province_id)->get());
    });
    Route::get('/district/{regency_id}', function ($regency_id) {
        return response()->json(\App\Models\District::where('regency_id', $regency_id)->get());
    });
    Route::get('/village/{district_id}', function ($district_id) {
        return response()->json(\App\Models\Village::where('district_id', $district_id)->get());
    });
});

Route::prefix('api')->group(function () {
    Route::get('/provinces',                [PasienController::class, 'getProvinces']);
    Route::get('/regencies/{province_id}',  [PasienController::class, 'getRegencies']);
    Route::get('/districts/{regency_id}',   [PasienController::class, 'getDistricts']);
    Route::get('/villages/{district_id}',   [PasienController::class, 'getVillages']);
});

/*
|--------------------------------------------------------------------------
| CAPTCHA Routes
|--------------------------------------------------------------------------
*/
Route::get('/captcha/{checksum}', function ($checksum) {
    // Serve CAPTCHA image
    $captcha = \Illuminate\Support\Facades\Session::get('captcha', []);
    
    // Verify checksum and return image
    if (isset($captcha['checksum']) && $captcha['checksum'] === $checksum && isset($captcha['text'])) {
        header('Content-Type: image/png');
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        echo \App\Services\CaptchaService::renderImage($captcha['text']);
        exit;
    }
    
    // Return 404 if invalid
    abort(404);
})->middleware('web')->name('captcha.image');

Route::post('/captcha-refresh', function () {
    // Generate new CAPTCHA for AJAX refresh
    $checksum = \App\Services\CaptchaService::generateCaptcha();
    return response()->json(['checksum' => $checksum]);
})->middleware('web')->name('captcha.refresh');

/*
|--------------------------------------------------------------------------
| Auth Routes (Laravel Breeze)
|--------------------------------------------------------------------------
*/
require __DIR__.'/auth.php';