<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class ContactController extends Controller
{
    private const SUBJECT = 'New Contact us page message';

    public function email(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
        ]);

        $this->createRecord([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'subject' => self::SUBJECT,
            'message' => $request->input('message'),
        ]);

        Mail::raw($this->formatMessage($request), function ($message) use ($request) {
            $message->to(config('app.email'))->subject(self::SUBJECT.' from '.$request->input('email'));
            $message->from(config('app.email'), $request->input('name'));
        });

        return redirect()->back()->with('success', 'Your message has been sent.');
    }

    public function trial(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
        ]);

        $this->createRecord([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'subject' => 'New Trial class request',
            'message' => 'Contact to book a trial class.',
        ]);

        Mail::raw($this->formatMessage($request), function ($message) use ($request) {
            $message->to(config('app.email'))->subject('New Trial class request from '.$request->input('email'));
            $message->from(config('app.email'), $request->input('name'));
        });

        return redirect()->back()->with('success', "We'll be in touch to book your trial class.");
    }

    public function formatMessage(Request $request): string
    {
        return <<<EOF
You have received a new contact message.
Name: {$request->input('name')}
Email: {$request->input('email')}
Message: {$request->input('message')}
EOF;
    }

    private function createRecord(array $data)
    {
        Contact::create([
            'name' => $data['name'] ?? '?',
            'email' => $data['email'] ?? '?',
            'subject' => $data['subject'] ?? '?',
            'message' => $data['message'] ?? null,
        ]);
    }
}
