<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Extracuricullar;
use Illuminate\Support\Facades\Validator;

class ExtracurricularController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->has('search')) {
            $extracuricullars = Extracuricullar::where('nama', 'LIKE', '%'.$request->search.'%')
                                                ->orWhere('deskripsi', 'LIKE', '%'.$request->search.'%')
                                                ->orWhere('kategori', 'LIKE', '%'.$request->search.'%')
                                                ->paginate(5);
        } else {
            $extracuricullars = Extracuricullar::paginate(5);
        }

        return view('ekstrakurikuler.ekstrakurikuler', compact('extracuricullars'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->only('nama', 'kategori', 'deskripsi'), [
            'nama' => 'required',
            'kategori' => 'required',
            'deskripsi' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        Extracuricullar::create([
            'nama' => $request->nama,
            'kategori' => $request->kategori,
            'deskripsi' => $request->deskripsi,

        ]);

        return redirect()->route('ekstrakurikuler.index')->with('success', 'Data Ekstrakurikuler Berhasil Ditambah!');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $ekstrakurikuler = Extracuricullar::findOrFail($id);
        return view('ekstrakurikuler.edit', compact('ekstrakurikuler'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $validatedData = $request->validate([
            'nama' => 'required',
            'kategori' => 'required',
            'deskripsi' => 'required',
        ]);

        $ekstrakurikuler = Extracuricullar::findOrFail($id);
        $ekstrakurikuler->update($validatedData);

        return redirect()->route('ekstrakurikuler.index')->with('success', 'Data Ekstrakurikuler Berhasil Diperbarui!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $ekstrakurikuler = Extracuricullar::findorfail($id);
        $ekstrakurikuler->delete();

        return back()->with('info', 'Data Ekstrakurikuler Berhasil Dihapus!');
    }
}
