<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Hash;
use App\Model\Master\LeadmineProRegistration;
use App\Services\OtpServices;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;

class LeadRegisterController extends Controller
{
    // Simple debug logger function
    private function logToFile($data, $filename = 'lead-register-debug.txt')
    {
        $file = storage_path('app/' . $filename);
        $content = "[" . date('Y-m-d H:i:s') . "]\n" . (is_string($data) ? $data : json_encode($data, JSON_PRETTY_PRINT)) . "\n\n";
        file_put_contents($file, $content, FILE_APPEND);
    }

    public function store(Request $request, OtpServices $otpService)
    {
        $this->logToFile(['step' => 'store:start', 'request' => $request->all()]);
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'company_name' => 'required',
            'password' => 'required|confirmed|min:6'
        ]);
        $this->logToFile(['step' => 'store:validation', 'result' => $validator->fails(), 'errors' => $validator->errors()]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $emailOtp = rand(100000, 999999);
        $mobileOtp = rand(100000, 999999);
        $this->logToFile(['step' => 'store:otp', 'emailOtp' => $emailOtp, 'mobileOtp' => $mobileOtp]);

        $lead = LeadmineProRegistration::create([
            'name' => $request->name,
            'email' => $request->email,
            'company_name' => $request->company_name,
            'phone' => $request->phone,
            'password' => Hash::make($request->password),
            'email_otp' => $emailOtp,
            'mobile_otp' => $mobileOtp,
        ]);
        $this->logToFile(['step' => 'store:lead_created', 'lead' => $lead]);

        // Send OTP via OtpServices (handles routing internally)
        $otpResult = $otpService->sendOtp($lead->phone, $mobileOtp);
        $this->logToFile([
            'step' => 'store:send_mobile_otp',
            'phone' => $lead->phone,
            'success' => $otpResult['success'] ?? false,
            'message' => $otpResult['message'] ?? 'Unknown',
            'response' => $otpResult
        ]);

        // Send email OTP
        $emailHtml = view('emails.leadmine-pro.email-otp', [
            'name' => $lead->name,
            'otp' => $emailOtp
        ])->render();
        send_sendgrid_mail(
            $lead->email,
            "Email Verification Code",
            $emailHtml
        );
        $this->logToFile(['step' => 'store:send_email_otp', 'email' => $lead->email]);

        // Send admin notification on registration
        $adminEmail = env('ADMIN_NOTIFY_EMAIL');
        if (!empty($adminEmail)) {
            $adminHtml = view('emails.leadmine-pro.new-registration', [
                'name' => $lead->name,
                'email' => $lead->email,
                'company' => $lead->company_name,
                'phone' => $lead->phone,
                'message' => '✅ User just registered on the platform',
            ])->render();
            $subject = "[LeadMinePro] Registration: {$lead->name} <{$lead->email}>";
            send_sendgrid_mail(
                $adminEmail,
                $subject,
                $adminHtml
            );
        }

        $this->logToFile(['step' => 'store:end', 'lead' => $lead->email]);
        return response()->json([
            'success' => true,
            'email' => $lead->email
        ]);
    }



    public function verifyEmail(Request $request)
    {
        $this->logToFile(['step' => 'verifyEmail:start', 'request' => $request->all()]);
        $lead = LeadmineProRegistration::where('email', $request->email)->latest()->first();

        if (!$lead) {
            return response()->json(['success' => false, 'message' => 'Lead not found'], 422);
        }

        if ($lead->email_otp != $request->email_otp) {
            return response()->json(['success' => false, 'message' => 'Invalid Email OTP'], 422);
        }
        $this->logToFile(['step' => 'verifyEmail:otp_match', 'lead' => $lead]);

        $lead->update([
            'email_verified_at' => Carbon::now(),
        ]);

        // Send admin notification on email verification
        $adminEmail = env('ADMIN_NOTIFY_EMAIL');
        if (!empty($adminEmail) && $lead) {
            $adminHtml = view('emails.leadmine-pro.new-registration', [
                'name' => $lead->name,
                'email' => $lead->email,
                'company' => $lead->company_name,
                'phone' => $lead->phone,
                'message' => '✉️ User verified their email address',
            ])->render();
            $subject = "[LeadMinePro] Registration: {$lead->name} <{$lead->email}>";
            send_sendgrid_mail(
                $adminEmail,
                $subject,
                $adminHtml
            );
        }
        $this->logToFile(['step' => 'verifyEmail:end', 'lead' => $lead->email]);

        return response()->json([
            'success' => true,
            'message' => 'Email verified'
        ]);
    }


    public function verifyMobile(Request $request, OtpServices $otpService)
    {
        $this->logToFile(['step' => 'verifyMobile:start', 'request' => $request->all()]);
        $lead = LeadmineProRegistration::where('email', $request->email)->latest()->first();

        if (!$lead) {
            return response()->json(['success' => false, 'message' => 'Lead not found'], 404);
        }

        if ($lead->mobile_otp != $request->mobile_otp) {
            return response()->json(['success' => false, 'message' => 'Invalid Mobile OTP'], 422);
        }
        $this->logToFile(['step' => 'verifyMobile:otp_match', 'lead' => $lead]);

        $lead->update([
            'mobile_verified_at' => Carbon::now(),
            'phone' => $request->phone,
            'country_code' => $request->country_code
        ]);

        // SEND WELCOME MAIL
        $this->logToFile(['step' => 'verifyMobile:send_welcome', 'lead' => $lead->email]);
        if (!empty($lead->email)) {
            $welcomeHtml = view('emails.leadmine-pro.thankyou-message-user', [
                'name' => $lead->name,
                'email' => $lead->email,
                'company' => $lead->company_name
            ])->render();

            send_sendgrid_mail(
                $lead->email,
                "Welcome to LeadMine Pro",
                $welcomeHtml
            );
        }

        // SEND ADMIN NOTIFICATION
        $adminEmail = env('ADMIN_NOTIFY_EMAIL');
        $this->logToFile(['step' => 'verifyMobile:send_admin', 'adminEmail' => $adminEmail]);
        if (!empty($adminEmail)) {
            $adminHtml = view('emails.leadmine-pro.new-registration', [
                'name' => $lead->name,
                'email' => $lead->email,
                'company' => $lead->company_name,
                'phone' => $lead->phone,
                'message' => '📱 User verified their mobile number - Registration Complete!',
            ])->render();
            $subject = "[LeadMinePro] Registration: {$lead->name} <{$lead->email}>";
            send_sendgrid_mail(
                $adminEmail,
                $subject,
                $adminHtml
            );
        }

        $this->logToFile(['step' => 'verifyMobile:end', 'lead' => $lead->email]);
        return response()->json([
            'success' => true
        ]);
    }


    public function resendEmailOtp(Request $request)
    {
        $this->logToFile(['step' => 'resendEmailOtp:start', 'request' => $request->all()]);
        $lead = LeadmineProRegistration::where('email', $request->email)->first();
        if (!$lead)
            return response()->json(['success' => false], 404);

        $otp = rand(100000, 999999);
        $this->logToFile(['step' => 'resendEmailOtp:otp', 'otp' => $otp]);
        $lead->update(['email_otp' => $otp]);
        $this->logToFile(['step' => 'resendEmailOtp:updated', 'lead' => $lead]);

        $emailHtml = view('emails.leadmine-pro.email-otp', [
            'name' => $lead->name,
            'otp' => $otp
        ])->render();
        send_sendgrid_mail(
            $lead->email,
            "Email Verification Code",
            $emailHtml
        );
        $this->logToFile(['step' => 'resendEmailOtp:end', 'lead' => $lead->email]);

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


    public function resendMobileOtp(Request $request, OtpServices $otpService)
    {
        $this->logToFile(['step' => 'resendMobileOtp:start', 'request' => $request->all()]);
        $lead = LeadmineProRegistration::where('email', $request->email)->first();
        if (!$lead)
            return response()->json(['success' => false], 404);

        $otp = rand(100000, 999999);
        $this->logToFile(['step' => 'resendMobileOtp:otp', 'otp' => $otp]);
        $lead->update(['mobile_otp' => $otp]);
        $this->logToFile(['step' => 'resendMobileOtp:updated', 'lead' => $lead]);

        // Send OTP via OtpServices (handles routing internally)
        $fullPhone = $lead->country_code . $lead->phone;
        $this->logToFile(['step' => 'resendMobileOtp:send_otp_start', 'phone' => $fullPhone]);
        $otpResult = $otpService->sendOtp($fullPhone, $otp);
        $this->logToFile([
            'step' => 'resendMobileOtp:send_otp_result',
            'phone' => $fullPhone,
            'success' => $otpResult['success'] ?? false,
            'message' => $otpResult['message'] ?? 'Unknown',
            'response' => $otpResult
        ]);
        $this->logToFile(['step' => 'resendMobileOtp:end', 'lead' => $lead->email]);

        return response()->json(['success' => true]);
    }
    public function contact(Request $request)
    {
        $this->logToFile(['step' => 'contact:start', 'request' => $request->all()]);
        $lead = LeadmineProRegistration::create([
            'name' => $request->name,
            'email' => $request->email,
            'message' => $request->message ?? 'N/A',
            'type' => 'contactus',
            'phone' => $request->phone ?? 'N/A',
            'company_name' => $request->company_name ?? 'N/A',
        ]);
        $this->logToFile(['step' => 'contact:lead_created', 'lead' => $lead]);

        $userHtml = view('emails.leadmine-pro.new-enquiry-user', [
            'name' => $lead->name,
            'email' => $lead->email,
            'phone' => $lead->phone,
            'message' => $lead->message,
        ])->render();

        $this->logToFile(['step' => 'contact:send_user_mail', 'email' => $lead->email]);
        send_sendgrid_mail(
            $lead->email,
            "Thank You for Contacting Us",
            $userHtml
        );

        $adminHtml = view('emails.leadmine-pro.new-enquiry', [
            'name' => $lead->name,
            'email' => $lead->email,
            'phone' => $lead->phone,
            'message' => $lead->message,
        ])->render();

        $this->logToFile(['step' => 'contact:send_admin_mail', 'email' => env('ADMIN_NOTIFY_EMAIL')]);
        send_sendgrid_mail(
            env('ADMIN_NOTIFY_EMAIL'),
            "New Contact Enquiry",
            $adminHtml
        );

        $this->logToFile(['step' => 'contact:end', 'lead' => $lead->email]);
        return response()->json([
            'success' => true,
            'message' => 'Contact request submitted successfully.'
        ]);
    }

    public function listAll()
    {
        $data = LeadmineProRegistration::orderBy('id', 'desc')->get();

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