<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactMail;

class ContactController extends Controller
{
    // Show contact form submissions in admin
    public function index()
    {
        $contacts = Contact::latest()->get(); // latest first
        return view('admin.contact.index', compact('contacts'));
    }

    // Store contact from frontend
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'nullable|string|max:20',
            'message' => 'required|string',
        ]);

        $data = $request->only('name', 'email', 'phone', 'message');

        // Save to DB
        Contact::create($data);

        // Send mail to admin
        Mail::to('trinexa.service@gmail.com')->send(new ContactMail($data));

        // Send thank you mail to user
        Mail::send('emails.thankyou', ['data' => $data], function($message) use ($data) {
            $message->to($data['email'])
                    ->subject('Thank You for Contacting Us');
        });

        return response()->json(['success' => true, 'message' => 'Message sent successfully!']);
    }

    // Delete contact
    public function destroy($id)
    {
        $contact = Contact::findOrFail($id);
        $contact->delete();

        return redirect()->route('admin.contact.index')->with('success', 'Contact deleted successfully!');
    }
}
