<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;
use App\Mail\ContactEnquiry;
use App\Mail\ContactThankYou;
use App\Models\Inquiry;
use App\Models\Service;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class ContactController extends Controller
{
    public function show()
    {
        $services = Service::where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        return view('pages.contact', [
            'services' => $services,
            'seo' => [
                'title'          => 'Contact Nexatech — Get in Touch for Technology Solutions',
                'description'    => 'Contact Nexatech for expert technology solutions, web development services, and digital consulting. Our team is ready to help your business grow.',
                'keywords'       => 'contact Nexatech, Nexatech support, Nexatech contact, IT services contact',
                'og_title'       => 'Contact Nexatech | Technology & Digital Solutions',
                'og_description' => 'Reach out to Nexatech for professional technology services, web development, and digital solutions tailored to your business needs.',
                'og_image'       => asset('images/og-img.jpg'),
                'canonical'      => url()->current(),
                'breadcrumb'     => 'Contact',
            ],
        ]);
    }

    public function submit(ContactRequest $request)
    {
        // Verify reCAPTCHA v3 token with Google
        $recaptchaResponse = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
            'secret'   => config('services.recaptcha.secret_key'),
            'response' => $request->recaptcha_token,
            'remoteip' => $request->ip(),
        ]);

        $recaptchaData = $recaptchaResponse->json();

        if (
            !($recaptchaData['success'] ?? false)
            || ($recaptchaData['score'] ?? 0) < 0.5
            || ($recaptchaData['action'] ?? '') !== 'contact_submit'
        ) {
            return response()->json([
                'success' => false,
                'errors'  => ['recaptcha_token' => ['reCAPTCHA verification failed. Please try again.']],
            ], 422);
        }

        $inquiry = Inquiry::create([
            'first_name'    => $request->firstName,
            'last_name'     => $request->lastName,
            'email'         => $request->email,
            'company'       => $request->company,
            'service_id'    => $request->service,
            'message'       => $request->message ?? '',
            'ip'            => $request->ip(),
            'browser'       => $request->userAgent(),
            'location_info' => $this->getLocationInfo($request->ip()),
        ]);

        // Send notification emails
        try {
            $recipients = array_map('trim', explode(',', config('services.contact_mail_to')));
            foreach ($recipients as $recipient) {
                Mail::to($recipient)->send(new ContactEnquiry($inquiry));
            }

            Mail::to($inquiry->email)->send(new ContactThankYou($inquiry));
        } catch (\Exception $e) {
            Log::error('Contact mail failed for inquiry #' . $inquiry->id . ': ' . $e->getMessage());
        }

        return response()->json(['success' => true]);
    }

    private function getLocationInfo(string $ip): ?array
    {
        // Skip for localhost / private IPs
        if (in_array($ip, ['127.0.0.1', '::1']) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
            return null;
        }

        try {
            $response = Http::timeout(3)->get("http://ip-api.com/json/{$ip}?fields=status,country,regionName,city,isp");
            $data = $response->json();

            if (($data['status'] ?? '') === 'success') {
                return [
                    'country' => $data['country'] ?? null,
                    'region'  => $data['regionName'] ?? null,
                    'city'    => $data['city'] ?? null,
                    'isp'     => $data['isp'] ?? null,
                ];
            }
        } catch (\Exception $e) {
            // Silently fail — location is non-critical
        }

        return null;
    }
}
