<?php

namespace App\Http\Controllers\Membership\Public;

use App\Http\Controllers\Controller;
use App\Models\MembershipCategory;
use App\Models\MembershipApplication;
use App\Services\MembershipService;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class MembershipApplicationController extends Controller
{
    protected MembershipService $membershipService;
    protected NotificationService $notificationService;

    public function __construct(MembershipService $membershipService, NotificationService $notificationService)
    {
        $this->membershipService = $membershipService;
        $this->notificationService = $notificationService;
    }

    /**
     * Display the membership application form.
     */
    public function create()
    {
        $categories = MembershipCategory::active()->ordered()->get();
        
        return view('membership.public.apply', compact('categories'));
    }

    /**
     * Store a new membership application.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'membership_category_id' => 'required|exists:membership_categories,id',
            'first_name' => 'required|string|max:191',
            'last_name' => 'required|string|max:191',
            'email' => 'required|email|max:191',
            'phone' => 'required|string|max:20',
            'address' => 'nullable|string|max:500',
            'city' => 'nullable|string|max:100',
            'country' => 'nullable|string|max:100',
            'occupation' => 'nullable|string|max:191',
            'organization' => 'nullable|string|max:191',
            'professional_background' => 'nullable|string|max:2000',
            'terms_accepted' => 'required|accepted',
        ], [
            'membership_category_id.required' => 'Please select a membership category.',
            'first_name.required' => 'First name is required.',
            'last_name.required' => 'Last name is required.',
            'email.required' => 'Email address is required.',
            'email.email' => 'Please enter a valid email address.',
            'phone.required' => 'Phone number is required.',
            'terms_accepted.required' => 'You must accept the terms and conditions.',
            'terms_accepted.accepted' => 'You must accept the terms and conditions.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        // XSS Prevention
        $validated = $validator->validated();
        $validated['first_name'] = strip_tags($validated['first_name']);
        $validated['last_name'] = strip_tags($validated['last_name']);
        $validated['email'] = strip_tags($validated['email']);
        $validated['phone'] = strip_tags($validated['phone']);
        $validated['address'] = strip_tags($validated['address'] ?? '');
        $validated['city'] = strip_tags($validated['city'] ?? '');
        $validated['country'] = strip_tags($validated['country'] ?? '');
        $validated['occupation'] = strip_tags($validated['occupation'] ?? '');
        $validated['organization'] = strip_tags($validated['organization'] ?? '');

        // Check if application already exists with this email
        $existingApplication = MembershipApplication::where('email', $validated['email'])
            ->whereIn('status', ['pending', 'under_review'])
            ->first();

        if ($existingApplication) {
            return redirect()->back()
                ->withErrors(['email' => 'An application with this email is already pending review.'])
                ->withInput();
        }

        // Create application
        $application = MembershipApplication::create([
            'reference_number' => MembershipApplication::generateReferenceNumber(),
            'membership_category_id' => $validated['membership_category_id'],
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'address' => $validated['address'] ?? null,
            'city' => $validated['city'] ?? null,
            'country' => $validated['country'] ?? null,
            'occupation' => $validated['occupation'] ?? null,
            'organization' => $validated['organization'] ?? null,
            'professional_background' => $validated['professional_background'] ?? null,
            'applicant_data' => $validated,
            'status' => 'pending',
            'payment_required' => true,
        ]);

        // Send confirmation notification
        $this->notificationService->sendApplicationConfirmation($application);

        return redirect()->route('membership.apply.success', $application->reference_number);
    }

    /**
     * Display application success page.
     */
    public function success(string $referenceNumber)
    {
        $application = MembershipApplication::where('reference_number', $referenceNumber)->firstOrFail();
        
        return view('membership.public.apply-success', compact('application'));
    }

    /**
     * Display the check-status form page.
     */
    public function checkStatusForm()
    {
        return view('membership.public.check-status');
    }

    /**
     * Check application status.
     */
    public function checkStatus(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'reference_number' => 'required|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator);
        }

        $application = MembershipApplication::where('reference_number', $request->reference_number)->first();

        if (!$application) {
            return redirect()->back()
                ->withErrors(['reference_number' => 'Application not found. Please check your reference number.']);
        }

        return view('membership.public.application-status', compact('application'));
    }

    /**
     * Display application status page.
     */
    public function status(string $referenceNumber)
    {
        $application = MembershipApplication::where('reference_number', $referenceNumber)->firstOrFail();
        
        return view('membership.public.application-status', compact('application'));
    }
}
