<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FeedbackReport;
use App\Mail\FeedbackMail;
use Illuminate\Support\Facades\Mail;

class FeedbackReportController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'nullable|string|max:255',
            'emel' => 'nullable|email|max:255',
            'mesej' => 'required|string|max:2000'
        ]);

        // simpan ke database
        $feedback = FeedbackReport::create([
            'nama' => $request->nama,
            'emel' => $request->emel,
            'mesej' => $request->mesej,
            'halaman_url' => $request->halaman_url,
            'status' => 'baru'
        ]);

        // hantar email ke admin
        try {
            $adminEmail = config('mail.from.address', 'admin@example.com');
            Mail::to($adminEmail)->send(new FeedbackMail($feedback));
        } catch (\Throwable $e) {
            \Log::warning('Feedback mail gagal dihantar: ' . $e->getMessage());
        }

        if ($request->wantsJson() || $request->ajax()) {
            return response()->json(['success' => true, 'message' => 'Feedback berjaya dihantar']);
        }
        return back()->with('success', 'Feedback berjaya dihantar');
    }
}
