<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Guru;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class GuruController extends Controller
{
    public function index()
    {
        $guru = Guru::all();
        return response()->json(['success' => true, 'data' => $guru], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama_guru' => 'required|string|max:255',
        ], [
            'nama_guru.required' => 'Nama guru tidak boleh kosong.',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $guru = Guru::create($request->all());
        return response()->json([
            'success' => true, 
            'message' => 'Guru ' . $guru->id_guru . ' berhasil ditambahkan.', 
            'data' => $guru
        ], 201);
    }

    public function update(Request $request, $id)
    {
        $guru = Guru::find($id);
        if (!$guru) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);

        $validator = Validator::make($request->all(), [
            'nama_guru' => 'required|string|max:255',
        ], [
            'nama_guru.required' => 'Update gagal, nama guru harus diisi.',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $guru->update($request->all());
        return response()->json(['success' => true, 'message' => 'Data ' . $guru->id_guru . ' berhasil diperbarui'], 200);
    }

    public function destroy($id)
    {
        $guru = Guru::find($id);
        if (!$guru) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);
        $guru->delete();
        return response()->json(['success' => true, 'message' => 'Data Guru berhasil dihapus'], 200);
    }
}