<?php

namespace App\Http\Controllers;

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

class ContactController extends Controller
{
    public function index()
    {
        return view('kontak');
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'pesan' => 'required|string',
        ]);

        Contact::create($request->all());

        return redirect()->back()->with('success', 'Terima kasih, pesan Anda telah terkirim ke Balai Penyuluhan KB Kecamatan Kanigoro.');
    }

    public function adminIndex(Request $request)
    {
        // Menangkap query pencarian
        $search = $request->input('search');

        // Mengambil data dengan kondisi pencarian (jika ada)
        $pesan = Contact::when($search, function ($query, $search) {
                return $query->where('nama', 'like', "%{$search}%")
                             ->orWhere('email', 'like', "%{$search}%");
            })
            ->latest()
            ->paginate(10);
        
        // Mempertahankan query search saat berpindah halaman paginasi
        $pesan->appends(['search' => $search]);

        return view('admin.pesan.index', compact('pesan'));
    }

    public function destroy($id)
    {
        $pesan = Contact::findOrFail($id);
        $pesan->delete();

        return redirect()->back()->with('success', 'Pesan berhasil dihapus dari sistem.');
    }
}