<?php

namespace App\Http\Controllers\Api\Admin;

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

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

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama_alumni' => 'required|string|max:255',
            'perguruan_tinggi' => 'required|string',
            'jurusan_diambil' => 'required|string',
        ], [
            'nama_alumni.required' => 'Nama alumni wajib diisi.',
            'perguruan_tinggi.required' => 'Nama Perguruan Tinggi harus diisi.',
            'jurusan_diambil.required' => 'Jurusan yang diambil tidak boleh kosong.',
        ]);

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

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

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

        $validator = Validator::make($request->all(), [
            'nama_alumni' => 'required|string|max:255',
            'perguruan_tinggi' => 'required|string',
            'jurusan_diambil' => 'required|string',
        ]);

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

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

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