<?php

namespace App\Http\Controllers;

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

class CourseController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'            => 'required|string|max:150',
            'code'            => 'required|string|max:20|unique:courses,code',
            'duration_months' => 'required|integer|min:1|max:60',
            'status'          => 'required|in:Active,Upcoming,Inactive',
        ]);

        Course::create($validated);

        return response()->json(['success' => true]);
    }

    public function update(Request $request, Course $course)
    {
        $validated = $request->validate([
            'name'            => 'required|string|max:150',
            'code'            => 'required|string|max:20|unique:courses,code,' . $course->id,
            'duration_months' => 'required|integer|min:1|max:60',
            'status'          => 'required|in:Active,Upcoming,Inactive',
        ]);

        $course->update($validated);

        return response()->json(['success' => true]);
    }

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

    public function index()
    {
        $courses = Course::orderBy('created_at', 'desc')->get()->map(function ($c) {
            return [
                'id'              => $c->id,
                'name'            => $c->name,
                'code'            => $c->code,
                'duration_months' => $c->duration_months,
                'status'          => $c->status,
                'initials'        => $c->initials,
                'badge_class'     => $c->badge_class,
            ];
        });

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