<?php

namespace App\Http\Controllers;

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

class SubjectController extends Controller
{
    public function index()
    {
        $subjects = Subject::withCount('teachers')->orderBy('name')->get();

        return view('admin.subjects.index', compact('subjects'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'       => 'required|string|max:100',
            'code'       => 'required|string|max:10|unique:subjects,code',
            'is_special' => 'sometimes|boolean',
        ]);

        $validated['is_special'] = $request->boolean('is_special');

        Subject::create($validated);

        return back()->with('success', 'Mata pelajaran berhasil ditambahkan!');
    }

    public function update(Request $request, int $id)
    {
        $subject = Subject::findOrFail($id);

        $validated = $request->validate([
            'name'       => 'required|string|max:100',
            'code'       => 'required|string|max:10|unique:subjects,code,' . $subject->id,
            'is_special' => 'sometimes|boolean',
        ]);

        $validated['is_special'] = $request->boolean('is_special');

        $subject->update($validated);

        return back()->with('success', 'Mata pelajaran berhasil diperbarui!');
    }

    public function destroy(int $id)
    {
        Subject::findOrFail($id)->delete();

        return back()->with('success', 'Mata pelajaran berhasil dihapus.');
    }
}
