<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\ContactFormMail;
use Illuminate\Support\Facades\Http; 
use Illuminate\Support\Facades\Log;

class ContactController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'email' => 'required|email|max:255',
            'subject' => 'required|string|max:255',
            'message' => 'required|string|min:10',
            'g-recaptcha-response' => ['required', function ($attribute, $value, $fail) {
                $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
                    'secret' => env('RECAPTCHA_SECRET_KEY'),
                    'response' => $value,
                ])->json();

                if (!isset($response['success']) || !$response['success'] || $response['score'] < 0.5) {
                    $fail('The reCAPTCHA verification failed. Please try again.');
                }
            }],
        
        ]);

        try {
            Mail::to('rahul@abssoft.com.np')->send(new ContactFormMail($validated));
        } catch (\Exception $e) {
            Log::error("Mail sending failed: " . $e->getMessage());
            return back()->with('error', 'Sorry, there was an issue sending your message. Please try again later.');
        }
        
        return back()->with('success', 'Thank you for your message! I will get back to you shortly.');
    }
}