<?php

namespace App\Http\Controllers;

use App\Models\ContactUs;
use App\Models\Property;
use App\Mail\ContactUsNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class ContactUsController extends Controller
{
    public function store(Request $request)
    {

        Log::info('Contact form submitted', $request->all());

        $validated = $request->validate([
            'name'          => 'required|string|max:255',
            'email'         => 'required|email',
            'number'        => 'required|string|max:20',
            'property_name' => 'nullable|string|max:255',
            'title'         => 'nullable|string|max:255', 
        ]);

        $propertyName = $validated['property_name'] ?? null;

        if ($propertyName && Property::where('property_name', $propertyName)->exists()) {
            $finalPropertyName = $propertyName;
        } else {
            $finalPropertyName = $validated['title'] ?? 'General Inquiry';
        }

        $validated['property_name'] = $finalPropertyName;

        unset($validated['title']);

        //dd($request->all());

        ContactUs::create($validated);

        Mail::to('mdarif.developer@gmail.com')->send(new ContactUsNotification($validated));

        return back()->with('success', 'Thank you for contacting us!');
    }

}

