<?php

namespace App\Http\Controllers;

use App\Http\Requests\HistoryKegiatanRequest;
use App\Models\HistoryKegiatan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;

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

    public function store(HistoryKegiatanRequest $request)
    {
        try {
            $historykegiatan = HistoryKegiatan::withTrashed()
                ->where('NamaHistoryKegiatan', $request->NamaHistoryKegiatan)
                ->first();

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

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

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

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

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