<?php

namespace App\Http\Controllers;

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

class SubjectController extends Controller
{
    public function index()
    {
        $subjects = Subject::latest()->get();
        return view('pages.referensi.mapel.index', compact('subjects'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:subjects,code', // Kode harus unik
        ]);

        Subject::create([
            'name' => $request->name,
            'code' => strtoupper($request->code), // Paksa jadi huruf besar
        ]);

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

    public function update(Request $request, $id)
    {
        $subject = Subject::findOrFail($id);
        
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:subjects,code,'.$subject->id, // Unik kecuali punya sendiri
        ]);

        $subject->update([
            'name' => $request->name,
            'code' => strtoupper($request->code),
        ]);

        return back()->with('success', 'Data berhasil diperbarui');
    }

    public function destroy($id)
    {
        $subject = Subject::findOrFail($id);
        
        // Opsional: Cek apakah mapel ini sedang dipakai di Prota/Modul agar tidak error
        // if($subject->annualPrograms()->count() > 0) { ... }
        
        $subject->delete();
        return back()->with('success', 'Mata Pelajaran dihapus');
    }
}