<?php

namespace App\Http\Controllers\Admin\Hr;

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

class ScheduleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Schedule::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('schedule_date', '>=', $v));
        $query->when($request->end_date, fn($q, $v) => $q->where('schedule_date', '<=', $v));

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

    public function store(Request $request): JsonResponse
    {
        $v = $request->validate([
            'user_id' => 'required|exists:users,id',
            'schedule_date' => 'required|date',
            'shift_type' => 'required|integer|in:1,2,3,4,5',
            'start_time' => 'nullable|date_format:H:i',
            'end_time' => 'nullable|date_format:H:i',
        ]);

        $schedule = Schedule::updateOrCreate(
            ['user_id' => $v['user_id'], 'schedule_date' => $v['schedule_date']],
            $v
        );

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