<?php

namespace App\Http\Controllers;

use App\Http\Requests\CoursewareCategoryRequest;
use App\Models\CoursewareCategory;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class CoursewareCategoryController extends Controller
{
    public function index(): View
    {
        $this->authorize('viewAny', CoursewareCategory::class);

        $categories = CoursewareCategory::query()
            ->withCount('coursewarePartners')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(15);
        $page_title = 'Courseware Categories';
        $page_description = 'Manage courseware categories';

        return view('iqec.courseware-categories.index', compact('categories', 'page_title', 'page_description'));
    }

    public function create(): View
    {
        $this->authorize('create', CoursewareCategory::class);

        $page_title = 'Add Category';
        $page_description = 'Create a courseware category';

        return view('iqec.courseware-categories.create', compact('page_title', 'page_description'));
    }

    public function store(CoursewareCategoryRequest $request): RedirectResponse
    {
        CoursewareCategory::create([
            'name' => $request->name,
            'slug' => CoursewareCategory::uniqueSlug($request->name),
            'sort_order' => (int) CoursewareCategory::max('sort_order') + 1,
            'is_active' => $request->boolean('is_active'),
        ]);

        return redirect()->route('courseware-categories.index')->with('success', 'Category created.');
    }

    public function edit(CoursewareCategory $coursewareCategory): View
    {
        $this->authorize('update', $coursewareCategory);

        $page_title = 'Edit Category';
        $page_description = $coursewareCategory->name;

        return view('iqec.courseware-categories.edit', compact('coursewareCategory', 'page_title', 'page_description'));
    }

    public function update(CoursewareCategoryRequest $request, CoursewareCategory $coursewareCategory): RedirectResponse
    {
        $this->authorize('update', $coursewareCategory);

        $coursewareCategory->update([
            'name' => $request->name,
            'slug' => CoursewareCategory::uniqueSlug($request->name, $coursewareCategory->id),
            'is_active' => $request->boolean('is_active'),
        ]);

        return redirect()->route('courseware-categories.index')->with('success', 'Category updated.');
    }

    public function destroy(CoursewareCategory $coursewareCategory): RedirectResponse
    {
        $this->authorize('delete', $coursewareCategory);

        $coursewareCategory->delete();

        return redirect()->route('courseware-categories.index')->with('success', 'Category deleted.');
    }
}
