<?php

namespace App\Http\Controllers\Admin\Hr;

use App\Http\Controllers\Controller;
use App\Models\Hr\AttendanceRecord;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttendanceRecordController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = AttendanceRecord::query()->with('user');
        $query->when($request->user_id, fn($q, $v) => $q->where('user_id', $v));
        $query->when($request->start_date, fn($q, $v) => $q->where('attendance_date', '>=', $v));
        $query->when($request->end_date, fn($q, $v) => $q->where('attendance_date', '<=', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->latest('attendance_date')->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $v = $request->validate([
            'user_id' => 'required|exists:users,id',
            'attendance_date' => 'required|date',
            'clock_in' => 'nullable|date_format:H:i',
            'clock_out' => 'nullable|date_format:H:i',
            'status' => 'nullable|integer|in:1,2,3,4,5',
            'overtime_hours' => 'nullable|numeric|min:0',
            'remark' => 'nullable|string|max:255',
        ]);

        return $this->success(AttendanceRecord::create($v));
    }

    public function clockIn(): JsonResponse
    {
        $record = AttendanceRecord::firstOrCreate(
            ['user_id' => auth()->id(), 'attendance_date' => now()->toDateString()],
            ['status' => 1]
        );
        $record->update(['clock_in' => now()->format('H:i:s')]);

        return $this->success($record);
    }

    public function clockOut(): JsonResponse
    {
        $record = AttendanceRecord::where('user_id', auth()->id())
            ->where('attendance_date', now()->toDateString())
            ->first();

        if (!$record) {
            return $this->error('今日未打卡上班', 40001);
        }
        $record->update(['clock_out' => now()->format('H:i:s')]);

        return $this->success($record);
    }
}
