<?php

use App\Http\Controllers\Mobile\OtpController;
use App\Http\Controllers\Mobile\RiwayatController;
use App\Http\Controllers\Mobile\UserController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
use App\Http\Controllers\Mobile\AbsenController;
use App\Http\Controllers\Mobile\IzinController;
use App\Http\Controllers\Mobile\UserController as MobileUserController;
use App\Models\User;

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:sanctum');

Route::post('/attendance/verify', [AbsenController::class, 'verify']);
Route::get('/attendance/daily', [AbsenController::class, 'daily']);

// Mobile auth & pengajuan izin routes
Route::prefix('mobile')->group(function () {
    Route::post('/login', [MobileUserController::class, 'login']);
    Route::post('/reset-password', [MobileUserController::class, 'resetPassword']);
    Route::post('/izin', [IzinController::class, 'store']);
});

Route::get('/employees', function () {
    return User::where('status', 'aktif')
        ->select('id', 'name', 'role', 'phone', 'employee_id')
        ->get();
});

// Route untuk mendapatkan data absensi hari ini
Route::get('/attendance/today', function () {
    return User::where('status', 'aktif')
        ->with(['attendances' => function ($query) {
            $query->today();
        }])
        ->get()
        ->map(function ($user) {
            $todayAttendance = $user->todayAttendance();
            return [
                'id' => $user->id,
                'name' => $user->name,
                'role' => $user->role,
                'phone' => $user->phone,
                'employee_id' => $user->employee_id,
                'check_in' => $todayAttendance ? $todayAttendance->check_in : null,
                'check_out' => $todayAttendance ? $todayAttendance->check_out : null,
                'status' => $todayAttendance ? $todayAttendance->status : 'Belum Absen',
            ];
        });
});

// Employee management routes
Route::apiResource('employees', EmployeeController::class);
Route::get('/employees/{employee}/attendance-history', [EmployeeController::class, 'attendanceHistory']);

//baru

//riwayat
Route::get('/riwayat/{userId} ', [RiwayatController::class, 'index']);

//cek email
Route::post('lupa-kata-sandi', [UserController::class, 'lupaKataSandi']);
Route::post('/send-otp', [OtpController::class, 'sendOtp']);
Route::post('/verify-otp', [OtpController::class, 'verifyOtp']);
Route::post('/reset-password', [UserController::class, 'resetPassword']);

//profile
Route::get('/user/{id}', [UserController::class, 'show']);
Route::get('/mobile/riwayat-hari-ini', [UserController::class, 'riwayatHariIni']);
