<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RSVP;
use App\Models\GuestBook;

class MainController extends Controller
{
    public function main(Request $request) {
        $rsvp = RSVP::all();
        $guestbooks = GuestBook::orderBy('created_at', 'desc')->take(5)->get();
        $totalPages = $guestbooks->count();

        $host = $request->getHost();
        if ($host == 'aliffayuna.com') {
            return view('digital-card', compact(['rsvp', 'guestbooks']));
        } else if ($host == 'rsvp.aliffayuna.com') {
            return view('rsvp-digital-card');
        } else {
            return view('digital-card', compact(['rsvp', 'guestbooks', 'totalPages']));
            // return view('rsvp-digital-card');
        }
    }

    public function saveRsvp(Request $request) {
        RSVP::create([
            'name' => $request->name,
            'member' => $request->member,
            'phone' => $request->phone
        ]);

        session()->flash('success', 'Terima kasih kerana sudi menghadirkan diri!');

        return response()->json(['message' => 'Terima kasih kerana sudi menghadirkan diri!']);
    }

    public function saveSpeech(Request $request) {
        GuestBook::create([
            'name' => $request->name,
            'speech' => $request->speech
        ]);

        session()->flash('success', 'Terima kasih atas ucapan anda!');

        return response()->json(['message' => 'Terima kasih atas ucapan anda!']);
    }

    public function fetchGuestbook(Request $request)
    {
        $page = $request->input('page', 1); // Default to page 1 if no page is provided
        $guestbook = GuestBook::orderBy('created_at', 'desc')->take(5)->get()->forPage($page, 1);

        return response()->json([
            'guestbook' => view('partials.guestbook', ['entry' => $guestbook->first()])->render(),
        ]);
    }

}