<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\CustomerCreditScore;
use App\Models\CreditScoreTier;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;
use App\Services\SmsService; // Import your service
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class CustomerAuthController extends Controller
{
    // ==================== WEB METHODS ====================
    protected $smsService;
    /**
     * Show customer registration step 1 form (email & password)
     */
     
     
    public function __construct(SmsService $smsService)
    {
        $this->smsService = $smsService;
    }
    public function showRegistrationForm()
    {
        return view('auth.customer-register-step1');
    }

    /**
     * Handle registration step 1 (email & password)
     */
    public function step1(Request $request)
    {
        $request->validate([
            'email' => 'required|email|unique:customer,email',
            'password' => 'required|string|min:8|confirmed',
        ]);

        // Store step 1 data in session
        $request->session()->put('registration.step1', [
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        return redirect()->route('customer.register.step2');
    }

    /**
     * Show registration step 2 form (profile picture only)
     */
    public function showStep2Form(Request $request)
    {
        // Check if step 1 is completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        return view('auth.customer-register-step2');
    }
    
   

    /**
     * Handle registration step 2 (profile picture only)
     */
    public function step2(Request $request)
    {
        // Check if step 1 is completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        $request->validate([
            'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        // Handle profile picture upload
        $profilePicturePath = null;
        if ($request->hasFile('profile_picture')) {
            $profilePicturePath = $this->handleProfilePictureUpload($request->file('profile_picture'));
        }

        // Handle webcam picture if provided
        if ($request->has('webcam_picture') && !empty($request->webcam_picture)) {
            $profilePicturePath = $this->handleWebcamPicture($request->webcam_picture);
        }

        // Store profile picture in session
        $request->session()->put('registration.step2', [
            'docpath' => $profilePicturePath,
        ]);

        return redirect()->route('customer.register.step3');
    }

    /**
     * Show registration step 3 form (personal information)
     */
    public function showStep3Form(Request $request)
    {
        // Check if step 1 and step 2 are completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        if (!$request->session()->has('registration.step2')) {
            return redirect()->route('customer.register.step2')->with('error', 'Please complete step 2 first.');
        }

        return view('auth.customer-register-step3');
    }

    /**
     * Handle registration step 3 (personal information)
     */
    public function step3(Request $request)
    {
        // Check if step 1 and step 2 are completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        if (!$request->session()->has('registration.step2')) {
            return redirect()->route('customer.register.step2')->with('error', 'Please complete step 2 first.');
        }

        $request->validate([
            'title' => 'required|string|max:10',
            'surname' => 'required|string|max:255',
            'first_name' => 'required|string|max:255',
            'middle_name' => 'nullable|string|max:255',
            'customer' => 'required|string|max:255',
            'dob' => 'required|date',
            'phone' => 'required|string|max:25',
            'office_phone' => 'nullable|string|max:25',
            'cgroup' => 'required|in:Individual,Company',
            'idtype' => 'required|string',
            'number' => 'required|string',
            'address' => 'required|string',
            'town' => 'required|string',
            'province' => 'required|string',
        ]);

        // Store step 3 data in session
        $step3Data = [
            'title' => $request->title,
            'surname' => $request->surname,
            'first_name' => $request->first_name,
            'middle_name' => $request->middle_name,
            'customer' => $request->customer,
            'dob' => $request->dob,
            'phone' => $request->phone,
            'office_phone' => $request->office_phone,
            'cgroup' => $request->cgroup,
            'idtype' => $request->idtype,
            'number' => $request->number,
            'address' => $request->address,
            'town' => $request->town,
            'province' => $request->province,
        ];

        $request->session()->put('registration.step3', $step3Data);

        return redirect()->route('customer.register.step4');
    }

    /**
     * Show registration step 4 form (NRC upload)
     */
    public function showStep4Form(Request $request)
    {
        // Check if previous steps are completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        if (!$request->session()->has('registration.step2')) {
            return redirect()->route('customer.register.step2')->with('error', 'Please complete step 2 first.');
        }

        if (!$request->session()->has('registration.step3')) {
            return redirect()->route('customer.register.step3')->with('error', 'Please complete step 3 first.');
        }

        return view('auth.customer-register-step4');
    }

    /**
     * Handle registration step 4 (NRC upload and verification)
     */
    public function step4(Request $request)
    {
        // Check if previous steps are completed
        if (!$request->session()->has('registration.step1')) {
            return redirect()->route('customer.register')->with('error', 'Please complete step 1 first.');
        }

        if (!$request->session()->has('registration.step2')) {
            return redirect()->route('customer.register.step2')->with('error', 'Please complete step 2 first.');
        }

        if (!$request->session()->has('registration.step3')) {
            return redirect()->route('customer.register.step3')->with('error', 'Please complete step 3 first.');
        }

        $request->validate([
            'nrc_front' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'nrc_back' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            'verification_status' => 'required|in:pending,verified,failed,skipped',
        ]);

        // Get all previous step data
        $step1Data = $request->session()->get('registration.step1');
        $step2Data = $request->session()->get('registration.step2');
        $step3Data = $request->session()->get('registration.step3');

        // Handle NRC file uploads
        $nrcFrontPath = null;
        $nrcBackPath = null;

        if ($request->hasFile('nrc_front')) {
            $nrcFrontPath = $this->handleNrcUpload($request->file('nrc_front'), 'front');
        }

        if ($request->hasFile('nrc_back')) {
            $nrcBackPath = $this->handleNrcUpload($request->file('nrc_back'), 'back');
        }

        // Generate customer number
        $customerNumber = $this->generateCustomerNumber();

        // Calculate default credit limit based on income (if provided in step 3)
        $defaultIncome = 5000; // Default assumption
        $creditLimit = $defaultIncome * 3; // 3x monthly income

        DB::beginTransaction();
        try {
            // Create customer with all data
            $customerData = array_merge($step3Data, [
                'email' => $step1Data['email'],
                'pass' => $step1Data['password'],
                'docpath' => $step2Data['docpath'] ?? null,
                'nrc_front_path' => $nrcFrontPath,
                'nrc_back_path' => $nrcBackPath,
                'verification_status' => $request->verification_status,
                'customer_number' => $customerNumber,
                'status' => 'Active',
                'postdate' => now(),
                'branchid' => 1,
                'companyid' => 1,
                'created_at' => now(),
                'updated_at' => now(),
                'income' => $defaultIncome, // Set default income for credit limit calculation
            ]);

            $customer = Customer::create($customerData);

            // Create default credit score immediately after customer is saved
            $this->createDefaultCreditScore($customer);

            // Clear registration session
            $request->session()->forget('registration');

            DB::commit();

            // Log registration
            // AuditLog::create([
            //     'customer_id' => $customer->id,
            //     'action' => 'registration',
            //     'description' => 'New customer registered: ' . $customer->customer . ' (Customer No: ' . $customerNumber . ')',
            //     'ip_address' => $request->ip(),
            //     'user_agent' => $request->userAgent(),
            // ]);

            // Log successful login
            // AuditLog::create([
            //     'customer_id' => $customer->id,
            //     'action' => 'login_success',
            //     'description' => 'Customer logged in after registration',
            //     'ip_address' => $request->ip(),
            //     'user_agent' => $request->userAgent(),
            // ]);

            // Login the customer after registration
            Auth::guard('customer')->login($customer);

            $message = 'Registration successful! Welcome to Immia Finance. Your customer number is: ' . $customerNumber;
            if ($request->verification_status === 'verified') {
                $message .= ' Your identity has been verified.';
            } elseif ($request->verification_status === 'failed') {
                $message .= ' Note: Identity verification failed. You may need to verify later for loan applications.';
            } elseif ($request->verification_status === 'skipped') {
                $message .= ' You can verify your identity later in your profile settings.';
            }

            return redirect()->route('customer.dashboard')->with('success', $message);

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Customer registration failed: ' . $e->getMessage(), [
                'exception' => $e
            ]);

            return redirect()->back()
                ->withInput()
                ->with('error', 'Registration failed. Please try again. Error: ' . $e->getMessage());
        }
    }

    /**
     * Show customer login form
     */
    public function showLoginForm()
    {
        return view('auth.customer-login');
    }

    /**
     * Handle customer login (Web)
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $customer = Customer::where('email', $request->email)
            ->where('status', 'Active')
            ->first();

        if (!$customer || !Hash::check($request->password, $customer->pass)) {
            // Log failed login attempt
            // AuditLog::create([
            //     'customer_id' => $customer ? $customer->id : null,
            //     'action' => 'login_failed',
            //     'description' => 'Failed login attempt for email: ' . $request->email,
            //     'ip_address' => $request->ip(),
            //     'user_agent' => $request->userAgent(),
            // ]);

            throw ValidationException::withMessages([
                'email' => ['The provided credentials are incorrect.'],
            ]);
        }

        // Check if customer has credit score, create if not
        if (!$customer->creditScores()->exists()) {
            $this->createDefaultCreditScore($customer);
        }

        // Log successful login
        // AuditLog::create([
        //     'customer_id' => $customer->id,
        //     'action' => 'login_success',
        //     'description' => 'Customer logged in successfully - Customer No: ' . ($customer->customer_number ?? 'N/A'),
        //     'ip_address' => $request->ip(),
        //     'user_agent' => $request->userAgent(),
        // ]);

        Auth::guard('customer')->login($customer, $request->boolean('remember'));

        return redirect()->intended(route('customer.dashboard'));
    }

    /**
     * Logout customer (Web)
     */
    public function logout(Request $request)
    {
        $customerNumber = null;
        
        // Log logout
        if (Auth::guard('customer')->check()) {
            $customer = Auth::guard('customer')->user();
            $customerNumber = $customer->customer_number;
            
            // AuditLog::create([
            //     'customer_id' => $customer->id,
            //     'action' => 'logout',
            //     'description' => 'Customer logged out - Customer No: ' . ($customerNumber ?? 'N/A'),
            //     'ip_address' => $request->ip(),
            //     'user_agent' => $request->userAgent(),
            // ]);
        }

        Auth::guard('customer')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')->with('success', 'You have been logged out successfully.');
    }

    // ==================== API METHODS (SESSION-BASED - NO TOKENS) ====================

    /**
     * Customer login via API (Session-based)
     */
    public function apiLogin(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'email' => 'required|email',
                'password' => 'required|string',
            ]);

            $customer = Customer::where('email', $request->email)
                ->where('status', 'Active')
                ->first();

            if (!$customer || !Hash::check($request->password, $customer->pass)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid credentials'
                ], 401);
            }

            // Check if customer has credit score, create if not
            if (!$customer->creditScores()->exists()) {
                $this->createDefaultCreditScore($customer);
            }

            return response()->json([
                'success' => true,
                'message' => 'Login successful',
                'data' => [
                    'customer' => [
                        'id' => $customer->id,
                        'customer_number' => $customer->customer_number,
                        'name' => $customer->customer,
                        'email' => $customer->email,
                        'phone' => $customer->phone,
                        'profile_picture' => $customer->docpath ? asset('storage/' . $customer->docpath) : null,
                        'credit_score' => $customer->currentCreditScore ? $customer->currentCreditScore->credit_score : 300,
                        'score_band' => $customer->currentCreditScore ? $customer->currentCreditScore->score_band : 'Very Poor',
                    ]
                ]
            ]);

        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            \Log::error('API Login error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Login failed. Please try again.'
            ], 500);
        }
    }

    /**
     * Customer registration via API (Session-based)
     */
    public function apiRegister(Request $request): JsonResponse
    {
        try {
            $request->validate([
                // Step 1: Account details
                'email' => 'required|email|unique:customer,email',
                'password' => 'required|string|min:8|confirmed',
                
                // Step 2: Personal information
                'title' => 'required|string|max:10',
                'surname' => 'required|string|max:255',
                'first_name' => 'required|string|max:255',
                'middle_name' => 'nullable|string|max:255',
                'customer' => 'required|string|max:255',
                'dob' => 'required|date',
                'phone' => 'required|string|max:25',
                'office_phone' => 'nullable|string|max:25',
                'cgroup' => 'required|in:Individual,Company',
                'idtype' => 'required|string',
                'number' => 'required|string',
                'address' => 'required|string',
                'town' => 'required|string',
                'province' => 'required|string',
                
                // Optional: Profile picture (base64)
                'profile_picture' => 'nullable|string',
                
                // Optional: NRC documents (base64)
                'nrc_front' => 'nullable|string',
                'nrc_back' => 'nullable|string',

                // Optional: Income for credit limit calculation
                'income' => 'nullable|numeric|min:0',
            ]);

            DB::beginTransaction();

            // Generate customer number
            $customerNumber = $this->generateCustomerNumber();

            // Handle profile picture upload if provided
            $profilePicturePath = null;
            if ($request->has('profile_picture') && !empty($request->profile_picture)) {
                $profilePicturePath = $this->handleBase64ImageUpload($request->profile_picture, 'profile-pictures', 'profile_');
            }

            // Handle NRC front upload if provided
            $nrcFrontPath = null;
            if ($request->has('nrc_front') && !empty($request->nrc_front)) {
                $nrcFrontPath = $this->handleBase64ImageUpload($request->nrc_front, 'nrc-documents', 'nrc_front_');
            }

            // Handle NRC back upload if provided
            $nrcBackPath = null;
            if ($request->has('nrc_back') && !empty($request->nrc_back)) {
                $nrcBackPath = $this->handleBase64ImageUpload($request->nrc_back, 'nrc-documents', 'nrc_back_');
            }

            // Calculate default credit limit based on income
            $defaultIncome = $request->income ?? 5000;
            $creditLimit = $defaultIncome * 3; // 3x monthly income

            // Create customer
            $customer = Customer::create([
                'email' => $request->email,
                'pass' => Hash::make($request->password),
                'title' => $request->title,
                'surname' => $request->surname,
                'first_name' => $request->first_name,
                'middle_name' => $request->middle_name,
                'customer' => $request->customer,
                'dob' => $request->dob,
                'phone' => $request->phone,
                'office_phone' => $request->office_phone,
                'cgroup' => $request->cgroup,
                'idtype' => $request->idtype,
                'number' => $request->number,
                'address' => $request->address,
                'town' => $request->town,
                'province' => $request->province,
                'docpath' => $profilePicturePath,
                'nrc_front_path' => $nrcFrontPath,
                'nrc_back_path' => $nrcBackPath,
                'verification_status' => 'pending',
                'customer_number' => $customerNumber,
                'status' => 'Active',
                'postdate' => now(),
                'branchid' => 1,
                'companyid' => 1,
                'created_at' => now(),
                'updated_at' => now(),
                'income' => $defaultIncome,
            ]);

            // Create default credit score immediately after customer is saved
            $this->createDefaultCreditScore($customer);

            // Login the customer using session (no tokens)
            Auth::guard('customer')->login($customer);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Registration successful! Your customer number is: ' . $customerNumber,
                'data' => [
                    'customer' => [
                        'id' => $customer->id,
                        'customer_number' => $customer->customer_number,
                        'name' => $customer->customer,
                        'email' => $customer->email,
                        'phone' => $customer->phone,
                        'profile_picture' => $customer->docpath ? asset('storage/' . $customer->docpath) : null,
                        'credit_score' => 300,
                        'score_band' => 'Very Poor',
                        'credit_limit' => $creditLimit,
                        'available_credit' => $creditLimit,
                    ]
                ]
            ]);

        } catch (ValidationException $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('API Registration error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Registration failed. Please try again.'
            ], 500);
        }
    }

    /**
     * Customer logout via API
     */
    public function apiLogout(Request $request): JsonResponse
    {
        $customerId = $request->query('customer_id');
        
        if (!$customerId) {
            return response()->json([
                'success' => false,
                'message' => 'Customer ID is required'
            ], 400);
        }

        $customer = Customer::where('id', $customerId)
            ->where('status', 'Active')
            ->first();

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

        // Perform any logout logic if needed
        // For simple approach, we just return success

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

    /**
     * Check if user is authenticated via API
     */
    public function apiCheckAuth(Request $request): JsonResponse
    {
        try {
            $customer = Auth::guard('customer')->user();

            if ($customer) {
                // Check if customer has credit score, create if not
                if (!$customer->creditScores()->exists()) {
                    $this->createDefaultCreditScore($customer);
                }

                return response()->json([
                    'success' => true,
                    'authenticated' => true,
                    'data' => [
                        'customer' => [
                            'id' => $customer->id,
                            'customer_number' => $customer->customer_number,
                            'name' => $customer->customer,
                            'email' => $customer->email,
                            'phone' => $customer->phone,
                            'profile_picture' => $customer->docpath ? asset('storage/' . $customer->docpath) : null,
                            'credit_score' => $customer->currentCreditScore ? $customer->currentCreditScore->credit_score : 300,
                            'score_band' => $customer->currentCreditScore ? $customer->currentCreditScore->score_band : 'Very Poor',
                        ]
                    ]
                ]);
            }

            return response()->json([
                'success' => true,
                'authenticated' => false,
                'message' => 'Not authenticated'
            ]);

        } catch (\Exception $e) {
            \Log::error('API Auth check error: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Authentication check failed'
            ], 500);
        }
    }

    /**
     * Get customer's current credit score (API endpoint)
     */
    public function apiGetCreditScore(Request $request): JsonResponse
    {
        try {
            $customer = Auth::guard('customer')->user();
            
            if (!$customer) {
                return response()->json([
                    'success' => false,
                    'message' => 'Customer not authenticated'
                ], 401);
            }

            // Check if customer has credit score, create if not
            if (!$customer->creditScores()->exists()) {
                $this->createDefaultCreditScore($customer);
            }

            $creditScore = $customer->currentCreditScore;

            if (!$creditScore) {
                // Create one if still doesn't exist
                $this->createDefaultCreditScore($customer);
                $creditScore = $customer->fresh()->currentCreditScore;
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'credit_score' => $creditScore->credit_score,
                    'score_band' => $creditScore->score_band,
                    'score_date' => $creditScore->score_date,
                    'credit_limit' => $creditScore->credit_limit,
                    'available_credit' => $creditScore->available_credit,
                    'credit_utilization' => $creditScore->credit_utilization_ratio,
                    'on_time_repayment_rate' => $creditScore->on_time_repayment_rate,
                ]
            ]);

        } catch (\Exception $e) {
            \Log::error('API Get Credit Score error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to get credit score'
            ], 500);
        }
    }

    // ==================== HELPER METHODS ====================

    /**
     * Create default credit score for a customer
     */
    private function createDefaultCreditScore(Customer $customer)
    {
        try {
            \Log::info("Creating default credit score for customer: {$customer->id} - {$customer->customer_number}");

            // Calculate default credit limit based on customer income
            $defaultIncome = $customer->income ?? 5000;
            $creditLimit = $defaultIncome * 3; // 3x monthly income
            
            // Determine score band for default score (300)
            $scoreBand = CustomerCreditScore::getScoreBand(300);

            // Create the credit score record
            $creditScore = CustomerCreditScore::create([
                'customer_id' => $customer->id,
                'credit_score' => 300,
                'score_band' => $scoreBand,
                'previous_score' => null,
                'score_change' => 0,
                'change_reason' => 'Initial credit score upon registration',
                'change_type' => 'initialization',
                'days_delinquent' => 0,
                'total_loans' => 0,
                'active_loans' => 0,
                'closed_loans' => 0,
                'defaulted_loans' => 0,
                'total_borrowed' => 0.00,
                'current_outstanding' => 0.00,
                'total_repaid' => 0.00,
                'on_time_repayment_rate' => 0.00,
                'late_payments_count' => 0,
                'missed_payments_count' => 0,
                'credit_utilization_ratio' => 0.00,
                'available_credit' => $creditLimit,
                'credit_limit' => $creditLimit,
                'last_repayment_date' => null,
                'last_repayment_amount' => 0.00,
                'last_loan_date' => null,
                'last_credit_inquiry' => null,
                'has_active_default' => false,
                'has_recent_late_payment' => false,
                'has_high_utilization' => false,
                'has_multiple_active_loans' => false,
                'score_date' => now()->toDateString(),
                'is_current' => true,
                'created_by' => 1, // System user ID
                'updated_by' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            \Log::info("Default credit score created successfully for customer: {$customer->id}");
            return $creditScore;

        } catch (\Exception $e) {
            \Log::error('Error creating default credit score: ' . $e->getMessage(), [
                'customer_id' => $customer->id,
                'customer_number' => $customer->customer_number,
                'error' => $e->getTraceAsString()
            ]);
            
            // Return false but don't throw - allow customer registration to continue
            return false;
        }
    }

    /**
     * Generate unique customer number in format CU00000001
     */
    private function generateCustomerNumber()
    {
        // Get the last customer number from the database
        $lastCustomer = Customer::orderBy('id', 'desc')->first();
        
        if ($lastCustomer && !empty($lastCustomer->customer_number)) {
            // Extract the numeric part and increment
            $lastNumber = (int) substr($lastCustomer->customer_number, 2);
            $newNumber = $lastNumber + 1;
        } else {
            // Start from 1 if no customers exist or no customer numbers set
            $newNumber = 1;
        }
        
        // Format the number with leading zeros and prefix
        $customerNumber = 'CU' . str_pad($newNumber, 8, '0', STR_PAD_LEFT);
        
        return $customerNumber;
    }

    /**
     * Handle NRC verification via AJAX (Web)
     */
    public function verifyNrc(Request $request)
    {
        $request->validate([
            'nrc_front' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            'profile_picture' => 'required|string', // base64 encoded
        ]);

        try {
            // In a real implementation, you would use a face recognition service
            // For demo purposes, we'll simulate the verification
            
            // Simulate processing time
            sleep(2);
            
            // Simulate verification result (80% success rate for demo)
            $isVerified = rand(1, 100) <= 80;
            
            return response()->json([
                'success' => true,
                'verified' => $isVerified,
                'confidence' => $isVerified ? rand(85, 98) : rand(40, 75),
                'message' => $isVerified 
                    ? 'Identity verification successful!' 
                    : 'Unable to verify identity. Please ensure the photos match.'
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Verification service temporarily unavailable. Please try again later.'
            ], 500);
        }
    }

    /**
     * Handle profile picture file upload (Web)
     */
    private function handleProfilePictureUpload($file)
    {
        $filename = 'profile_' . time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
        $path = 'profile-pictures/' . $filename;
        
        // Store the file directly without resizing
        $file->storeAs('profile-pictures', $filename, 'public');
        
        return $path;
    }

    /**
     * Handle webcam picture (base64) - Web
     */
    private function handleWebcamPicture($base64Image)
    {
        // Remove the data:image/png;base64, part
        $image = str_replace('data:image/png;base64,', '', $base64Image);
        $image = str_replace(' ', '+', $image);
        $imageData = base64_decode($image);

        $filename = 'webcam_profile_' . time() . '_' . uniqid() . '.png';
        $path = 'profile-pictures/' . $filename;

        // Store the webcam image directly without processing
        Storage::disk('public')->put($path, $imageData);

        return $path;
    }

    /**
     * Handle base64 image upload (API)
     */
    private function handleBase64ImageUpload($base64Image, $folder, $prefix): ?string
    {
        try {
            // Check if base64 string is valid
            if (preg_match('/^data:image\/(\w+);base64,/', $base64Image, $type)) {
                $image = substr($base64Image, strpos($base64Image, ',') + 1);
                $type = strtolower($type[1]); // jpg, png, gif

                if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                    throw new \Exception('Invalid image type');
                }

                $image = str_replace(' ', '+', $image);
                $imageData = base64_decode($image);

                if ($imageData === false) {
                    throw new \Exception('Base64 decode failed');
                }

                $filename = $prefix . time() . '_' . uniqid() . '.' . $type;
                $path = $folder . '/' . $filename;

                Storage::disk('public')->put($path, $imageData);

                return $path;
            }

            return null;
        } catch (\Exception $e) {
            \Log::error('Base64 image upload failed: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Handle NRC file upload (Web)
     */
    private function handleNrcUpload($file, $type)
    {
        $filename = 'nrc_' . $type . '_' . time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
        $path = 'nrc-documents/' . $filename;
        
        $file->storeAs('nrc-documents', $filename, 'public');
        
        return $path;
    }

    /**
     * Check if all registration steps are completed (Web)
     */
    private function isRegistrationComplete(Request $request)
    {
        return $request->session()->has('registration.step1') &&
               $request->session()->has('registration.step2') &&
               $request->session()->has('registration.step3');
    }

    /**
     * Get current registration progress (Web)
     */
    private function getRegistrationProgress(Request $request)
    {
        $progress = 0;
        if ($request->session()->has('registration.step1')) $progress += 25;
        if ($request->session()->has('registration.step2')) $progress += 25;
        if ($request->session()->has('registration.step3')) $progress += 25;
        if ($request->session()->has('registration.step4')) $progress += 25;
        
        return $progress;
    }

    /**
     * Update existing customers with customer numbers (one-time function)
     */
    public function updateExistingCustomersWithNumbers()
    {
        // This is a one-time function to update existing customers
        $customers = Customer::whereNull('customer_number')->get();
        
        foreach ($customers as $customer) {
            $customerNumber = $this->generateCustomerNumber();
            $customer->update(['customer_number' => $customerNumber]);
            echo "Updated customer {$customer->id} with number: {$customerNumber}\n";
        }
        
        return "Updated " . $customers->count() . " customers with customer numbers.";
    }

    /**
     * Fix missing credit scores for existing customers (one-time function)
     */
    public function fixMissingCreditScores()
    {
        $customersWithoutScores = Customer::whereDoesntHave('creditScores')->get();
        
        $this->info("Found {$customersWithoutScores->count()} customers without credit scores.");
        
        $created = 0;
        $failed = 0;
        
        foreach ($customersWithoutScores as $customer) {
            try {
                $this->createDefaultCreditScore($customer);
                $created++;
                echo "Created credit score for customer: {$customer->customer_number}\n";
            } catch (\Exception $e) {
                $failed++;
                echo "Failed for customer {$customer->customer_number}: {$e->getMessage()}\n";
            }
        }
        
        return "Completed. Created: {$created}, Failed: {$failed}";
    }
    
    
    /**
 * Show Forgot Password Form (Email/Phone input)
 */
public function showForgotPasswordForm()
{
    return view('auth.forgot-password');
}

/**
 * Handle OTP Generation and Sending
 */
public function sendOtp(Request $request)
{
    $request->validate(['identifier' => 'required']);

    $customer = Customer::where('email', $request->identifier)
                        ->orWhere('phone', $request->identifier)
                        ->first();

    if (!$customer) {
        return back()->withErrors(['identifier' => 'No account found.']);
    }

    $otp = rand(100000, 999999);
    
    session([
        'reset_otp' => $otp,
        'reset_customer_id' => $customer->id,
        'otp_expires_at' => now()->addMinutes(10)
    ]);

    $message = "Your Immia Finance reset code is: {$otp}. Valid for 10 minutes.";

    // --- 1. Handle SMS Sending & Logging ---
    $smsSent = $this->smsService->sendSms($customer->phone, $message);
    
    if ($smsSent) {
        Log::info("OTP SMS sent successfully to customer ID: {$customer->id} on phone: {$customer->phone}");
    } else {
        Log::error("OTP SMS failed to send for customer ID: {$customer->id} on phone: {$customer->phone}");
    }

    // --- 2. Handle Email Sending & Logging ---
    try {
        Mail::raw($message, function ($mail) use ($customer) {
            $mail->to($customer->email)
                 ->subject('Your Password Reset Code - Immia Finance');
        });
        Log::info("OTP Email sent successfully to customer ID: {$customer->id} at: {$customer->email}");
    } catch (\Exception $e) {
        Log::error("OTP Email failed for customer ID: {$customer->id}. Error: " . $e->getMessage());
    }

    return redirect()->route('customer.password.reset.form')
                     ->with('success', 'A verification code has been sent to your registered phone and email.');
}

/**
 * Show Reset Password Form (OTP & New Password)
 */
public function showResetForm()
{
    if (!session()->has('reset_otp')) {
        return redirect()->route('customer.password.request');
    }
    return view('auth.reset-password-otp');
}

/**
 * Process the Password Reset
 */
/**
 * Process the Password Reset and Login
 */


/**
 * Resend OTP to the customer
 */
public function resendOtp(Request $request)
{
    // 1. Check if we have a customer ID in session
    if (!session()->has('reset_customer_id')) {
        return redirect()->route('customer.password.request')
                         ->with('error', 'Session expired. Please enter your details again.');
    }

    // 2. Rate Limiting: Prevent resending more than once every 60 seconds
    $lastResend = session('otp_last_sent');
    if ($lastResend && now()->diffInSeconds($lastResend) < 60) {
        return back()->with('error', 'Please wait before requesting another code.');
    }

    $customer = Customer::find(session('reset_customer_id'));
    
    // 3. Generate NEW OTP
    $otp = rand(100000, 999999);
    $message = "Your new Immia Finance reset code is: {$otp}. Valid for 10 minutes.";

    // 4. Update session and Send
    session([
        'reset_otp' => $otp,
        'otp_expires_at' => now()->addMinutes(10),
        'otp_last_sent' => now()
    ]);

    if ($this->smsService->sendSms($customer->phone, $message)) {
        return back()->with('success', 'A new code has been sent.');
    }

    return back()->with('error', 'Failed to send SMS. Please try again later.');
}

/**
 * Step 2: Show the OTP Verification Form
 */
public function showVerifyOtpForm()
{
    if (!session()->has('reset_customer_id')) {
        return redirect()->route('customer.password.request');
    }
    return view('auth.verify-otp');
}

/**
 * Step 2: Handle OTP Verification
 */
public function verifyOtp(Request $request)
{
    $request->validate(['otp' => 'required|numeric']);

    if ($request->otp != session('reset_otp') || now()->gt(session('otp_expires_at'))) {
        return back()->withErrors(['otp' => 'Invalid or expired OTP.']);
    }

    // Mark OTP as verified in session to allow access to step 3
    session(['otp_verified' => true]);

    return redirect()->route('customer.password.reset.final');
}

/**
 * Step 3: Show the Final Reset Form
 */
public function showFinalResetForm()
{
    if (!session('otp_verified')) {
        return redirect()->route('customer.password.reset.form');
    }
    return view('auth.reset-password-final');
}

/**
 * Step 3: Process the Password Update
 */
public function resetPassword(Request $request)
{
    $request->validate([
        'identifier' => 'required', // Email or Phone for extra security
        'password' => 'required|string|min:8|confirmed',
    ]);

    $customer = Customer::find(session('reset_customer_id'));

    // Verify the identifier matches the customer we are resetting
    if ($customer->email !== $request->identifier && $customer->phone !== $request->identifier) {
        return back()->withErrors(['identifier' => 'The email/phone does not match our records for this reset.']);
    }

    $customer->pass = Hash::make($request->password);
    $customer->save();

    // Log the user in
    Auth::guard('customer')->login($customer);

    // Clean up
    session()->forget(['reset_otp', 'reset_customer_id', 'otp_expires_at', 'otp_verified']);

    return redirect()->route('customer.dashboard')->with('success', 'Password reset successfully.');
}

}