<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\HelperTrait;
use App\Models\ContactUs;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;


class ContactUsController extends Controller
{
    use HelperTrait;
    /**
     * Store a newly created contact us form submission in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request): JsonResponse
    {
        // Validate the incoming request
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'phone_number' => 'required|string|max:20',
            'message' => 'required|string|max:5000',
        ]);

        if ($request->has('captcha_token')) {
            $captchaToken = $request->captcha_token;
            $secretKey = config('services.recaptcha.secret');
            $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
                'secret' => $secretKey,
                'response' => $captchaToken,
            ]);

            $result = $response->json();
            // Log the response for debugging (remove in production if needed)
            \Illuminate\Support\Facades\Log::info('reCAPTCHA verification response', [
                'status' => $response->status(),
                'result' => $result
            ]);

            // Check if HTTP request was successful
            if (!$response->successful()) {
                \Illuminate\Support\Facades\Log::error('reCAPTCHA API request failed', [
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);
                return $this->error('reCAPTCHA verification service unavailable. Please try again later.', 503);
            }

            // Check if reCAPTCHA verification was successful
            if (!isset($result['success']) || !$result['success']) {
                $errorCodes = $result['error-codes'] ?? [];
                \Illuminate\Support\Facades\Log::warning('reCAPTCHA verification failed', [
                    'error_codes' => $errorCodes,
                    'result' => $result
                ]);
                return $this->error('reCAPTCHA verification failed. Please try again.', 422);
            }
        }

        // Create the contact us entry
        $contactUs = ContactUs::create($validated);

        // Prepare common email data
        $emailData = array_merge($validated, [
            'submitted_at' => $contactUs->created_at,
        ]);

        // Send confirmation email to user
        $this->sendContactEmail(
            $contactUs->email,
            'Thank you for contacting us - ' . config('app.name'),
            'Thank you for contacting us',
            $emailData,
            false
        );
        // Send notification email to admin
        $adminEmail = $this->getAdminSalesEmail();
        if ($adminEmail) {
            $this->sendContactEmail(
                $adminEmail,
                'New Contact Form Submission - ' . config('app.name'),
                'New Contact Form Submission',
                $emailData,
                true
            );
        }
        return $this->success($contactUs, 'Your message has been sent successfully. We will get back to you soon.');
    }


    /**
     * Display a listing of the contact us submissions.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = $request->get('per_page', 15);
            $contactSubmissions = ContactUs::orderBy('created_at', 'desc')
                ->paginate($perPage);

            return $this->success($contactSubmissions, 'Contact submissions retrieved successfully.');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    /**
     * Display the specified contact us submission.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): JsonResponse
    {
        try {
            $contactUs = ContactUs::findOrFail($id);

            return $this->success($contactUs, 'Contact submission retrieved successfully.');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 404);
        }
    }

    /**
     * Remove the specified contact us submission from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): JsonResponse
    {
        try {
            $contactUs = ContactUs::findOrFail($id);
            $contactUs->delete();

            return $this->success(null, 'Contact submission deleted successfully.');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }


    private function sendContactEmail(string $to, string $subject, string $emailSubject, array $data, bool $isAdmin): void
    {
        $emailParams = [
            'to' => $to,
            'subject' => $subject,
            'msg' => view('Emails.contact-us', array_merge($data, [
                'subject' => $emailSubject,
                'is_admin_notification' => $isAdmin,
            ]))->render()
        ];

        $this->SendInstantEmail($emailParams);
    }

    /**
     * Get admin sales email
     */
    private function getAdminSalesEmail(): ?string
    {
        return DB::table('adminsettings')
            ->where('customer_id', $this->getSuperAdminId())
            ->where('key', 'company_company_sales_email')
            ->value('value');
    }
}
