<?php

namespace App\Models;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class GuestbookEntry extends Model
{
    use HasFactory;
    protected $table = "guestbook__entries";
    protected $fillable = ['name', 'message',
        'flagged'
    ];

    /**
     * Creates a new guestbook entry.
     *
     * @param Request $request The HTTP POST request
     * @return GuestbookEntry
     */
    public static function create(Request $request): GuestbookEntry {
        $newEntry = new GuestbookEntry;
        $newEntry->name = $request->get('name');
        $newEntry->message = $request->get('message');
        $newEntry->ip = $request->ip() ?: '0.0.0.0';
        $newEntry->agent = $request->userAgent();
        $newEntry->flagged = true;
        $newEntry->save();
        return $newEntry;
    }

    public static function get() {
        if (Auth::check()) {
            return GuestbookEntry::select()->orderBy('created_at', 'desc')->get();
        }
        return GuestbookEntry::where("flagged", false)->orderBy('created_at', 'desc')->get();
    }
}
