<?php

namespace App\Http\Controllers;

use App\Models\SuggestedMember;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SuggestedMemberController extends Controller
{
    public function index()
    {
        $suggestedMembers = SuggestedMember::with(['adder', 'confirmer'])->latest()->paginate(10);
        return view('suggested-members.index', compact('suggestedMembers'));
    }

    public function create()
    {
        return view('suggested-members.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'phone' => 'required|unique:suggested_members|max:15',
            'church' => 'required|max:255',
            'location' => 'required|max:255',
        ]);

        $validated['added_by'] = Auth::id();

        SuggestedMember::create($validated);

        return redirect()->route('suggested-members.create')
            ->with('success', 'Suggested member added successfully!');
    }

    public function confirm($id)
    {
        $suggestedMember = SuggestedMember::findOrFail($id);

        if ($suggestedMember->status === 'confirmed') {
            return redirect()->back()->with('error', 'Member already confirmed.');
        }

        // Create actual member
        Member::create([
            'name' => $suggestedMember->name,
            'phone' => $suggestedMember->phone,
            'church' => $suggestedMember->church,
            'location' => $suggestedMember->location,
            'join_date' => now()->format('Y-m-d'),
            'status' => 'active',
        ]);

        // Update suggested member status
        $suggestedMember->update([
            'status' => 'confirmed',
            'confirmed_by' => Auth::id(),
        ]);

        return redirect()->back()->with('success', 'Suggested member confirmed and added to members!');
    }
}
