<?php

namespace App\Http\Controllers\Membership\Member;

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

class MemberRenewalController extends Controller
{
    public function __construct(
        protected MembershipRenewalService $renewalService
    ) {}

    /**
     * Show paginated renewal history for the authenticated member.
     */
    public function index()
    {
        $member = $this->getMember();

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

        $renewals = $member->renewals()
            ->with('certificate')
            ->latest('renewed_at')
            ->paginate(15);

        return view('membership.member.renewal-history', compact('member', 'renewals'));
    }

    /**
     * Process a manual renewal for the authenticated member.
     */
    public function store()
    {
        $member = $this->getMember();

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

        abort_unless($member->isActive(), 403, 'Only active members can renew their membership.');

        try {
            $this->renewalService->processRenewal($member, 'manual', auth()->id());

            return redirect()->route('member.certificate.index')
                ->with('success', 'Your membership has been renewed and a new certificate has been sent to your email.');
        } catch (\Throwable $e) {
            return redirect()->back()
                ->withErrors(['error' => 'Renewal failed. Please try again or contact support.']);
        }
    }

    /**
     * Show the renewal preference settings page.
     */
    public function settings()
    {
        $member = $this->getMember();

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

        return view('membership.member.renewal-settings', compact('member'));
    }

    /**
     * Save the member's renewal preference (manual / automatic).
     */
    public function updateSettings(Request $request)
    {
        $member = $this->getMember();

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

        // Only the authenticated member can update their own preference
        abort_unless($member->user_id === auth()->id(), 403);

        $request->validate([
            'renewal_type' => 'required|in:manual,automatic',
        ], [
            'renewal_type.required' => 'Please select a renewal preference.',
            'renewal_type.in'       => 'Invalid renewal type selected.',
        ]);

        $isAutomatic = $request->renewal_type === 'automatic';

        $member->update([
            'renewal_type'        => $request->renewal_type,
            'auto_renewal_enabled' => $isAutomatic,
        ]);

        return redirect()->route('member.renewal.settings')
            ->with('success', 'Your renewal preference has been saved.');
    }

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