<?php

namespace App\Http\Controllers;

use App\Models\Batch;
use Illuminate\Http\Request;

class BatchController extends Controller
{
    public function index()
    {
        $batches = Batch::withCount('students')
            ->with(['students.course'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(fn($b) => [
                'id'             => $b->id,
                'name'           => $b->name,
                'start_date'     => $b->start_date->format('Y-m-d'),
                'status'         => $b->status,
                'schedules'      => $b->schedules ?? [],
                'badge_class'    => $b->badge_class,
                'students_count' => $b->students_count,
                'courses'        => $b->students
                    ->pluck('course')
                    ->filter()
                    ->unique('id')
                    ->map(fn($c) => ['id' => $c->id, 'name' => $c->name])
                    ->values(),
            ]);

        return response()->json($batches);
    }

    private function rules(): array
    {
        return [
            'name'            => 'required|string|max:150',
            'start_date'      => 'required|date',
            'status'          => 'required|in:Running,Upcoming,Completed',
            'schedules'       => 'nullable|array',
            'schedules.*.day' => 'nullable|string|max:15',
            'schedules.*.time'=> 'nullable|string|max:10',
        ];
    }

    public function store(Request $request)
    {
        $validated = $request->validate($this->rules());
        $batch = Batch::create($validated);
        return response()->json(['success' => true, 'id' => $batch->id]);
    }

    public function update(Request $request, Batch $batch)
    {
        $validated = $request->validate($this->rules());
        $batch->update($validated);
        return response()->json(['success' => true]);
    }

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