<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ItemController;
use App\Http\Controllers\BorrowRequestController;
use App\Http\Controllers\VerificationController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\RoomController;
use App\Http\Controllers\ReturnController;
use App\Http\Controllers\HistoryController;
use App\Http\Controllers\VehicleController;
use App\Http\Controllers\Admin\RequestItemController;
use App\Http\Controllers\ItemRequestController;
use App\Models\ItemRequest;
// Don't forget to import ReturnController

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\File;

if (app()->environment('local')) {
    Route::get('/__qa/login/{user}', function (\App\Models\User $user) {
        \Illuminate\Support\Facades\Auth::login($user);
        request()->session()->regenerate();

        return redirect()->route('dashboard');
    })->name('qa.login');
}

Route::get('/storage/{filename}', function ($filename) {
    // Cari file di folder storage/app/public
    $path = storage_path('app/public/' . $filename);

    // Jika file tidak ditemukan, tampilkan error 404
    if (!File::exists($path)) {
        abort(404);
    }

    // Ambil file dan tampilkan dengan header yang sesuai (gambar/pdf dll)
    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
})->where('filename', '.*'); // Regex agar bisa membaca sub-folder
Route::get('/', function () {
    return redirect()->route('login');
});



# Auth
Route::get('login', [AuthController::class, 'showLogin'])->name('login');
Route::post('login', [AuthController::class, 'login'])->name('login.post');
Route::get('register', [AuthController::class, 'showRegister'])->name('register');
Route::post('register', [AuthController::class, 'register'])->name('register.post');
Route::post('logout', [AuthController::class, 'logout'])->name('logout');

# Protected
Route::middleware(['auth'])->group(function () {

    Route::get('item-requests', [ItemRequestController::class, 'index'])->name('item-requests.index');
    Route::get('item-requests/create', [ItemRequestController::class, 'create'])->name('item-requests.create');
    Route::post('item-requests', [ItemRequestController::class, 'store'])->name('item-requests.store');

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

    // Items (create/edit/delete only staff & sekretariat)
    Route::resource('items', ItemController::class);
    // Route untuk menampilkan halaman
    Route::get('/items', [ItemController::class, 'index'])->name('items.index');
    // Route untuk memproses penambahan item baru (API)
    Route::post('/items', [ItemController::class, 'store'])->name('items.store');
    Route::get('/items/create', [ItemController::class, 'create'])->name('items.create');

    Route::get('/history', [ReturnController::class, 'index'])->name('history.index');

    // Borrow flow (multi-step)
    Route::get('borrow/select', [BorrowRequestController::class, 'selectItem'])->name('borrow.select');
    Route::post('borrow/select', [BorrowRequestController::class, 'postSelectItem'])->name('borrow.postSelectItem');
    Route::get('borrow/quantity', [BorrowRequestController::class, 'stepQuantity'])->name('borrow.step.quantity');
    Route::post('borrow/quantity', [BorrowRequestController::class, 'storeQuantity'])->name('borrow.storeQuantity');
    Route::get('borrow/date', [BorrowRequestController::class, 'stepDate'])->name('borrow.step.date');
    Route::post('borrow/submit', [BorrowRequestController::class, 'store'])->name('borrow.store');

    Route::get('borrow', [BorrowRequestController::class, 'index'])->name('borrow.index');
    Route::get('borrow/{borrowRequest}', [BorrowRequestController::class, 'show'])->name('borrow.show');
    // Rute untuk menampilkan formulir peminjaman
    Route::get('/borrow/create', [BorrowRequestController::class, 'create'])->name('borrow.create');

    // (duplicate-safe) Rute untuk memproses data dari formulir
    Route::post('/borrow', [BorrowRequestController::class, 'store'])->name('borrow.store');


    Route::get('borrow/{borrowRequest}/edit', [BorrowRequestController::class, 'edit'])->name('borrow.edit');
    Route::put('borrow/{borrowRequest}', [BorrowRequestController::class, 'update'])->name('borrow.update');

    // ACTION ROUTES: approve / reject / return
    // Gunakan PATCH karena mengubah resource (status).
    Route::patch('borrow/{borrowRequest}/approve', [BorrowRequestController::class, 'approve'])->name('borrow.approve');
    Route::patch('borrow/{borrowRequest}/reject',  [BorrowRequestController::class, 'reject'])->name('borrow.reject');
    // 'return' adalah kata kunci di PHP, jadi gunakan method nama berbeda di controller (returnItem)
    Route::patch('borrow/{borrowRequest}/return',  [BorrowRequestController::class, 'returnItem'])->name('borrow.return');

    // Route GET untuk MENAMPILKAN halaman workflow verifikasi
    Route::get('verification', [VerificationController::class, 'index'])->name('verification.index');

    // Route POST tunggal untuk MEMPROSES SEMUA AKSI (approve, reject, revise)
    Route::post('verification/{borrowRequest}/action', [VerificationController::class, 'processAction'])->name('verification.action');

    // === NEW: Route khusus untuk Room Booking Verification ===
    // Menggunakan RoomBooking sebagai parameter binding
    Route::post('verification/room/{roomBooking}/action', [VerificationController::class, 'processRoomAction'])->name('verification.room.action');

    // Verification (role-based)
    Route::post('verification/{borrowRequest}/approve', [VerificationController::class, 'approve'])->name('verification.approve')->middleware('role:staff_bidang,kepala_bidang,sekretariat');
    Route::post('verification/{borrowRequest}/reject', [VerificationController::class, 'reject'])->name('verification.reject')->middleware('role:staff_bidang,kepala_bidang,sekretariat');
    Route::post('verification/{borrowRequest}/revision', [VerificationController::class, 'requestRevision'])->name('verification.revision')->middleware('role:staff_bidang,kepala_bidang');

    // == BAGIAN PROFIL YANG DIPERBAIKI ==
    Route::get('/profile', [ProfileController::class, 'index'])->name('profile.index');
    Route::get('/profile/edit', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::get('/profile/password', [ProfileController::class, 'editPassword'])->name('profile.password');
    Route::put('/profile/password', [ProfileController::class, 'updatePassword'])->name('profile.password.update');
    Route::get('/profile/login-history', [ProfileController::class, 'loginHistory'])->name('profile.login-history');

    // Duplicate-safe borrow select/quantity routes (beberapa sudah didefinisikan di atas)
    Route::get('/borrow/select', [BorrowRequestController::class, 'selectItem'])->name('borrow.select');
    Route::post('/borrow/select', [BorrowRequestController::class, 'postSelectItem'])->name('borrow.post.select');
    Route::get('/borrow/quantity', [BorrowRequestController::class, 'stepQuantity'])->name('borrow.step.quantity');
    Route::post('/borrow/quantity', [BorrowRequestController::class, 'storeQuantity'])->name('borrow.store.quantity');
    Route::post('/borrow/submit', [App\Http\Controllers\BorrowRequestController::class, 'store'])->name('borrow.store');

    // Reports
    Route::get('reports', [ReportController::class, 'index'])->name('reports.index')->middleware('role:sekretariat,kepala_bidang');
    Route::get('reports/export/excel', [ReportController::class, 'exportExcel'])->name('reports.export.excel');
    Route::get('reports/export/pdf', [ReportController::class, 'exportPdf'])->name('reports.export.pdf');

    Route::middleware('role:sekretariat')->group(function () {
        Route::resource('admin/request-items', RequestItemController::class)
            ->names('admin.request-items');
    });

    // Hindari bentrok dengan folder fisik `public/rooms` saat memakai `php artisan serve`
    Route::get('room-management', [RoomController::class, 'index'])->name('rooms.index');
    Route::post('rooms/booking', [RoomController::class, 'storeBooking'])->name('rooms.booking.store');
    Route::middleware('role:sekretariat')->group(function () {
        Route::get('rooms/create', [RoomController::class, 'create'])->name('rooms.create'); // Ditambahkan
        Route::post('room-management/store', [RoomController::class, 'store'])->name('rooms.store');
        Route::get('rooms/{room}/edit', [RoomController::class, 'edit'])->name('rooms.edit');
        Route::put('rooms/{room}', [RoomController::class, 'update'])->name('rooms.update'); // Ditambahkan
        Route::delete('rooms/{room}', [RoomController::class, 'destroy'])->name('rooms.destroy');
    });


    // Hindari bentrok dengan folder fisik `public/vehicles` saat memakai `php artisan serve`
    Route::get('vehicle-management', [VehicleController::class, 'index'])->name('vehicles.index');
    Route::post('vehicles/store', [VehicleController::class, 'storeVehicle'])->name('vehicles.store');
    Route::post('vehicles/booking', [VehicleController::class, 'storeBooking'])->name('vehicles.booking.store');
    Route::get('vehicles/create', [VehicleController::class, 'create'])->name('vehicles.create');
    Route::get('vehicles/{id}/edit', [VehicleController::class, 'edit'])->name('vehicles.edit'); // Tambahkan ini
    Route::put('vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update'); // Tambahkan ini
    Route::delete('vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy'); // Tambahkan ini

    # --- RETURNS & HISTORY (Sinkron dengan Sidebar & View Baru) ---
    // Halaman: Pinjaman Aktif (Barang yang masih dipegang user)
    Route::get('/returns', [ReturnController::class, 'index'])->name('returns.index');
    Route::post('/returns/{id}/submit', [ReturnController::class, 'submitReturn'])->name('returns.submit');

    // Halaman: History Pengembalian (Tampilan yang baru saja kita benarkan)
    // Kita arahkan ke method 'history' di ReturnController
    Route::get('/history', [ReturnController::class, 'history'])->name('history.index');

    # --- VERIFICATION (Aksi Admin/Sekretariat) ---
    Route::prefix('verification')->name('verification.')->group(function () {
        Route::get('/', [VerificationController::class, 'index'])->name('index');

        Route::post('/item-request/{itemRequest}/action', [VerificationController::class, 'processItemRequestAction'])
            ->name('item-request.action')
            ->middleware('role:sekretariat');

        // Verifikasi Peminjaman Baru
        Route::post('/{borrowRequest}/action', [VerificationController::class, 'processAction'])->name('action');
        Route::post('/room/{roomBooking}/action', [VerificationController::class, 'processRoomAction'])->name('room.action');

        // Tambahan rute kendaraan di dalam prefix agar namanya menjadi verification.vehicle.action
        Route::post('/vehicle/action/{id}', [VerificationController::class, 'processVehicleAction'])->name('vehicle.action');

        // Verifikasi Pengembalian (Sekretariat Only)
        Route::middleware('role:sekretariat')->group(function () {
            Route::get('/returns', [ReturnController::class, 'verification'])->name('returns');
            Route::post('/returns/{id}/approve', [ReturnController::class, 'approveReturn'])->name('returns.approve');
        });
    });

    Route::get('/history', [HistoryController::class, 'userIndex'])->name('history.index');

    // Tambahan jika Anda ingin link "Riwayat" di sidebar Sekretariat berbeda:
    Route::get('/admin/history', [HistoryController::class, 'secretariatIndex'])->name('history.admin')->middleware('role:sekretariat');
});
