<?php

namespace App\Http\Controllers\Membership\Member;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Models\MembershipCertificate;
use App\Services\MembershipCertificateService;
use Illuminate\Support\Facades\Storage;

class MemberCertificateController extends Controller
{
    public function __construct(
        protected MembershipCertificateService $certificateService
    ) {}

    /**
     * Show the member's current certificate page.
     */
    public function index()
    {
        $member = $this->getMember();

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

        $certificate = $member->currentCertificate();

        // Renewal reminder: membership_end_date within 30 days
        $showRenewalReminder = false;
        if ($member->membership_end_date) {
            $daysUntilExpiry = now()->startOfDay()->diffInDays($member->membership_end_date, false);
            $showRenewalReminder = $daysUntilExpiry <= 30;
        }

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

    /**
     * Download the certificate PDF.
     * Enforces ownership — a member can only download their own certificate.
     */
    public function download(MembershipCertificate $certificate)
    {
        $member = $this->getMember();

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

        abort_unless($certificate->member_id === $member->id, 403, 'You are not authorised to download this certificate.');

        abort_unless($certificate->pdf_path && Storage::disk('public')->exists($certificate->pdf_path), 404, 'Certificate file not found.');

        return Storage::disk('public')->download(
            $certificate->pdf_path,
            $certificate->certificate_number . '.pdf'
        );
    }

    /**
     * Regenerate the member's current certificate.
     */
    public function regenerate()
    {
        $member = $this->getMember();

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

        try {
            $this->certificateService->regenerateForMember($member);
            return redirect()->route('member.certificate.index')
                ->with('success', 'Your certificate has been regenerated and sent to your email.');
        } catch (\Throwable $e) {
            return redirect()->route('member.certificate.index')
                ->withErrors(['error' => 'Certificate regeneration failed. Please try again later.']);
        }
    }

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