<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Message;
use Illuminate\Support\Facades\Auth;

class MessageController extends Controller {
    public function index() {
        $messages = Message::latest()->take(5)->get(); // Ambil 5 pesan terbaru
        return view('layouts.navbar', compact('messages')); // Pastikan layout navbar menerima data ini
    }
    
    public function store(Request $request) {
        $request->validate([
            'contact-name' => 'required',
            'contact-email' => 'required|email',
            'contact-phone' => 'required',
            'contact-subject' => 'required',
            'contact-message' => 'required',
        ]);

        // Pastikan user sudah login sebelum menyimpan pesan
        if (!Auth::check()) {
            return response()->json(['success' => false, 'message' => 'Anda harus login untuk mengirim pesan!'], 401);
        }

        // Simpan pesan dengan user_id sesuai akun yang login
        Message::create([
            'user_id' => Auth::id(), // Ambil ID user yang sedang login
            'name' => $request->input('contact-name'),
            'email' => $request->input('contact-email'),
            'phone' => $request->input('contact-phone'),
            'subject' => $request->input('contact-subject'),
            'message' => $request->input('contact-message'),
        ]);

        return response()->json(['success' => true, 'message' => 'Pesan berhasil dikirim!']);
    }    
}
