<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ContactUs;
use App\Models\NatureOfInvestment;

class ContactUsController extends Controller
{
    public function index()
    {
        $contacts = ContactUs::latest()->paginate(10);
        return view('admin.contact-us.index', compact('contacts'));
    }

    public function edit($id)
    {
        $contact = ContactUs::findOrFail($id);
        $natureOfInvestments = NatureOfInvestment::all();
        return view('admin.contact-us.addedit', compact('contact', 'natureOfInvestments'));
    }

    public function update(Request $request, $id)
    {
        $contact = ContactUs::findOrFail($id);
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email',
            'phone' => 'nullable|string',
            'city' => 'nullable|string',
            'nature_of_work' => 'nullable|array',
        ]);
        $data['nature_of_work'] = implode(',', $request->nature_of_work ?? []);
        $contact->update($data);

        return redirect()->route('admin.contact-us.index')->with('success', 'Contact entry updated successfully.');
    }

    public function destroy($id)
    {
        ContactUs::findOrFail($id)->delete();
        return back()->with('success', 'Contact entry deleted successfully.');
    }

    // Optional: create() and store() if you want to manually add entries from admin
    public function show()
    {
        $natureOfInvestments = NatureOfInvestment::all();
        return view('admin.contact-us.addedit', compact('natureOfInvestments'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string',
            'email' => 'required|email',
            'phone' => 'nullable|string',
            'city' => 'nullable|string',
            'nature_of_work' => 'nullable|array',
        ]);
        $data['nature_of_work'] = implode(',', $request->nature_of_work ?? []);
        ContactUs::create($data);

        return redirect()->route('admin.contact-us.index')->with('success', 'New contact entry added.');
    }
}
