<?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\LandingController;
use App\Http\Controllers\ForcedPasswordChangeController;
use App\Http\Controllers\Admin\RequestItemController;
use App\Http\Controllers\ItemRequestController;
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('/', [LandingController::class, 'index'])->name('landing');



# 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('wajib-ganti-password', [ForcedPasswordChangeController::class, 'edit'])->name('password.force.edit');
    Route::put('wajib-ganti-password', [ForcedPasswordChangeController::class, 'update'])->name('password.force.update');

    Route::get('item-requests', [ItemRequestController::class, 'index'])->name('item-requests.index');
    Route::get('item-requests/create', [ItemRequestController::class, 'create'])->name('item-requests.create');
    Route::get('item-requests/items/{requestItem}', [ItemRequestController::class, 'showItem'])->name('item-requests.items.show');
    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);

    // Borrow flow (multi-step)
    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::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');
    Route::get('/borrow/create', [BorrowRequestController::class, 'create'])->name('borrow.create');
    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');

    // 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');

    // Reports
    Route::middleware('role:sekretariat,kepala_bidang')->group(function () {
        Route::get('reports', [ReportController::class, 'index'])->name('reports.index');
        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:staff_bidang,kepala_bidang')->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/booking', [VehicleController::class, 'storeBooking'])->name('vehicles.booking.store');
    Route::middleware('role:sekretariat')->group(function () {
        Route::post('vehicles/store', [VehicleController::class, 'storeVehicle'])->name('vehicles.store');
        Route::get('vehicles/create', [VehicleController::class, 'create'])->name('vehicles.create');
        Route::get('vehicles/{id}/edit', [VehicleController::class, 'edit'])->name('vehicles.edit');
        Route::put('vehicles/{id}', [VehicleController::class, 'update'])->name('vehicles.update');
        Route::delete('vehicles/{id}', [VehicleController::class, 'destroy'])->name('vehicles.destroy');
    });

    # --- 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');

    # --- 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:staff_bidang,kepala_bidang');

        // 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');
});
