<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Models\User;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class MemberController extends Controller
{
    public function index(Request $request)
    {
        $query = Member::query();

        // For leaders, only show their own region's members
        if (auth()->user()->role === 'leader') {
            $query->where('leader_id', auth()->id());
        } elseif (in_array(auth()->user()->role, ['admin', 'top-leader']) && session('selected_region')) {
            $region = session('selected_region');
            $query->whereHas('leader', function($q) use ($region) {
                $q->where('region', $region);
            });
        }

        // Search by member name
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $members = $query->latest()->paginate(15);
        return view('members.index', compact('members'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            // 'member_number' => 'required|unique:members',
            'name' => 'required|max:255',
            'phone' => 'required|unique:members|max:15',
            'email' => 'nullable|email',
            'join_date' => 'required|date',
            'church' => 'nullable|string|max:255',
            'location' => 'nullable|string|max:255',
            'status' => 'nullable|in:active,inactive',
        ]);

        // Auto-assign leader for leaders creating members
        if (auth()->user()->role === 'leader') {
            $validated['leader_id'] = auth()->id();
        } elseif ($request->filled('leader_id')) {
            // Top-leaders can manually assign leaders
            $validated['leader_id'] = $request->leader_id;
        }

        Member::create($validated);

        return redirect()->route('members.index')
            ->with('success', 'Member registered successfully!');
    }

    public function show($id)
    {
        $member = Member::findOrFail($id);
        $contributions = $member->contributions()->latest()->take(10)->get();
        return view('members.show', compact('member', 'contributions'));
    }

    public function edit($id)
    {
        $member = Member::findOrFail($id); // Retrieve the member by ID or throw a 404 error
        return view('members.edit', compact('member')); // Pass the member to the view
    }

    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'name' => 'required|max:255',
            'phone' => 'required|max:15',
            'email' => 'nullable|email',
            'join_date' => 'required|date',
            'church' => 'nullable|string|max:255',
            'location' => 'nullable|string|max:255',
            'status' => 'required|in:active,inactive',
        ]);

        $member = Member::findOrFail($id); // Retrieve the member by ID or throw a 404 error
        $member->update($validated); // Update the member with validated data

        return redirect()->route('members.index')
            ->with('success', 'Member updated successfully!');
    }
    public function destroy($id)
{
    $member = Member::findOrFail($id); // Retrieve the member by ID or throw a 404 error
    $member->delete(); // Delete the member

    return redirect()->route('members.index')
        ->with('success', 'Member deleted successfully!');
}

    public function downloadStatement($id)
    {
        $member = Member::findOrFail($id);
        $contributions = $member->contributions()->latest()->get();
        $totalContributions = $contributions->sum('amount');

        $data = [
            'member' => $member,
            'user' => $member, // For compatibility with existing view which expects $user
            'contributions' => $contributions,
            'totalContributions' => $totalContributions,
            'generatedDate' => now()->format('d M Y')
        ];

        $pdf = Pdf::loadView('pdfs.member-statement', $data);
        return $pdf->download('statement-' . str_replace(' ', '-', strtolower($member->name)) . '-' . now()->format('Y-m-d') . '.pdf');
    }

    /**
     * Display unassigned members for top-leaders to assign.
     */
    public function unassigned(Request $request)
    {
        // Only top-leaders and admins can access
        if (!in_array(auth()->user()->role, ['top-leader', 'admin'])) {
            abort(403);
        }

        $query = Member::whereNull('leader_id');

        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $unassignedMembers = $query->latest()->paginate(15);

        // Get all leaders for the assignment dropdown
        $leaders = User::where('role', 'leader')->orderBy('name')->get();

        return view('members.unassigned', compact('unassignedMembers', 'leaders'));
    }

    /**
     * Assign a member to a leader.
     */
    public function assignLeader(Request $request, $id)
    {
        // Only top-leaders and admins can assign
        if (!in_array(auth()->user()->role, ['top-leader', 'admin'])) {
            abort(403);
        }

        $request->validate([
            'leader_id' => 'required|exists:users,id',
        ]);

        $member = Member::findOrFail($id);
        $member->update(['leader_id' => $request->leader_id]);

        return redirect()->back()->with('success', 'Member assigned to leader successfully!');
    }
}