<?php

namespace App\Http\Controllers\Admin\Hr;

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

class LeaveRequestController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = LeaveRequest::query()->with('user');
        $query->when($request->user_id, fn($q, $v) => $q->where('user_id', $v));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

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

    public function store(Request $request): JsonResponse
    {
        $v = $request->validate([
            'user_id' => 'required|exists:users,id',
            'type' => 'required|integer|in:1,2,3,4,5,6',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'days' => 'required|numeric|min:0.5',
            'reason' => 'nullable|string',
        ]);
        $v['status'] = 0;

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

    public function show(LeaveRequest $leaveRequest): JsonResponse
    {
        return $this->success($leaveRequest->load(['user', 'auditor']));
    }

    public function update(Request $request, LeaveRequest $leaveRequest): JsonResponse
    {
        if ($leaveRequest->status !== 0) {
            return $this->error('已审批的申请不可修改', 40001);
        }
        $v = $request->validate([
            'type' => 'sometimes|integer|in:1,2,3,4,5,6',
            'start_date' => 'sometimes|date',
            'end_date' => 'sometimes|date|after_or_equal:start_date',
            'days' => 'sometimes|numeric|min:0.5',
            'reason' => 'nullable|string',
        ]);
        $leaveRequest->update($v);

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

    public function destroy(LeaveRequest $leaveRequest): JsonResponse
    {
        if ($leaveRequest->status !== 0) {
            return $this->error('已审批的申请不可删除', 40001);
        }
        $leaveRequest->delete();

        return $this->success(null);
    }

    public function audit(Request $request, LeaveRequest $leaveRequest): JsonResponse
    {
        if ($leaveRequest->status !== 0) {
            return $this->error('该申请已审批', 40001);
        }
        $v = $request->validate([
            'status' => 'required|integer|in:1,2',
        ]);
        $leaveRequest->update([
            'status' => $v['status'],
            'audit_user_id' => auth()->id(),
            'audit_at' => now(),
        ]);

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