<?php

namespace App\Http\Controllers;

use App\Models\GuestbookEntry;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Contracts\View\View;
use Illuminate\Validation\ValidationException;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;
use UAParser\Parser;

class GuestbookController extends Controller {
    public function show(): View {
        $entries = GuestbookEntry::get();
        $parser = Parser::create();

        return view('guestbook')
            ->with('entries', $entries)
            ->with('parser', $parser);
    }

    /**
     * Creates a new guestbook entry
     *
     * @param Request $request
     * @return RedirectResponse
     * @throws ValidationException
     */
    public function addEntry(Request $request): RedirectResponse {
        $newEntry = GuestbookEntry::create($request);
        $email = (new MailtrapEmail())
            ->from(new Address("wah@wah.moe", "wah dot moe"))
            ->to(new Address("roscoe@wah.moe", "Roscoe D. Wah"))
            ->subject("New Guestbook Entry!")
            ->html('
<style> td { padding: 5px } </style>
<table border="1">
<tr><td><b>Name:</b></td><td>'.htmlentities($newEntry->name).'</td></tr>
<tr><td><b>IP:</b></td><td>'.$newEntry->ip.'</td></tr>
<tr><td><b>Agent:</b></td><td>'.htmlentities($newEntry->agent).'</td></tr>
<tr><td><b>Message:</b></td><td>'.htmlentities($newEntry->message).'</td></tr>
</table>');

        MailtrapClient::initSendingEmails(
            apiKey: config('services.mailtrap-sdk.apiKey')
        )->send($email);

        return back()->with('success', 'Entry submitted successfully!');
    }

    public function destroy($id): RedirectResponse {
        $entry = GuestbookEntry::findOrFail($id);
        $entry->delete();
        return redirect()->route('guestbook');
    }

    public function flag($id): RedirectResponse {
        $entry = GuestbookEntry::where("id", $id)->get()->first;
        $entry->update([
            "flagged" => !$entry->flagged,
        ]);
        return redirect()->route('guestbook');
    }
}
