<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

Route::get('/', function () {
    return view('welcome');
});

// Authentication Routes
Route::get('/login', function () {
    return view('auth.login');
})->name('login')->middleware('guest');

Route::post('/login', function (Illuminate\Http\Request $request) {
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (Auth::attempt($credentials, $request->boolean('remember'))) {
        $request->session()->regenerate();
        return redirect()->intended('/absensi');
    }

    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
})->name('login.post')->middleware('guest');

Route::post('/logout', function (Illuminate\Http\Request $request) {
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return redirect('/');
})->name('logout')->middleware('auth');

// Protected Routes
Route::middleware('auth')->group(function () {
    Route::get('/absensi', function () {
        return view('attendance');
    })->name('attendance');

    // API Routes for authenticated users
    Route::get('/api/attendances', [App\Http\Controllers\AttendanceController::class, 'index']);
    Route::post('/api/attendances', [App\Http\Controllers\AttendanceController::class, 'store']);
    // Route::patch('/api/attendances/{id}/score', [App\Http\Controllers\AttendanceController::class, 'updateScore'])->middleware('role:teacher'); // --- IGNORE ---hanya guru saja yang boleh ngasih nilai
    Route::patch('/api/attendances/{id}/score', [App\Http\Controllers\AttendanceController::class, 'updateScore']);
    Route::delete('/api/attendances/{id}', [App\Http\Controllers\AttendanceController::class, 'destroy']);
});
