<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AttendanceController extends Controller
{
    public function live(): JsonResponse
    {
        return response()->json([
            'data' => DB::table('attendance_logs')
                ->where('tenant_id', app('tenant.id'))
                ->latest('punched_at')
                ->limit(50)
                ->get(),
        ]);
    }

    public function rawLogs(): JsonResponse
    {
        return response()->json(['data' => DB::table('attendance_logs')->where('tenant_id', app('tenant.id'))->paginate(50)]);
    }

    public function manualEntry(Request $request): JsonResponse
    {
        $data = $request->validate([
            'employee_id' => ['required', 'integer'],
            'punch_type' => ['required', 'in:check_in,check_out,lunch_in,lunch_out,break_in,break_out,ot_in,ot_out'],
            'punched_at' => ['required', 'date'],
        ]);

        $id = DB::table('attendance_logs')->insertGetId($data + [
            'tenant_id' => app('tenant.id'),
            'auth_mode' => 'manual',
            'created_at' => now(),
        ]);

        return response()->json(['data' => DB::table('attendance_logs')->find($id)], 201);
    }

    public function adjust(Request $request): JsonResponse
    {
        return response()->json([
            'status' => 'pending_approval',
            'data' => $request->all(),
        ], 202);
    }
}
