<?php

namespace App\Http\Controllers;

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

class CourseController extends Controller
{
    public function index(): View
    {
        $courses = Course::latest()->get();
        return view('courses.index', compact('courses'));
    }

    public function create(): View
    {
        return view('courses.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'code' => 'required|unique:courses,code|max:50',
            'name' => 'required|max:255',
        ]);

        Course::create($request->only([
            'code',
            'name',
            'type',
            'start_date',
            'end_date',
            'description',
            'status',
        ]));

        return redirect()->route('courses.index')
            ->with('success', 'Đã thêm khóa đào tạo thành công.');
    }

    public function show(Course $course): View
    {
        return view('courses.show', compact('course'));
    }

    public function edit(Course $course): View
    {
        return view('courses.edit', compact('course'));
    }

    public function update(Request $request, Course $course): RedirectResponse
    {
        $request->validate([
            'code' => 'required|max:50|unique:courses,code,' . $course->id,
            'name' => 'required|max:255',
        ]);

        $course->update($request->only([
            'code',
            'name',
            'type',
            'start_date',
            'end_date',
            'description',
            'status',
        ]));

        return redirect()->route('courses.index')
            ->with('success', 'Đã cập nhật khóa đào tạo thành công.');
    }

    public function destroy(Course $course): RedirectResponse
    {
        $course->delete();

        return redirect()->route('courses.index')
            ->with('success', 'Đã xóa khóa đào tạo thành công.');
    }
}