<?php

namespace App\Http\Controllers;

use App\Http\Requests\JenisKegiatanRequest;
use App\Models\JenisKegiatan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;

class JenisKegiatanController extends Controller
{
    public function index()
    {
        try {
            $jeniskegiatan = JenisKegiatan::latest()->get();
            return Inertia::render('admin/kegiatan/index_jenis_kegiatan', ['jeniskegiatan' => $jeniskegiatan]);
        } catch (\Exception $e) {
            Log::error('Error fetching Jenis Kegiatan: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong.');
        }
    }

    public function store(JenisKegiatanRequest $request)
    {
        try {
            $jeniskegiatan = JenisKegiatan::withTrashed()
                ->where('NamaJenisKegiatan', $request->NamaJenisKegiatan)
                ->first();

            if ($jeniskegiatan) {
                $jeniskegiatan->restore();
                return redirect()->route('admin.jeniskegiatan.index')->with('success', 'Jenis Kegiatan berhasil dikembalikan.');
            }

            JenisKegiatan::create($request->validated());

            return redirect()->route('admin.jeniskegiatan.index')->with('success', 'Jenis Kegiatan berhasil dibuat.');
        } catch (\Exception $e) {
            Log::error('Error creating Jenis Kegiatan: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong.');
        }
    }

    public function update(JenisKegiatanRequest $request, JenisKegiatan $jeniskegiatan)
    {
        try {
            $jeniskegiatan->update($request->validated());
            return redirect()->route('admin.jeniskegiatan.index')->with('success', 'Jenis Kegiatan berhasil diperbarui.');
        } catch (\Exception $e) {
            Log::error('Error updating Jenis Kegiatan: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong.');
        }
    }

    public function destroy(JenisKegiatan $jeniskegiatan)
    {
        try {
            $jeniskegiatan->delete();
            return redirect()->route('admin.jeniskegiatan.index')->with('success', 'Jenis Kegiatan berhasil dihapus.');
        } catch (\Exception $e) {
            Log::error('Error deleting Jenis Kegiatan: ' . $e->getMessage());
            return back()->with('error', 'Something went wrong.');
        }
    }

    public function getAll()
    {
        try {
            $jeniskegiatan = JenisKegiatan::where('IsPublish', true)
                ->select('JenisKegiatanId', 'NamaJenisKegiatan')
                ->get();
            return response()->json($jeniskegiatan);
        } catch (\Exception $e) {
            Log::error('Error fetching all Jenis Kegiatan: ' . $e->getMessage());
            return response()->json(['error' => 'Something went wrong'], 500);
        }
    }
}
