<?php

namespace App\Http\Controllers;

use App\Models\Anggota;
use Illuminate\Http\Request;

class AnggotaController extends Controller
{
   public function index(Request $request)
{
    $keyword = $request->search;

    $anggota = Anggota::when($keyword, function ($q) use ($keyword) {
        $q->where('nama', 'like', "%$keyword%")
          ->orWhere('no_identitas', 'like', "%$keyword%")
          ->orWhere('no_ktp', 'like', "%$keyword%");
    })
    ->latest()
    ->paginate(10);

    return view('anggota.index', compact('anggota'));
}

    public function create()
    {
        return view('anggota.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama'           => 'required|string|max:255',
            'jenis_anggota'  => 'required|in:Mahasiswa,Siswa,Dosen,Umum',
            'no_identitas'   => 'required|unique:anggotas,no_identitas',
            'no_ktp'         => 'nullable|numeric|digits_between:1,16',
            'prodi'          => 'nullable|string|max:255',
            'no_hp'          => 'required|string|max:20',
            'alamat'         => 'required|string',
            'nama_wali'      => 'required|string|max:255',
            'no_hp_wali'     => 'required|string|max:20',
            'hubungan_wali'  => 'required|in:Orang Tua,Saudara,Dosen Wali,Lainnya',
        ]);

        Anggota::create($validated);

        return redirect()
            ->route('admin.anggota.member.index')
            ->with('success', 'Data anggota berhasil ditambahkan!');
    }

    public function edit(Anggota $member)
    {
        return view('anggota.edit', ['anggota' => $member]);
    }

    public function update(Request $request, Anggota $member)
    {
        $validated = $request->validate([
            'nama'           => 'required|string|max:255',
            'jenis_anggota'  => 'required|in:Mahasiswa,Siswa,Dosen,Umum',
            'no_identitas'   => 'required|unique:anggotas,no_identitas,' . $member->id,
            'no_ktp'         => 'nullable|numeric|digits_between:1,16',
            'prodi'          => 'nullable|string|max:255',
            'no_hp'          => 'required|string|max:20',
            'alamat'         => 'required|string',
            'nama_wali'      => 'required|string|max:255',
            'no_hp_wali'     => 'required|string|max:20',
            'hubungan_wali'  => 'required|in:Orang Tua,Saudara,Dosen Wali,Lainnya',
        ]);

        $member->update($validated);

        return redirect()
            ->route('admin.anggota.member.index')
            ->with('success', 'Data anggota berhasil diperbarui!');
    }

    public function destroy(Anggota $member)
    {
        $member->delete();

        return redirect()
            ->route('admin.anggota.member.index')
            ->with('success', 'Data anggota berhasil dihapus!');
    }
}
