<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Faq;
use App\Models\Artikel;
use Illuminate\Support\Facades\Mail;

class LandingControllers extends Controller
{
    public function index()
    {
        $faqs = Faq::latest()->take(5)->get();
        $artikels = Artikel::latest()->take(7)->get();

        return view('landing-page.welcome', compact('faqs', 'artikels'));
    }

    public function sendContactMail(Request $request)
    {
        $request->validate([
            'subject' => 'required|string|max:100',
            'email'   => 'required|email',
            'message' => 'required|string'
        ]);

        try {
            $senderEmail = $request->email;
            $msgSubject  = $request->subject;
            $msgContent  = $request->message;

            $emailBody = "Halo Admin PeGas,\n\nAnda menerima pesan baru dari formulir kontak Landing Page.\n\n";
            $emailBody .= "Pengirim: " . $msgSubject . " (" . $senderEmail . ")\n";
            $emailBody .= "Isi Pesan:\n" . $msgContent . "\n\n";
            $emailBody .= "Sistem Informasi Manajemen Stok LPG PeGas 2026.";

            Mail::raw($emailBody, function ($message) use ($senderEmail, $msgSubject) {
                $message->to('pegaslpgsystem@gmail.com')
                        ->from($senderEmail)
                        ->subject("MESSAGES: " . $msgSubject);
            });

            return response()->json([
                'success' => true,
                'message' => 'Pesan berhasil dikirim ke email pegaslpgsystem@gmail.com'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengirim pesan: ' . $e->getMessage()
            ], 500);
        }
    }
}