57 lines
1.6 KiB
PHP
57 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Habit;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Carbon;
|
|
|
|
class HabitController extends Controller
|
|
{
|
|
public function index(): JsonResponse
|
|
{
|
|
return response()->json(Habit::all()->toArray());
|
|
}
|
|
|
|
public function get(int $id): JsonResponse
|
|
{
|
|
return response()->json(Habit::find($id)->toArray());
|
|
}
|
|
|
|
public function create(Request $request): JsonResponse
|
|
{
|
|
$habit = Habit::create([
|
|
'name' => $request->get('name'),
|
|
'description' => $request->get('description'),
|
|
'target_count' => $request->get('targetCount'),
|
|
'current_count' => 0
|
|
]);
|
|
|
|
return response()->json($habit->toArray());
|
|
}
|
|
|
|
public function currentCountUpdate(Request $request, int $id): JsonResponse
|
|
{
|
|
$habit = Habit::find($id);
|
|
$completions = $habit->completions ?? [];
|
|
$date = Carbon::now()->startOfDay()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
|
|
|
|
if (in_array($date, $completions)) {
|
|
return response()->json(['message' => 'Привычка уже отмечена сегодня'], Response::HTTP_UNPROCESSABLE_ENTITY);
|
|
}
|
|
|
|
$habit->current_count += 1;
|
|
$completions[] = Carbon::now()->startOfDay()->format(Carbon::DEFAULT_TO_STRING_FORMAT);
|
|
$habit->completions = $completions;
|
|
|
|
if ($habit->current_count >= $habit->target_count) {
|
|
$habit->is_completed = true;
|
|
}
|
|
$habit->save();
|
|
|
|
return response()->json($habit->toArray());
|
|
}
|
|
}
|