<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Response;
use App\Models\Member;
use App\Http\Controllers\Auth\LoginWithEmailController;
use App\Http\Controllers\Auth\RegisterController;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\VerificationController;
use App\Http\Controllers\GoogleController;

use App\Http\Controllers\{
    AuthController,
    AnggotaController,
    BorrowTransactionController,
    StatistikController,
    BackupController
};

use App\Http\Controllers\Admin\{
    DashboardController,
    AnggotaController as AdminAnggotaController,
    PeminjamanController as AdminPeminjamanController,
    KoleksiController as AdminKoleksiController,
    StatistikController as AdminStatistikController,
    SystemController
};

use App\Http\Controllers\User\{
    KoleksiController as UserKoleksiController,
    UserMemberController,
    UserPeminjamanController
};


Route::middleware(['web', StartSession::class])->group(function () {


    Route::get('/welcome', fn() => view('welcome'))->name('welcome');

    Route::get('/', fn() => auth()->check()
        ? redirect()->route('home')
        : redirect()->route('welcome'));

    Route::get('/home', [AuthController::class, 'dashboard'])->middleware('auth')->name('home');
    Route::get('/profile', [AuthController::class, 'profile'])->middleware('auth')->name('profile');

    Route::get('/register', [AuthController::class, 'showRegister'])->name('register');
    Route::post('/register', [AuthController::class, 'register'])->name('register.submit');
    Route::get('/login', [AuthController::class, 'showLogin'])->name('login');
    Route::post('/login', [AuthController::class, 'login'])->name('login.submit');
    Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
    Route::get('/forgot-password', [AuthController::class, 'showForgotPasswordForm'])->name('forgotPassword');
    Route::post('/forgot-password', [AuthController::class, 'sendResetLink'])->name('sendResetLink');

    Route::get('/reset-password/{token}', [AuthController::class, 'showResetPasswordForm'])->name('password.reset');
    Route::post('/reset-password', [AuthController::class, 'resetPassword'])->name('password.update');
    Route::get('/email/verify', function () {
        return view('auth.verify-email');
    })->middleware('auth')->name('verification.notice');

    Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
        $request->fulfill();
        return redirect('/home');
    })->middleware(['auth', 'signed'])->name('verification.verify');

    Route::post('/email/verification-notification', function (Request $request) {
        $request->user()->sendEmailVerificationNotification();
        return back()->with('message', 'Link verifikasi baru telah dikirim!');
    })->middleware(['auth', 'throttle:6,1'])->name('verification.send');

    // Admin Routes

    Route::prefix('admin')->middleware(['auth'])->group(function () {
Route::get('/dashboard-api', [App\Http\Controllers\Admin\DashboardController::class, 'apiData'])->name('admin.dashboard.api');
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('admin.dashboard');
        Route::get('/profile', [AuthController::class, 'profile'])->name('admin.profile');
        Route::post('/profile/update', [AuthController::class, 'updateProfile'])->name('admin.updateProfile');
        Route::post('/profile/password', [AuthController::class, 'updatePassword'])->name('admin.updatePassword');
        Route::get('/security', [AuthController::class, 'adminsecurity'])->name('admin.security');
        Route::post('/admin/check-password', [AuthController::class, 'checkCurrentPassword'])->name('admin.checkPassword');
        Route::post('/profile/update-foto', [AuthController::class, 'updateFoto'])
            ->name('admin.update_foto');
        Route::delete('/profile/delete-foto', [AuthController::class, 'deleteFoto'])
            ->name('admin.delete_foto');

        Route::prefix('anggota')->group(function () {
            Route::get('/', [AdminAnggotaController::class, 'index'])->name('admin.anggota.index');
            Route::get('/create', [AdminAnggotaController::class, 'create'])->name('admin.anggota.create');
            Route::post('/', [AdminAnggotaController::class, 'store'])->name('admin.anggota.store');
            Route::get('/{id}/edit', [AdminAnggotaController::class, 'edit'])->name('admin.anggota.edit');
            Route::put('/{id}', [AdminAnggotaController::class, 'update'])->name('admin.anggota.update');
            Route::delete('/{id}', [AdminAnggotaController::class, 'destroy'])->name('admin.anggota.destroy');
            Route::get('/cetak/{id}', [AdminAnggotaController::class, 'cetak'])->name('admin.anggota.cetak');
            Route::get('/anggota', [App\Http\Controllers\Admin\AnggotaController::class, 'index'])->name('admin.anggota');
            Route::get('/anggota/{id}', [App\Http\Controllers\Admin\AnggotaController::class, 'show'])->name('admin.anggota.show');
            Route::post('/anggota/{id}/approve', [App\Http\Controllers\Admin\AnggotaController::class, 'approve'])->name('admin.anggota.approve');
            Route::post('/anggota/{id}/reject', [App\Http\Controllers\Admin\AnggotaController::class, 'reject'])->name('admin.anggota.reject');
            Route::get('/cetak/{id}/pdf', [AdminAnggotaController::class, 'downloadPdf'])
                ->name('member.kartu.pdf');
            Route::get('/admin/anggota/{id}/pdf', [AdminAnggotaController::class, 'downloadPdf'])
                ->name('admin.anggota.pdf');
            Route::get('/admin/anggota/{id}/print', [AdminAnggotaController::class, 'print'])
                    ->name('admin.anggota.print');
        });

        Route::prefix('koleksi')->group(function () {
            Route::get('/', [AdminKoleksiController::class, 'index'])->name('admin.koleksi.index');
            Route::get('/create', [AdminKoleksiController::class, 'create'])->name('admin.koleksi.create');
            Route::post('/', [AdminKoleksiController::class, 'store'])->name('admin.koleksi.store');
            Route::post('/barcode-multiple', [AdminKoleksiController::class, 'printMultipleBarcode'])->name('admin.koleksi.barcode_multiple');
            Route::get('/{kode_eksemplar}/edit', [AdminKoleksiController::class, 'edit'])->name('admin.koleksi.edit');
            Route::put('/{kode_eksemplar}', [AdminKoleksiController::class, 'update'])->name('admin.koleksi.update');
            Route::delete('/{kode_eksemplar}', [AdminKoleksiController::class, 'destroy'])->name('admin.koleksi.destroy');
            Route::delete('/koleksi/destroy-multiple', [AdminKoleksiController::class, 'destroyMultiple'])->name('admin.koleksi.destroy_multiple');
            Route::get('/{kode_eksemplar}/barcode', [AdminKoleksiController::class, 'printBarcodeSingle'])
                ->name('admin.koleksi.barcode_single');
            

        });

        Route::get('/peminjaman', [AdminPeminjamanController::class, 'index'])->name('admin.peminjaman');
        Route::post('/peminjaman/{id}/setujui', [AdminPeminjamanController::class, 'setujui'])->name('admin.peminjaman.setujui');
        Route::post('/peminjaman/{id}/tolak', [AdminPeminjamanController::class, 'tolak'])->name('admin.peminjaman.tolak');
        Route::post('/peminjaman/{id}/ambil', [AdminPeminjamanController::class, 'ambilBuku'])->name('admin.peminjaman.ambil');
        Route::put('/peminjaman/{id}/kembalikan', [AdminPeminjamanController::class, 'kembalikan'])->name('admin.peminjaman.kembalikan');
        Route::get('/peminjaman/download/{id}', [AdminPeminjamanController::class, 'downloadSuratPengantar'])->name('admin.peminjaman.download');
        Route::post('/peminjaman/{id}/setujui', [AdminPeminjamanController::class, 'setujui'])->name('admin.peminjaman.setujui');
        Route::post('/peminjaman/{id}/tolak', [AdminPeminjamanController::class, 'tolak'])->name('admin.peminjaman.tolak');
        Route::post('/peminjaman/{id}/setujui-pengembalian', [AdminPeminjamanController::class, 'setujuiPengembalian'])
            ->name('admin.peminjaman.setujuiPengembalian');
Route::get('/peminjaman/{id}/cetak-nota', [AdminPeminjamanController::class, 'cetakNota'])->name('admin.peminjaman.nota');
      Route::post('/peminjaman/{id}/setujui-perpanjangan', [AdminPeminjamanController::class, 'setujuiPerpanjangan'])
    ->name('admin.peminjaman.setujui-perpanjangan');

Route::post('/peminjaman/{id}/tolak-perpanjangan', [AdminPeminjamanController::class, 'tolakPerpanjangan'])
    ->name('admin.peminjaman.tolak-perpanjangan');

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

        Route::get('/system', [SystemController::class, 'index'])->name('admin.system');
        Route::post('/system/add', [SystemController::class, 'makeAdmin'])->name('admin.system.add');
        Route::post('/system/remove', [SystemController::class, 'removeAdmin'])->name('admin.system.remove');
        Route::post('/block', [SystemController::class, 'block'])->name('admin.system.block');
        Route::post('/unblock', [SystemController::class, 'unblock'])->name('admin.system.unblock');
    });

    // User Routes
    Route::prefix('user')->middleware(['auth'])->group(function () {
        Route::get('/dashboard', [AuthController::class, 'userDashboard'])->name('user.dashboard');
        Route::get('/profile', [AuthController::class, 'profile'])->name('user.profile');
        Route::post('/profile/update-foto', [AuthController::class, 'updateFoto'])
            ->name('user.update_foto');
        Route::delete('/profile/delete-foto', [AuthController::class, 'deleteFoto'])
            ->name('user.delete_foto');
        Route::get('/koleksi', [UserKoleksiController::class, 'index'])->name('user.koleksi');
        Route::get('/koleksi/search', [UserKoleksiController::class, 'index'])->name('user.koleksi.search');
        Route::get('/api/pengarang', [UserKoleksiController::class, 'getPengarang'])->name('api.pengarang');
        Route::get('/ganti-bahasa/{kode}', [UserKoleksiController::class, 'gantiBahasa'])->name('ganti.bahasa');
        Route::get('/koleksi/{koleksi}', [UserKoleksiController::class, 'show'])->name('user.koleksi.show');

        Route::get('register', [UserMemberController::class, 'create'])->name('user.member.create');
        Route::post('register', [UserMemberController::class, 'store'])->name('user.member.store');
        Route::get('list', [UserMemberController::class, 'index'])->name('user.member.index');
        Route::get('/member/pending', [UserMemberController::class, 'pending'])->name('user.member.pending');
        Route::get('peminjaman', [UserPeminjamanController::class, 'index'])->name('user.peminjaman.index');
        Route::get('peminjaman/create', [UserPeminjamanController::class, 'create'])->name('user.peminjaman.create');
        Route::post('peminjaman', [UserPeminjamanController::class, 'store'])->name('user.peminjaman.store');
        
        
Route::match(['get', 'post'], '/peminjaman/{id}/perpanjang-form', [UserPeminjamanController::class, 'showPerpanjangForm'])
    ->name('user.peminjaman.perpanjang.form');Route::post('/peminjaman/{id}/perpanjang-proses', [UserPeminjamanController::class, 'processPerpanjang'])->name('user.peminjaman.perpanjang.process');
        Route::get('peminjaman/download/{id}', [UserPeminjamanController::class, 'downloadSuratPengantar'])->name('user.peminjaman.download');

        Route::post('peminjaman/{id}/kembalikan', [UserPeminjamanController::class, 'kembalikan'])->name('user.peminjaman.kembalikan');

        Route::get('peminjaman/{id}/penilaian', [UserPeminjamanController::class, 'penilaian'])->name('user.rating.form');
        Route::post('peminjaman/{id}/penilaian', [UserPeminjamanController::class, 'simpanPenilaian'])->name('user.rating.store');

        Route::get('/layanan', fn() => view('user.layanan.index'))->name('user.layanan');
        Route::prefix('layanan')->group(function () {
            Route::get('/referensi', fn() => view('user.layanan.referensi'))->name('user.layanan.referensi');
            Route::get('/peminjaman', fn() => view('user.layanan.peminjaman'))->name('user.layanan.peminjaman');
            Route::get('/digital', fn() => view('user.layanan.digital'))->name('user.layanan.digital');
            Route::get('/informasi', fn() => view('user.layanan.informasi'))->name('user.layanan.informasi');
            Route::get('/kontak-lokasi', fn() => view('user.kontak-lokasi'))->name('user.kontak-lokasi');
            Route::get('/fasilitas', fn() => view('user.fasilitas'))->name('user.fasilitas');
        });
    });

    // API & Public Routes
    Route::get('/members', fn() => Member::all());

    Route::get('/search', function (\Illuminate\Http\Request $request) {
        return redirect()->route('user.koleksi', ['search' => $request->query('search')]);
    })->name('public.search');



    Route::get('/download/surat/{filename}', function ($filename) {
        $path = storage_path('app/public/surat_pengantar/' . $filename);
        if (!file_exists($path))
            abort(404, 'File tidak ditemukan');
        return Response::download($path, $filename, ['Content-Type' => 'application/pdf']);
    })->name('download.surat');
});
Route::prefix('user')->middleware(['auth'])->group(function () {
    Route::get('/profile', [AuthController::class, 'profile'])->name('user.profile');
    Route::post('/profile/update', [AuthController::class, 'updateProfile'])->name('user.updateProfile');
    Route::post('/profile/password', [AuthController::class, 'updatePassword'])->name('user.updatePassword');
    Route::get('/security', [AuthController::class, 'security'])->name('user.security');
    Route::post('/user/check-password', [AuthController::class, 'checkCurrentPassword'])->name('user.checkPassword');
});

// Login via Email Aktif
Route::get('/login/email', [LoginWithEmailController::class, 'showForm'])->name('login.email');
Route::post('/login/email', [LoginWithEmailController::class, 'sendLink'])->name('login.email.send');
Route::get('/login/email/{token}', [LoginWithEmailController::class, 'login'])->name('login.email.token');


Route::get('/verify-email', [AuthController::class, 'showVerifyEmailForm'])->name('verify.email.form');
Route::post('/verify-email', [AuthController::class, 'verifyEmail'])->name('verify.email.submit');
Route::post('/resend-otp', [AuthController::class, 'resendOtp'])->name('resend.otp');

Route::get('/user-foto/{filename}', function ($filename) {
    $path = storage_path('app/public/foto/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    return response()->file($path);
});
Route::prefix('transaksi')->group(function () {

    // halaman utama (opsional)
    Route::get('/iot', function () {
        return view('transaksi.iot');
    });

    // FLOW
    Route::get('/scan-barcode', function () {
        return view('transaksi.scan-barcode');
    });

    Route::get('/detail-buku', function () {
        return view('transaksi.detail-buku');
    });

    Route::get('/scan-rfid', function () {
        return view('transaksi.scan-rfid');
    });

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

    Route::get('/peminjaman-berhasil', function () {
        return view('transaksi.peminjaman-berhasil');
    });
      Route::get('/pengembalian-berhasil', function () {
        return view('transaksi.pengembalian-berhasil');
    });

});
Route::get('/transaksi/detail/{id}', function ($id) {

    $trx = \App\Models\BorrowTransaction::with(['anggota','koleksi'])
        ->findOrFail($id);

    return view('transaksi.detail', compact('trx'));
});
 Route::get('/transaksi/konfirmasi-kembali', function () {
    return view('transaksi.konfirmasi-kembali');
});
// Route untuk mengarahkan ke Google
Route::get('auth/google', [GoogleController::class, 'redirectToGoogle'])->name('login.google');

// Route untuk menerima data balik dari Google
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Route::get('/masuk', function () {
    return '
    <html lang="id">
    <head>
        <title>Menghubungkan ke Pustaka Nawasena...</title>
        <style>
            body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f4f6f9; color: #333; }
            .loader { text-align: center; }
        </style>
    </head>
    <body>
        <div class="loader">
            <h3>Menghubungkan ke Server Bakorwil...</h3>
            <p>Mohon tunggu sebentar, sistem sedang sinkronisasi dengan ESP32.</p>
        </div>
        <script>
            // Memaksa browser mengirim header bypass ke Ngrok sebelum masuk ke halaman utama
            fetch("/", {
                method: "GET",
                headers: { "ngrok-skip-browser-warning": "true" }
            }).then(() => {
                // Begitu sukses tembus, langsung lempar ke halaman login utama
                window.location.href = "/login"; 
            }).catch(() => {
                window.location.href = "/login";
            });
        </script>
    </body>
    </html>
    ';
});

