<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TokenController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\Admin\DepartmentController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\CategoryController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    if (auth()->check()) {
        return redirect()->route('dashboard');
    }
    return redirect()->route('login');
});

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

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::resource('tokens', TokenController::class);
    Route::post('tokens/{token}/approve', [TokenController::class, 'approve'])->name('tokens.approve');
    Route::post('tokens/{token}/decline', [TokenController::class, 'decline'])->name('tokens.decline');
    Route::get('tokens/{token}/summary-pdf', [TokenController::class, 'downloadSummary'])->name('tokens.summary-pdf');

    Route::get('notifications', [NotificationController::class, 'index'])->name('notifications.index');
    Route::post('notifications/{notification}/mark-read', [NotificationController::class, 'markRead'])->name('notifications.mark-read');
    Route::post('notifications/mark-all-read', [NotificationController::class, 'markAllRead'])->name('notifications.mark-all-read');
});

Route::middleware(['auth', 'admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::resource('departments', DepartmentController::class);
    Route::resource('users', UserController::class);
    Route::resource('categories', CategoryController::class);
    Route::post('categories/{category}/stages', [CategoryController::class, 'updateStages'])->name('categories.updateStages');

    // AJAX helpers for the dynamic stage builder
    Route::get('ajax/roles', function (\Illuminate\Http\Request $r) {
        return \App\Models\User::query()
            ->where('department_id', '=', $r->integer('department_id'))
            ->whereNotNull('designation')
            ->where('designation', '!=', '')
            ->distinct()
            ->orderBy('designation')
            ->pluck('designation');
    })->name('ajax.roles');

    Route::get('ajax/users', function (\Illuminate\Http\Request $r) {
        return \App\Models\User::query()
            ->where('department_id', '=', $r->integer('department_id'))
            ->where('designation', '=', $r->string('role'))
            ->orderBy('name')
            ->get(['id', 'name', 'employee_id']);
    })->name('ajax.users');
});

require __DIR__.'/auth.php';
