<?php

namespace App\Http\Controllers\Membership\Member;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\Contribution;
use App\Services\ContributionService;
use Illuminate\Http\Request;

class MemberPortalController extends Controller
{
    protected ContributionService $contributionService;

    public function __construct(ContributionService $contributionService)
    {
        $this->contributionService = $contributionService;
    }

    /**
     * Display member dashboard.
     */
    public function dashboard()
    {
        $member = $this->getMember();

        if (!$member) {
            return redirect()->route('login')
                ->withErrors(['error' => 'Member profile not found.']);
        }

        $member->load(['membershipCategories', 'contributions', 'loanApplications']);

        // Statistics
        $statistics = [
            'total_contributions' => $member->contributions()->paid()->sum('amount'),
            'pending_contributions' => $member->contributions()->pending()->count(),
            'overdue_contributions' => $member->contributions()->overdue()->count(),
            'active_loans' => $member->loanApplications()->active()->count(),
            'outstanding_loan_balance' => $member->getOutstandingLoanBalance(),
        ];

        // Recent contributions
        $recentContributions = $member->contributions()
            ->with('membershipCategory')
            ->latest()
            ->take(5)
            ->get();

        // Pending contributions
        $pendingContributions = $member->contributions()
            ->with('membershipCategory')
            ->whereIn('status', ['pending', 'overdue'])
            ->orderBy('due_date')
            ->take(5)
            ->get();

        // Active loans
        $activeLoans = $member->loanApplications()
            ->with('loanProduct')
            ->whereIn('status', ['active', 'disbursed'])
            ->latest()
            ->get();

        return view('membership.member.dashboard', compact(
            'member',
            'statistics',
            'recentContributions',
            'pendingContributions',
            'activeLoans'
        ));
    }

    /**
     * Display member profile.
     */
    public function profile()
    {
        $member = $this->getMember();

        if (!$member) {
            return redirect()->route('login');
        }

        $member->load(['membershipCategories', 'user']);

        return view('membership.member.profile', compact('member'));
    }

    /**
     * Update member profile.
     */
    public function updateProfile(Request $request)
    {
        $member = $this->getMember();

        if (!$member) {
            return redirect()->route('login');
        }

        $request->validate([
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string|max:500',
            'city' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
        ]);

        $user = $member->user;
        $user->update([
            'phone' => strip_tags($request->phone ?? ''),
        ]);

        $member->update([
            'notes' => strip_tags($request->notes ?? ''),
        ]);

        return redirect()->route('member.profile')
            ->with('success', 'Profile updated successfully.');
    }

    /**
     * Display contribution history.
     */
    public function contributions(Request $request)
    {
        $member = $this->getMember();

        if (!$member) {
            return redirect()->route('login');
        }

        $history = $this->contributionService->generateHistory($member, $request->only([
            'status',
            'category_id',
            'from_date',
            'to_date',
            'per_page',
        ]));

        return view('membership.member.contributions', compact('member', 'history'));
    }

    /**
     * Display contribution payment page.
     */
    public function payContribution(Contribution $contribution)
    {
        $member = $this->getMember();

        if (!$member || $contribution->member_id !== $member->id) {
            abort(403, 'Unauthorized access to this contribution.');
        }

        if ($contribution->isPaid()) {
            return redirect()->route('member.contributions')
                ->withErrors(['error' => 'This contribution has already been paid.']);
        }

        $contribution->load('membershipCategory');

        return view('membership.member.pay-contribution', compact('member', 'contribution'));
    }

    /**
     * Process contribution payment.
     */
    public function processContributionPayment(Request $request, Contribution $contribution)
    {
        $member = $this->getMember();

        if (!$member || $contribution->member_id !== $member->id) {
            abort(403, 'Unauthorized access to this contribution.');
        }

        $paymentMethod = $request->input('payment_method', 'mobile');

        $rules = ['payment_method' => 'nullable|in:mobile,card'];
        if ($paymentMethod === 'card') {
            $rules['card_number'] = 'required|string';
            $rules['card_expiry'] = ['required', 'regex:/^(0[1-9]|1[0-2])\/\d{2}$/'];
            $rules['card_cvv']    = 'required|digits_between:3,4';
        } else {
            $rules['phone_number'] = 'required|string|regex:/^[0-9+]{9,15}$/';
        }

        $request->validate($rules, [
            'phone_number.required' => 'Phone number is required.',
            'phone_number.regex'    => 'Please enter a valid phone number.',
        ]);

        $result = $this->contributionService->processPayment(
            contribution: $contribution,
            phoneNumber: $request->input('phone_number', ''),
            paymentMethod: $paymentMethod,
            cardNumber: $request->input('card_number'),
            cardExpiry: $request->input('card_expiry'),
            cardCvv: $request->input('card_cvv'),
        );

        if ($result['success']) {
            return redirect()->route('member.contributions')
                ->with('success', $result['message']);
        }

        return redirect()->back()
            ->withErrors(['error' => $result['message']]);
    }

    /**
     * Get the authenticated member.
     */
    protected function getMember(): ?Member
    {
        return Member::where('user_id', auth()->id())->first();
    }
}
