<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\Media;
use App\Models\Page;
use App\Models\ReferralSubmission;
use App\Support\AdminNotifier;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ReferralController extends Controller
{
    public function show(): View
    {
        $page = Page::query()
            ->published()
            ->where('route_path', '/referral')
            ->with('sections')
            ->firstOrFail();

        $supportOptions = config('hillcrest.referral_support_options', []);

        return view('site.referral', compact('page', 'supportOptions'));
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'referrer_name' => ['required', 'string', 'max:255'],
            'referrer_organisation' => ['nullable', 'string', 'max:255'],
            'referrer_role' => ['nullable', 'string', 'max:255'],
            'referrer_email' => ['required', 'email', 'max:255'],
            'referrer_phone' => ['nullable', 'string', 'max:50'],
            'individual_name' => ['required', 'string', 'max:255'],
            'individual_dob' => ['nullable', 'date'],
            'individual_postcode' => ['nullable', 'string', 'max:20'],
            'support_needs' => ['nullable', 'array'],
            'support_needs.*' => ['string', 'max:100', Rule::in(array_keys(config('hillcrest.referral_support_options', [])))],
            'additional_notes' => ['nullable', 'string', 'max:10000'],
            'attachment' => ['nullable', 'file', 'mimes:pdf,doc,docx,jpg,jpeg,png', 'max:5120'],
        ]);

        $attachmentId = null;
        if ($request->hasFile('attachment')) {
            $file = $validated['attachment'];
            $path = $file->store('uploads/referrals', 'public');
            $media = Media::query()->create([
                'disk' => 'public',
                'path' => $path,
                'filename' => $file->getClientOriginalName(),
                'mime_type' => $file->getClientMimeType(),
                'size_bytes' => $file->getSize(),
            ]);
            $attachmentId = $media->id;
        }

        $submission = ReferralSubmission::query()->create([
            'referrer_name' => $validated['referrer_name'],
            'referrer_organisation' => $validated['referrer_organisation'] ?? null,
            'referrer_role' => $validated['referrer_role'] ?? null,
            'referrer_email' => $validated['referrer_email'],
            'referrer_phone' => $validated['referrer_phone'] ?? null,
            'individual_name' => $validated['individual_name'],
            'individual_dob' => $validated['individual_dob'] ?? null,
            'individual_postcode' => $validated['individual_postcode'] ?? null,
            'support_needs' => $validated['support_needs'] ?? [],
            'additional_notes' => $validated['additional_notes'] ?? null,
            'attachment_media_id' => $attachmentId,
            'ip_address' => $request->ip(),
            'user_agent' => (string) $request->userAgent(),
            'status' => 'new',
        ]);

        AdminNotifier::trySend('New referral submission', [
            'Referrer: '.$submission->referrer_name,
            'Organisation: '.($submission->referrer_organisation ?? '—'),
            'Contact: '.$submission->referrer_email,
            'Individual: '.$submission->individual_name,
            'Postcode: '.($submission->individual_postcode ?? '—'),
            $attachmentId ? 'Attachment uploaded: yes' : 'Attachment: none',
        ]);

        return redirect()
            ->route('referral.show')
            ->with('status', 'Thank you. Your referral has been submitted.');
    }
}
