<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contribution;
use App\Models\Member;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;

class ContributionsController extends Controller
{
    public function index(Request $request)
    {
        $query = Contribution::with('member');

        // Search by member name
        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('member', function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%");
            });
        }

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

        // Regional Treasurer Filtering
        $user = auth()->user();
        if ($user->role === 'regional-treasurer' && $user->region) {
            $query->whereHas('member.leader', function($q) use ($user) {
                $q->where('region', $user->region);
            });
        }
        // Admin/Top-Leader Regional Context Filtering
        elseif (in_array($user->role, ['admin', 'top-leader']) && session('selected_region')) {
            $region = session('selected_region');
            $query->whereHas('member.leader', function($q) use ($region) {
                $q->where('region', $region);
            });
        }
        // Leader Filtering (only their members)
        elseif ($user->role === 'leader') {
            $query->whereHas('member', function($q) use ($user) {
                $q->where('leader_id', $user->id);
            });
        }
        // Regular User Filtering (only their own)
        elseif ($user->role === 'user') {
            $query->whereHas('member', function($q) use ($user) {
                $q->where('phone', $user->phone);
            });
        }

        $contributions = $query->latest()->paginate(15);
        
        return view('contributions.index', compact('contributions'));
    }
    public function create()
    {
        $user = auth()->user();
        $query = Member::active();

        // Leaders can only see their own members
        if ($user->role === 'leader') {
            $query->where('leader_id', $user->id);
        } 
        // Regional Treasurers can only see members in their region
        elseif ($user->role === 'regional-treasurer' && $user->region) {
            $query->whereHas('leader', function($q) use ($user) {
                $q->where('region', $user->region);
            });
        }
        // Admins/Top-Leaders can filter by region if selected
        elseif (in_array($user->role, ['admin', 'top-leader']) && session('selected_region')) {
            $region = session('selected_region');
            $query->whereHas('leader', function($q) use ($region) {
                $q->where('region', $region);
            });
        }
        // Regular users can only see themselves
        elseif ($user->role === 'user') {
            $query->where('phone', $user->phone);
        }

        $members = $query->orderBy('name')->get();
        return view('contributions.create', compact('members'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'member_id' => 'required|exists:members,id',
            'amount' => 'required|numeric|min:0',
            'contribution_type' => 'required|in:social,share,Social,Share',
            'contribution_date' => 'required|date',
            'payment_method' => 'required|in:mpesa,cash,bank_transfer,cheque',
            'transaction_id' => 'required|string|unique:contributions,transaction_id',
            'description' => 'nullable|string|max:255',
        ]);

        // Normalize contribution_type to lowercase
        $validated['contribution_type'] = strtolower($validated['contribution_type']);

        try {
            DB::beginTransaction();

            // 1. Create Contribution
            $contribution = Contribution::create([
                'member_id' => $validated['member_id'],
                'amount' => $validated['amount'],
                'contribution_type' => $validated['contribution_type'],
                'contribution_date' => $validated['contribution_date'],
                'payment_method' => $validated['payment_method'],
                'transaction_id' => $validated['transaction_id'],
                'status' => 'completed',
            ]);

            // 2. Get member and update balance
            $member = Member::find($validated['member_id']);
            $balanceBefore = $member->current_balance;
            $balanceAfter = $balanceBefore + $validated['amount'];
            $member->update(['current_balance' => $balanceAfter]);

            // 3. Record Transaction (Ledger)
            Transaction::create([
                'member_id' => $validated['member_id'],
                'transaction_reference' => 'CON-' . strtoupper(substr($validated['contribution_type'], 0, 3)) . '-' . time(),
                'transaction_type' => 'contribution',
                'contribution_type' => $validated['contribution_type'],
                'amount' => $validated['amount'],
                'balance_before' => $balanceBefore,
                'balance_after' => $balanceAfter,
                'payment_method' => $validated['payment_method'],
                'mpesa_receipt' => $validated['payment_method'] === 'mpesa' ? $validated['transaction_id'] : null,
                'description' => $validated['description'] ?? ucfirst($validated['contribution_type']) . ' Contribution',
                'transaction_date' => $validated['contribution_date'],
                'recorded_by' => auth()->id(),
            ]);

            DB::commit();
            return redirect()->route('contributions.index')->with('success', 'Contribution recorded successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->withInput()->with('error', 'Error recording contribution: ' . $e->getMessage());
        }
    }
}
