<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Http\Requests\Site\ContactSubmissionRequest;
use App\Models\ContactSubmission;
use App\Models\Page;
use App\Support\AdminNotifier;
use Illuminate\Support\Carbon;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

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

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

    public function store(ContactSubmissionRequest $request): RedirectResponse
    {
        $validated = $request->validated();

        $isDuplicate = ContactSubmission::query()
            ->where('email', $validated['email'])
            ->where('subject', $validated['subject'])
            ->where('message', $validated['message'])
            ->where('created_at', '>=', Carbon::now()->subMinutes(20))
            ->exists();

        if ($isDuplicate) {
            return redirect()
                ->route('contact.show')
                ->withErrors([
                    'message' => 'This message was already submitted recently. Please wait before submitting again.',
                ])
                ->withInput();
        }

        $submission = ContactSubmission::query()->create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?? null,
            'subject' => $validated['subject'],
            'enquiry_type' => $validated['enquiry_type'],
            'preferred_contact' => $validated['preferred_contact'] ?? null,
            'message' => $validated['message'],
            'ip_address' => $request->ip(),
            'user_agent' => (string) $request->userAgent(),
            'status' => 'new',
        ]);

        AdminNotifier::trySend('New contact form message', [
            'Subject: '.$submission->subject,
            'Enquiry type: '.($submission->enquiry_type ?? 'general'),
            'Preferred contact: '.($submission->preferred_contact ?? 'not specified'),
            'From: '.$submission->name.' <'.$submission->email.'>',
            'Phone: '.($submission->phone ?? '—'),
            'Message:',
            $submission->message,
        ]);

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