<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\NatureofInvestment;
use App\Models\ContactUs;
use App\Models\WhatWeDo;
use Illuminate\Support\Facades\Http;

class FrontendContactController extends Controller
{
    public function contactForm()
    {
        $natureOfInvestments = NatureofInvestment::where('status', 1)->orderBy('name')->get();
        return view('frontend.contact-us', compact('natureOfInvestments'));
    }

    public function store(Request $request)
    {
        // Step 1: Validate input
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:20',
            'city' => 'nullable|string|max:255',
            'nature_of_work' => 'nullable|array',
            'nature_of_work.*' => 'integer',
            'g-recaptcha-response' => 'required'
        ]);

        // Step 2: Verify reCAPTCHA with Google
        $recaptchaResponse = $request->input('g-recaptcha-response');
        $googleResponse = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
            'secret'   => env('RECAPTCHA_SECRET_KEY'),
            'response' => $recaptchaResponse,
            'remoteip' => $request->ip()
        ]);

        $captchaResult = $googleResponse->json();

        if (!($captchaResult['success'] ?? false)) {
            return back()
                ->withErrors(['captcha' => 'reCAPTCHA verification failed. Please try again.'])
                ->withInput();
        }

        // Step 3: Save Contact
        ContactUs::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'city' => $request->city,
            'nature_of_work' => is_array($request->nature_of_work)
                ? implode(',', $request->nature_of_work)
                : null,
        ]);

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

}
