<?php

namespace App\Http\Controllers\Api\Admin;

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

class ProspekKerjaController extends Controller
{
    public function index()
    {
        $prospek = ProspekKerja::with('jurusan')->orderBy('id', 'desc')->get();
        return response()->json(['success' => true, 'data' => $prospek], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'jurusan_id' => 'required|exists:jurusans,id',
            'nama_profesi' => 'required|string|max:255',
            'range_gaji' => 'nullable|string|max:255',
            'deskripsi_pekerjaan' => 'nullable|string',
        ]);

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

        $prospek = ProspekKerja::create($request->all());
        return response()->json(['success' => true, 'message' => 'Prospek Kerja berhasil ditambahkan', 'data' => $prospek], 201);
    }

    public function show($id)
    {
        $prospek = ProspekKerja::find($id);
        if (!$prospek) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);
        return response()->json(['success' => true, 'data' => $prospek], 200);
    }

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

        $validator = Validator::make($request->all(), [
            'jurusan_id' => 'required|exists:jurusans,id',
            'nama_profesi' => 'required|string|max:255',
            'range_gaji' => 'nullable|string|max:255',
            'deskripsi_pekerjaan' => 'nullable|string',
        ]);

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

        $prospek->update($request->all());
        return response()->json(['success' => true, 'message' => 'Prospek Kerja berhasil diperbarui', 'data' => $prospek], 200);
    }

    public function destroy($id)
    {
        $prospek = ProspekKerja::find($id);
        if (!$prospek) return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);

        $prospek->delete();
        return response()->json(['success' => true, 'message' => 'Prospek Kerja berhasil dihapus'], 200);
    }
}