<?php

namespace App\Http\Controllers;

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

class TeacherController extends Controller
{
    /**
     * Menampilkan daftar guru.
     */
    public function index()
    {
        $teachers = Teacher::with('subjects')->latest()->paginate(20);
        $subjects = Subject::orderBy('name')->get();

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

    /**
     * Menyimpan data guru baru.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'nip'          => 'required|string|max:30|unique:teachers,nip',
            'name'         => 'required|string|max:100',
            'gender'       => 'required|in:L,P',
            'is_homeroom'  => 'sometimes|boolean',
            'phone'        => 'nullable|string|max:20',
            'subject_ids'  => 'nullable|array',
            'subject_ids.*' => 'exists:subjects,id',
        ]);

        $validated['is_homeroom'] = $request->boolean('is_homeroom');
        $subjectIds = $validated['subject_ids'] ?? [];
        unset($validated['subject_ids']);

        $teacher = Teacher::create($validated);
        $teacher->syncSubjects($subjectIds);

        return back()->with('success', 'Data guru berhasil ditambahkan!');
    }

    /**
     * Menampilkan form edit data guru.
     */
    public function edit(int $id)
    {
        $teacher  = Teacher::with('subjects')->findOrFail($id);
        $subjects = Subject::orderBy('name')->get();

        return view('admin.teachers.edit', compact('teacher', 'subjects'));
    }

    /**
     * Memperbarui data guru.
     */
    public function update(Request $request, int $id)
    {
        $teacher = Teacher::findOrFail($id);

        $validated = $request->validate([
            'nip'          => 'required|string|max:30|unique:teachers,nip,' . $teacher->id,
            'name'         => 'required|string|max:100',
            'gender'       => 'required|in:L,P',
            'is_homeroom'  => 'sometimes|boolean',
            'phone'        => 'nullable|string|max:20',
            'subject_ids'  => 'nullable|array',
            'subject_ids.*' => 'exists:subjects,id',
        ]);

        $validated['is_homeroom'] = $request->boolean('is_homeroom');
        $subjectIds = $validated['subject_ids'] ?? [];
        unset($validated['subject_ids']);

        $teacher->update($validated);
        $teacher->syncSubjects($subjectIds);

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

    /**
     * Menghapus data guru.
     */
    public function destroy(int $id)
    {
        Teacher::findOrFail($id)->delete();

        return back()->with('success', 'Data guru berhasil dihapus.');
    }
}
