<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AccessLogController;
use App\Http\Controllers\Api\BiometricController;

/* |-------------------------------------------------------------------------- | API Routes for ESP32 Biometric Door |-------------------------------------------------------------------------- */

Route::post('/train-user', [BiometricController::class , 'trainUser']);

Route::post('/access-log', [AccessLogController::class , 'store']);

Route::get('/logs', function (\Illuminate\Http\Request $request) {

    $perPage = max(1, (int) $request->get('per_page', 50));
    $page    = max(1, (int) $request->get('page', 1));
    $status  = $request->get('status', 'all');
    $name    = trim($request->get('name', ''));

    // Buat dua query terpisah agar count() tidak mempengaruhi get()
    $buildBase = function () use ($status, $name) {
        $q = \App\Models\AccessLog::query();

        if ($status === 'success') {
            $q->whereRaw("LOWER(status) IN ('success', 'sukses', 'open')");
        } elseif ($status === 'failed') {
            $q->whereRaw("LOWER(status) NOT IN ('success', 'sukses', 'open')");
        }

        if ($name !== '') {
            $q->whereHas('user', function ($sub) use ($name) {
                $sub->whereRaw('LOWER(name) LIKE ?', ['%' . strtolower($name) . '%']);
            });
        }

        return $q;
    };

    $total = $buildBase()->count();

    $logs = $buildBase()
        ->with('user')
        ->latest('access_time')
        ->skip(($page - 1) * $perPage)
        ->take($perPage)
        ->get();

    return response()->json([
        'data'        => $logs,
        'total'       => $total,
        'page'        => $page,
        'per_page'    => $perPage,
        'total_pages' => (int) ceil($total / $perPage),
    ]);

});

Route::get('/logs/summary', function () {

    return response()->json([
    'total' => \App\Models\AccessLog::count(),
    'success' => \App\Models\AccessLog::whereRaw('LOWER(status) IN (?, ?)', ['success', 'sukses'])->count(),
    'failed' => \App\Models\AccessLog::whereRaw('LOWER(status) IN (?, ?)', ['failed', 'gagal'])->count(),
    ]);

});

Route::delete('/logs', function () {

    \App\Models\AccessLog::truncate();

    return response()->json([
    "message" => "all logs deleted"
    ]);

});