<?php

namespace App\Http\Controllers;

use App\Models\Subtask;
use App\Models\Task;
use Illuminate\Http\Request;

class SubtaskController extends Controller
{
    public function store(Request $request, Task $task)
    {
        $validated = $request->validate([
            'content' => 'required|string|max:255',
        ]);

        $subtask = $task->subtasks()->create([
            'content' => $validated['content'],
            'order_index' => $task->subtasks()->max('order_index') + 1,
        ]);

        if ($request->wantsJson()) {
            return response()->json($subtask);
        }

        return redirect()->back();
    }

    public function toggle(Subtask $subtask)
    {
        $subtask->update([
            'is_completed' => !$subtask->is_completed
        ]);

        return response()->json(['success' => true, 'is_completed' => $subtask->is_completed]);
    }

    public function destroy(Subtask $subtask)
    {
        $subtask->delete();
        return response()->json(['success' => true]);
    }
}
