<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\HelperTrait;
use App\Models\DemoRequest;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;


class DemoRequestController extends Controller
{
    use HelperTrait;
    /**
     * Display a listing of demo requests with filters and pagination.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = DemoRequest::query();
            
            // Order by latest first (default)
            $query->orderBy('created_at', 'desc');
            
            // Apply custom search if provided
            if ($request->has('search') && $request->search) {
                $search = $request->search;
                $query->where(function ($q) use ($search) {
                    $q->where('first_name', 'LIKE', "%{$search}%")
                      ->orWhere('last_name', 'LIKE', "%{$search}%")
                      ->orWhere('work_email', 'LIKE', "%{$search}%")
                      ->orWhere('company_name', 'LIKE', "%{$search}%")
                      ->orWhere('phone', 'LIKE', "%{$search}%")
                      ->orWhere('company_type', 'LIKE', "%{$search}%");
                });
            }
            
            // Apply date range filters if provided
            if ($request->has('date_from') && $request->date_from) {
                $query->whereDate('created_at', '>=', $request->date_from);
            }
            
            if ($request->has('date_to') && $request->date_to) {
                $query->whereDate('created_at', '<=', $request->date_to);
            }
            
            // Apply email_consent filter if provided
            if ($request->has('email_consent') && $request->email_consent !== '') {
                $query->where('email_consent', filter_var($request->email_consent, FILTER_VALIDATE_BOOLEAN));
            }
            
            
            // Otherwise return all records with count
            return $this->withCount($query, 'Demo requests retrieved successfully');
            
        } catch (\Exception $e) {
            return $this->error('An error occurred while retrieving demo requests: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Store a newly created demo request form submission.
     *
     * @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',
            'work_email' => 'required|email|max:255',
            'company_name' => 'required|string|max:255',
            'phone' => 'required|string|max:20',
            'company_type' => 'required|string|max:255',
            'email_consent' => 'nullable|boolean',
            'company_size' => 'required|integer',
        ]);

        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 Demo Request', [
                'status' => $response->status(),
                'result' => $result
            ]);

            // Check if HTTP request was successful
            if (!$response->successful()) {
                \Illuminate\Support\Facades\Log::error('reCAPTCHA API request failed Demo Request', [
                    '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 Demo Request', [
                    'error_codes' => $errorCodes,
                    'result' => $result
                ]);
                return $this->error('reCAPTCHA verification failed. Please try again.', 422);
            }
        }

        // Create the demo request entry
        $demoRequest = DemoRequest::create($validated);

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

        // Send confirmation email to user
        $this->sendDemoRequestEmail(
            $demoRequest->work_email,
            'Thank you for your demo request - ' . config('app.name'),
            'Thank you for your demo request',
            $emailData,
            false
        );

        // Send notification email to admin
        $adminEmail = $this->getAdminSalesEmail();
        if ($adminEmail) {
            $this->sendDemoRequestEmail(
                $adminEmail,
                'New Demo Request Submission - ' . config('app.name'),
                'New Demo Request Submission',
                $emailData,
                true
            );
        }

        return $this->success($demoRequest, 'Your demo request has been submitted successfully. We will contact you soon.');
    }

    /**
     * Display the specified demo request.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): JsonResponse
    {
        try {
            $demoRequest = DemoRequest::findOrFail($id);

            return $this->success($demoRequest, 'Demo request retrieved successfully.');
        } catch (\Exception $e) {
            return $this->error('Demo request not found.', 404);
        }
    }

    /**
     * Remove the specified demo request from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): JsonResponse
    {
        try {
            $demoRequest = DemoRequest::findOrFail($id);
            $demoRequest->delete();

            return $this->success(null, 'Demo request deleted successfully.');
        } catch (\Exception $e) {
            return $this->error('Demo request not found.', 404);
        }
    }
    private function sendDemoRequestEmail(string $to, string $subject, string $emailSubject, array $data, bool $isAdmin): void
    {
        $emailParams = [
            'to' => $to,
            'subject' => $subject,
            'msg' => view('Emails.demo-request', array_merge($data, [
                'subject' => $emailSubject,
                'is_admin_notification' => $isAdmin,
            ]))->render()
        ];

        $this->SendInstantEmail($emailParams);
    }

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

