const User = require('../models/User');
const Group = require('../models/Group');
const mongoose = require('mongoose');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');

// Register a new user
exports.register = async (req, res) => {
    try {
        const { name, mobile, password, email, dob, gender, emailId, bloodGroup, pincodeNative, state, district, nativePlace, nameMeaning, referralCode } = req.body;
        
        console.log(`📝 [REGISTER DEBUG] Registration attempt for mobile: ${mobile}`);
        console.log(`📝 [REGISTER DEBUG] Name: ${name}`);
        console.log(`📝 [REGISTER DEBUG] Email: ${email}`);
        console.log(`📝 [REGISTER DEBUG] DOB: ${dob}`);
        console.log(`📝 [REGISTER DEBUG] Referral Code: ${referralCode || 'Not provided'}`);
        
        // Validate required fields
        if (!name || !mobile || !password) {
            console.log(`❌ [REGISTER DEBUG] Missing required fields`);
            return res.status(400).json({
                success: false,
                message: 'Name, mobile, and password are required'
            });
        }
        
        // Check if user already exists
        const existingUser = await User.findOne({ mobile });
        if (existingUser) {
            console.log(`❌ [REGISTER DEBUG] User already exists: ${mobile}`);
            return res.status(400).json({
                success: false,
                message: 'User already exists with this mobile number'
            });
        }
        
        // Handle referral code validation (optional)
        let referredByUserId = null;
        if (referralCode) {
            console.log(`🔍 [REGISTER DEBUG] Validating referral code: ${referralCode}`);
            
            // Validate referral code format
            if (!/^[A-Z0-9]{6}$/.test(referralCode)) {
                console.log(`❌ [REGISTER DEBUG] Invalid referral code format: ${referralCode}`);
                return res.status(400).json({
                    success: false,
                    message: 'Invalid referral code format. Must be 6 uppercase letters and numbers.'
                });
            }
            
            // Find user with this referral code
            const referringUser = await User.findOne({ referralCode: referralCode.toUpperCase() });
            if (!referringUser) {
                console.log(`❌ [REGISTER DEBUG] Referral code not found: ${referralCode}`);
                return res.status(400).json({
                    success: false,
                    message: 'Invalid referral code. Please check and try again.'
                });
            }
            
            // Prevent self-referral
            if (referringUser.mobile === mobile) {
                console.log(`❌ [REGISTER DEBUG] Self-referral attempt: ${mobile}`);
                return res.status(400).json({
                    success: false,
                    message: 'You cannot use your own referral code.'
                });
            }
            
            referredByUserId = referringUser._id;
            console.log(`✅ [REGISTER DEBUG] Valid referral code found. Referring user: ${referringUser.name} (${referringUser._id})`);
        }
        
        // Parse and validate date
        const parseDate = (dateString) => {
            if (!dateString) return null;
            
            console.log(`📅 [REGISTER DEBUG] Parsing date: ${dateString}`);
            
            // Try different date formats
            const formats = [
                // DD-MM-YYYY
                /^(\d{1,2})-(\d{1,2})-(\d{4})$/,
                // YYYY-MM-DD
                /^(\d{4})-(\d{1,2})-(\d{1,2})$/,
                // MM/DD/YYYY
                /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
            ];
            
            for (let i = 0; i < formats.length; i++) {
                const match = dateString.match(formats[i]);
                if (match) {
                    let year, month, day;
                    
                    if (i === 0) { // DD-MM-YYYY
                        day = parseInt(match[1]);
                        month = parseInt(match[2]) - 1; // JavaScript months are 0-indexed
                        year = parseInt(match[3]);
                    } else if (i === 1) { // YYYY-MM-DD
                        year = parseInt(match[1]);
                        month = parseInt(match[2]) - 1;
                        day = parseInt(match[3]);
                    } else { // MM/DD/YYYY
                        month = parseInt(match[1]) - 1;
                        day = parseInt(match[2]);
                        year = parseInt(match[3]);
                    }
                    
                    const date = new Date(year, month, day);
                    console.log(`📅 [REGISTER DEBUG] Parsed date: ${date.toISOString()}`);
                    return date;
                }
            }
            
            // Fallback to native Date parsing
            const fallbackDate = new Date(dateString);
            if (!isNaN(fallbackDate.getTime())) {
                console.log(`📅 [REGISTER DEBUG] Fallback parsing successful: ${fallbackDate.toISOString()}`);
                return fallbackDate;
            }
            
            console.log(`❌ [REGISTER DEBUG] Invalid date format: ${dateString}`);
            return null;
        };
        
        const parsedDob = parseDate(dob);
        if (dob && !parsedDob) {
            console.log(`❌ [REGISTER DEBUG] Invalid date format: ${dob}`);
            return res.status(400).json({
                success: false,
                message: 'Invalid date format. Please use DD-MM-YYYY, YYYY-MM-DD, or MM/DD/YYYY format'
            });
        }
        
        // Validate date range
        if (parsedDob) {
            const now = new Date();
            const minDate = new Date(1900, 0, 1);
            const maxDate = new Date(now.getFullYear() - 5, now.getMonth(), now.getDate()); // At least 5 years old
            
            if (parsedDob < minDate) {
                console.log(`❌ [REGISTER DEBUG] Date too old: ${parsedDob.toISOString()}`);
                return res.status(400).json({
                    success: false,
                    message: 'Date of birth cannot be before 1900'
                });
            }
            
            if (parsedDob > maxDate) {
                console.log(`❌ [REGISTER DEBUG] Date too recent: ${parsedDob.toISOString()}`);
                return res.status(400).json({
                    success: false,
                    message: 'You must be at least 5 years old to register'
                });
            }
        }
        
        // Generate OTP
        const otp = Math.floor(100000 + Math.random() * 900000).toString();
        console.log(`🔐 [REGISTER DEBUG] Generated OTP: ${otp}`);
        
        // Generate unique referral code for the new user
        let userReferralCode;
        try {
            userReferralCode = await User.generateUniqueReferralCode();
            console.log(`🎯 [REGISTER DEBUG] Generated referral code: ${userReferralCode}`);
        } catch (error) {
            console.log(`❌ [REGISTER DEBUG] Error generating referral code:`, error.message);
            return res.status(500).json({
                success: false,
                message: 'Error generating referral code. Please try again.'
            });
        }
        
        // Create new user
        const user = new User({
            name,
            mobile,
            password,
            email,
            dob: parsedDob,
            gender,
            emailId,
            bloodGroup,
            pincodeNative,
            state,
            district,
            nativePlace,
            nameMeaning,
            referralCode: userReferralCode,
            referredBy: referredByUserId,
            otp,
            otpExpires: new Date(Date.now() + 10 * 60 * 1000) // 10 minutes
        });
        
        await user.save();
        console.log(`✅ [REGISTER DEBUG] User created successfully: ${user._id}`);
        
        res.status(201).json({
            success: true,
            message: 'User registered successfully. Please verify OTP.',
            data: {
                userId: user._id,
                mobile: user.mobile,
                referralCode: user.referralCode,
                referredBy: referredByUserId,
                otpExpires: user.otpExpires
            }
        });
        
    } catch (error) {
        console.error('❌ [REGISTER ERROR] Registration failed:', error);
        res.status(500).json({
            success: false,
            message: 'Registration failed',
            error: error.message
        });
    }
};

// Verify OTP
exports.verifyOTP = async (req, res) => {
    try {
        const { mobile, otp } = req.body;
        
        const user = await User.findOne({ mobile, otp });
        if (!user) {
            return res.status(400).json({
                success: false,
                message: 'Invalid OTP'
            });
        }
        
        if (user.otpExpires < new Date()) {
            return res.status(400).json({
                success: false,
                message: 'OTP expired'
            });
        }
        
        user.isVerified = true;
        user.otp = undefined;
        user.otpExpires = undefined;
        await user.save();

        // Add coins to referring user if this user was referred
        if (user.referredBy) {
            try {
                const referringUser = await User.findById(user.referredBy);
                if (referringUser) {
                    referringUser.coins += 20; // 20 coins per referral
                    referringUser.totalReferrals += 1;
                    referringUser.successfulReferrals += 1;
                    await referringUser.save();
                    console.log(`🎉 [REFERRAL DEBUG] Added 20 coins to referring user: ${referringUser.name} (${referringUser._id})`);
                }
            } catch (error) {
                console.error('❌ [REFERRAL ERROR] Error adding coins to referring user:', error);
                // Don't fail the verification if coin addition fails
            }
        }
        
        const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET || 'your-secret-key', { expiresIn: '7d' });
        
        res.json({
            success: true,
            message: 'OTP verified successfully',
            data: {
                token,
                user: {
                    _id: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    email: user.email,
                    isVerified: user.isVerified
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [VERIFY OTP ERROR] OTP verification failed:', error);
        res.status(500).json({
            success: false,
            message: 'OTP verification failed',
            error: error.message
        });
    }
};

// Resend OTP
exports.resendOTP = async (req, res) => {
    try {
        const { mobile } = req.body;
        
        const user = await User.findOne({ mobile });
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        const otp = Math.floor(100000 + Math.random() * 900000).toString();
        user.otp = otp;
        user.otpExpires = new Date(Date.now() + 10 * 60 * 1000);
        await user.save();
        
        res.json({
            success: true,
            message: 'OTP resent successfully',
            data: {
                otpExpires: user.otpExpires
            }
        });
        
    } catch (error) {
        console.error('❌ [RESEND OTP ERROR] Resend OTP failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to resend OTP',
            error: error.message
        });
    }
};

// Get user by ID
exports.getUserById = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const user = await User.findById(userId).select('-password -otp');
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            message: 'User retrieved successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    email: user.email,
                    profileImage: user.profileImage,
                    occupation: user.occupation,
                    profession_status: user.profession_status,
                    schoolDetails: user.schoolDetails,
                    collegeDetails: user.collegeDetails,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted,
                    occupationCompleted: user.occupationCompleted,
                    hasOccupation: user.hasOccupation,
                    about: user.about,
                    interests: user.interests,
                    createdAt: user.createdAt,
                    updatedAt: user.updatedAt
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET USER ERROR] Get user failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user',
            error: error.message
        });
    }
};

// Get all users (for testing purposes)
exports.getAllUsers = async (req, res) => {
    try {
        const users = await User.find({}).select('-password -otp');
        
        res.json({
            success: true,
            message: 'Users retrieved successfully',
            data: {
                users,
                count: users.length
            }
        });
        
    } catch (error) {
        console.error('❌ [GET ALL USERS ERROR] Get all users failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get users',
            error: error.message
        });
    }
};

// Get user by mobile number (for testing)
exports.getUserByMobile = async (req, res) => {
    try {
        const { mobile } = req.params;
        
        const user = await User.findOne({ mobile }).select('-password -otp');
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            message: 'User retrieved successfully',
            data: {
                user: {
                    _id: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    email: user.email,
                    profileImage: user.profileImage,
                    occupation: user.occupation,
                    profession_status: user.profession_status,
                    schoolDetails: user.schoolDetails,
                    collegeDetails: user.collegeDetails,
                    hasPersonalDetails: user.hasPersonalDetails,
                    personalDetailsCompleted: user.personalDetailsCompleted,
                    occupationCompleted: user.occupationCompleted,
                    hasOccupation: user.hasOccupation,
                    about: user.about,
                    interests: user.interests,
                    createdAt: user.createdAt,
                    updatedAt: user.updatedAt
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET USER BY MOBILE ERROR] Get user by mobile failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user',
            error: error.message
        });
    }
};

// Get profession status
exports.getProfessionStatus = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const user = await User.findById(userId).select('profession_status name mobile');
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            message: 'Profession status retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                profession_status: user.profession_status
            }
        });
        
    } catch (error) {
        console.error('❌ [GET PROFESSION STATUS ERROR] Get profession status failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get profession status',
            error: error.message
        });
    }
};

// Update profession status
exports.updateProfessionStatus = async (req, res) => {
    try {
        const { userId } = req.params;
        const { profession_status } = req.body;
        
        if (typeof profession_status !== 'boolean') {
            return res.status(400).json({
                success: false,
                message: 'Profession status must be a boolean value'
            });
        }
        
        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        user.profession_status = profession_status;
        await user.save();
        
        res.json({
            success: true,
            message: 'Profession status updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                profession_status: user.profession_status
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE PROFESSION STATUS ERROR] Update profession status failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update profession status',
            error: error.message
        });
    }
};

// Get school details
exports.getSchoolDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const user = await User.findById(userId).select('schoolDetails occupation name mobile');
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            message: 'School details retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                schoolDetails: user.schoolDetails,
                occupation: user.occupation
            }
        });
        
    } catch (error) {
        console.error('❌ [GET SCHOOL DETAILS ERROR] Get school details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get school details',
            error: error.message
        });
    }
};

// Update school details
exports.updateSchoolDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        const { schoolState, schoolDistrict, schoolVillage, schoolCode, schoolName, class10thStatus, academicYear } = req.body;
        
        console.log(`🏫 [UPDATE SCHOOL DEBUG] Updating school details for userId: ${userId}`);
        console.log(`🏫 [UPDATE SCHOOL DEBUG] School details:`, { schoolState, schoolDistrict, schoolVillage, schoolCode, schoolName, class10thStatus, academicYear });
        
        // Validate required fields
        if (!schoolState || !schoolDistrict || !schoolVillage || !schoolCode || !schoolName || !class10thStatus || !academicYear) {
            return res.status(400).json({
                success: false,
                message: 'All school detail fields are required'
            });
        }
        
        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update school details
        user.schoolDetails = {
            schoolState,
            schoolDistrict,
            schoolVillage,
            schoolCode,
            schoolName,
            class10thStatus,
            academicYear
        };
        
        await user.save();
        
        // Generate schoolId for group creation
        const schoolId = `${schoolCode}_${academicYear}`;
        console.log(`🏫 [UPDATE SCHOOL DEBUG] Generated schoolId: ${schoolId}`);
        
        // Try to create or find school group
        let schoolGroupId = null;
        try {
            const schoolGroup = await Group.findOrCreateSchoolGroup(userId, schoolId, {
                schoolState,
                schoolDistrict,
                schoolVillage,
                schoolCode,
                schoolName,
                academicYear
            });
            schoolGroupId = schoolGroup._id;
            console.log(`🏫 [UPDATE SCHOOL DEBUG] School group created/found: ${schoolGroupId}`);
        } catch (groupError) {
            console.log(`⚠️ [UPDATE SCHOOL DEBUG] Group creation failed, but user update succeeded: ${groupError.message}`);
        }
        
        // Update user's schoolGroupId
        if (schoolGroupId) {
            user.schoolGroupId = schoolGroupId;
            await user.save();
        }
        
        res.json({
            success: true,
            message: 'School details updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                schoolDetails: user.schoolDetails,
                schoolGroupId: schoolGroupId,
                occupation: user.occupation
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE SCHOOL DETAILS ERROR] Update school details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update school details',
            error: error.message
        });
    }
};

// Get college details
exports.getCollegeDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        
        const user = await User.findById(userId).select('collegeDetails occupation name mobile');
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        res.json({
            success: true,
            message: 'College details retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                collegeDetails: user.collegeDetails,
                occupation: user.occupation
            }
        });
        
    } catch (error) {
        console.error('❌ [GET COLLEGE DETAILS ERROR] Get college details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get college details',
            error: error.message
        });
    }
};

// Update college details
exports.updateCollegeDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        const { graduationStatus, collegeCode, collegeName, courseName, courseSubBranch, academicYear, selectOnYear } = req.body;
        
        console.log(`🎓 [UPDATE COLLEGE DEBUG] Updating college details for userId: ${userId}`);
        console.log(`🎓 [UPDATE COLLEGE DEBUG] College details:`, { graduationStatus, collegeCode, collegeName, courseName, courseSubBranch, academicYear, selectOnYear });
        
        // Validate required fields
        if (!graduationStatus || !collegeCode || !collegeName || !courseName || !courseSubBranch || !academicYear || !selectOnYear) {
            return res.status(400).json({
                success: false,
                message: 'All college detail fields are required'
            });
        }
        
        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update college details
        user.collegeDetails = {
            graduationStatus,
            collegeCode,
            collegeName,
            courseName,
            courseSubBranch,
            academicYear,
            selectOnYear
        };
        
        await user.save();
        
        // Generate collegeId for group creation
        const collegeId = `${collegeCode}_${academicYear}_${courseName}_${courseSubBranch}`;
        console.log(`🎓 [UPDATE COLLEGE DEBUG] Generated collegeId: ${collegeId}`);
        
        // Try to create or find college group
        let collegeGroupId = null;
        try {
            const collegeGroup = await Group.findOrCreateCollegeGroup(userId, collegeId, {
                graduationStatus,
                collegeCode,
                collegeName,
                courseName,
                courseSubBranch,
                academicYear,
                selectOnYear
            });
            collegeGroupId = collegeGroup._id;
            console.log(`🎓 [UPDATE COLLEGE DEBUG] College group created/found: ${collegeGroupId}`);
        } catch (groupError) {
            console.log(`⚠️ [UPDATE COLLEGE DEBUG] Group creation failed, but user update succeeded: ${groupError.message}`);
        }
        
        // Update user's collegeGroupId
        if (collegeGroupId) {
            user.collegeGroupId = collegeGroupId;
            await user.save();
        }
        
        res.json({
            success: true,
            message: 'College details updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                collegeDetails: user.collegeDetails,
                collegeGroupId: collegeGroupId,
                occupation: user.occupation
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE COLLEGE DETAILS ERROR] Update college details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update college details',
            error: error.message
        });
    }
};

// Get user about by userId
exports.getUserAbout = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`📝 [USER ABOUT DEBUG] Getting about for userId: ${userId}`);
        
        // Find user by ID
        const user = await User.findById(userId).select('about name mobile');
        
        if (!user) {
            console.log(`❌ [USER ABOUT DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`✅ [USER ABOUT DEBUG] User found:`, {
            userId: user._id,
            name: user.name,
            mobile: user.mobile,
            hasAbout: !!user.about,
            aboutLength: user.about?.length || 0
        });
        
        res.json({
            success: true,
            message: 'User about retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                about: user.about || ''
            }
        });
        
    } catch (error) {
        console.error('❌ [USER ABOUT ERROR] Get user about failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user about',
            error: error.message
        });
    }
};

// Update user about by userId
exports.updateUserAbout = async (req, res) => {
    try {
        const { userId } = req.params;
        const { about } = req.body;
        
        console.log(`📝 [UPDATE ABOUT DEBUG] Updating about for userId: ${userId}`);
        console.log(`📝 [UPDATE ABOUT DEBUG] New about: ${about}`);
        console.log(`📝 [UPDATE ABOUT DEBUG] About length: ${about?.length || 0}`);
        
        // Validate about field
        if (about !== undefined && typeof about !== 'string') {
            console.log(`❌ [UPDATE ABOUT DEBUG] Invalid about type: ${typeof about}`);
            return res.status(400).json({
                success: false,
                message: 'About must be a string value'
            });
        }
        
        if (about && about.length > 1000) {
            console.log(`❌ [UPDATE ABOUT DEBUG] About too long: ${about.length} characters`);
            return res.status(400).json({
                success: false,
                message: 'About cannot exceed 1000 characters'
            });
        }
        
        // Find user by ID
        const user = await User.findById(userId);
        
        if (!user) {
            console.log(`❌ [UPDATE ABOUT DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update about
        const oldAbout = user.about;
        user.about = about || '';
        await user.save();
        
        console.log(`✅ [UPDATE ABOUT DEBUG] About updated successfully`);
        console.log(`📝 [UPDATE ABOUT DEBUG] Old about length: ${oldAbout?.length || 0}`);
        console.log(`📝 [UPDATE ABOUT DEBUG] New about length: ${user.about?.length || 0}`);
        
        res.json({
            success: true,
            message: 'User about updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                about: user.about,
                previous_about: oldAbout
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE ABOUT ERROR] Update user about failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update user about',
            error: error.message
        });
    }
};

// Get user interests by userId
exports.getUserInterests = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`🎯 [USER INTERESTS DEBUG] Getting interests for userId: ${userId}`);
        
        // Find user by ID
        const user = await User.findById(userId).select('interests name mobile');
        
        if (!user) {
            console.log(`❌ [USER INTERESTS DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`✅ [USER INTERESTS DEBUG] User found:`, {
            userId: user._id,
            name: user.name,
            mobile: user.mobile,
            interestsCount: user.interests?.length || 0,
            interests: user.interests || []
        });
        
        res.json({
            success: true,
            message: 'User interests retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                interests: user.interests || [],
                interestsCount: user.interests?.length || 0
            }
        });
        
    } catch (error) {
        console.error('❌ [USER INTERESTS ERROR] Get user interests failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user interests',
            error: error.message
        });
    }
};

// Update user interests by userId
exports.updateUserInterests = async (req, res) => {
    try {
        const { userId } = req.params;
        const { interests } = req.body;
        
        console.log(`🎯 [UPDATE INTERESTS DEBUG] Updating interests for userId: ${userId}`);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] New interests:`, interests);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] Interests type: ${typeof interests}`);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] Is array: ${Array.isArray(interests)}`);
        
        // Validate interests field
        if (interests !== undefined && !Array.isArray(interests)) {
            console.log(`❌ [UPDATE INTERESTS DEBUG] Invalid interests type: ${typeof interests}`);
            return res.status(400).json({
                success: false,
                message: 'Interests must be an array of strings'
            });
        }
        
        // Validate each interest
        if (interests) {
            for (let i = 0; i < interests.length; i++) {
                const interest = interests[i];
                if (typeof interest !== 'string') {
                    console.log(`❌ [UPDATE INTERESTS DEBUG] Invalid interest at index ${i}: ${typeof interest}`);
                    return res.status(400).json({
                        success: false,
                        message: `Interest at index ${i} must be a string`
                    });
                }
                if (interest.length > 100) {
                    console.log(`❌ [UPDATE INTERESTS DEBUG] Interest too long at index ${i}: ${interest.length} characters`);
                    return res.status(400).json({
                        success: false,
                        message: `Interest at index ${i} cannot exceed 100 characters`
                    });
                }
            }
        }
        
        // Find user by ID
        const user = await User.findById(userId);
        
        if (!user) {
            console.log(`❌ [UPDATE INTERESTS DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update interests
        const oldInterests = user.interests || [];
        user.interests = interests || [];
        await user.save();
        
        console.log(`✅ [UPDATE INTERESTS DEBUG] Interests updated successfully`);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] Old interests count: ${oldInterests.length}`);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] New interests count: ${user.interests.length}`);
        console.log(`🎯 [UPDATE INTERESTS DEBUG] New interests:`, user.interests);
        
        res.json({
            success: true,
            message: 'User interests updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                interests: user.interests,
                interestsCount: user.interests.length,
                previous_interests: oldInterests,
                previous_interests_count: oldInterests.length
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE INTERESTS ERROR] Update user interests failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update user interests',
            error: error.message
        });
    }
};

// Get user about and interests by userId (combined endpoint)
exports.getUserAboutAndInterests = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`📝🎯 [USER ABOUT & INTERESTS DEBUG] Getting about and interests for userId: ${userId}`);
        
        // Find user by ID
        const user = await User.findById(userId).select('about interests name mobile');
        
        if (!user) {
            console.log(`❌ [USER ABOUT & INTERESTS DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`✅ [USER ABOUT & INTERESTS DEBUG] User found:`, {
            userId: user._id,
            name: user.name,
            mobile: user.mobile,
            hasAbout: !!user.about,
            aboutLength: user.about?.length || 0,
            interestsCount: user.interests?.length || 0,
            interests: user.interests || []
        });
        
        res.json({
            success: true,
            message: 'User about and interests retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                about: user.about || '',
                interests: user.interests || [],
                interestsCount: user.interests?.length || 0
            }
        });
        
    } catch (error) {
        console.error('❌ [USER ABOUT & INTERESTS ERROR] Get user about and interests failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user about and interests',
            error: error.message
        });
    }
};

// Update working professional details by userId
exports.updateWorkingProfessionalDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        const { jobCategory, jobSubcategory, state, district, village } = req.body;
        
        console.log(`💼 [WORKING PROFESSIONAL DEBUG] Updating working professional details for userId: ${userId}`);
        console.log(`💼 [WORKING PROFESSIONAL DEBUG] Data:`, { jobCategory, jobSubcategory, state, district, village });
        
        // Validate required fields
        if (!jobCategory || !jobSubcategory || !state || !district || !village) {
            console.log(`❌ [WORKING PROFESSIONAL DEBUG] Missing required fields`);
            return res.status(400).json({
                success: false,
                message: 'All fields are required: jobCategory, jobSubcategory, state, district, village'
            });
        }
        
        // Find user by ID
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [WORKING PROFESSIONAL DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update working professional details
        user.workingProfessional = {
            jobCategory,
            jobSubcategory,
            state,
            district,
            village
        };
        
        await user.save();
        
        console.log(`✅ [WORKING PROFESSIONAL DEBUG] Working professional details updated successfully`);
        
        res.json({
            success: true,
            message: 'Working professional details updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                occupation: user.occupation,
                workingProfessional: user.workingProfessional
            }
        });
        
    } catch (error) {
        console.error('❌ [WORKING PROFESSIONAL ERROR] Update working professional details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update working professional details',
            error: error.message
        });
    }
};

// Update business details by userId
exports.updateBusinessDetails = async (req, res) => {
    try {
        const { userId } = req.params;
        const { businessName, businessArea, pincode, businessCategory, businessSubCategory, state, village, district } = req.body;
        
        console.log(`🏢 [BUSINESS DEBUG] Updating business details for userId: ${userId}`);
        console.log(`🏢 [BUSINESS DEBUG] Data:`, { businessName, businessArea, pincode, businessCategory, businessSubCategory, state, village, district });
        
        // Validate required fields
        if (!businessName || !businessArea || !pincode || !businessCategory || !businessSubCategory || !state || !village || !district) {
            console.log(`❌ [BUSINESS DEBUG] Missing required fields`);
            return res.status(400).json({
                success: false,
                message: 'All fields are required: businessName, businessArea, pincode, businessCategory, businessSubCategory, state, village, district'
            });
        }
        
        // Find user by ID
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [BUSINESS DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Update business details
        user.business = {
            businessName,
            businessArea,
            pincode,
            businessCategory,
            businessSubCategory,
            state,
            village,
            district
        };
        
        await user.save();
        
        console.log(`✅ [BUSINESS DEBUG] Business details updated successfully`);
        
        res.json({
            success: true,
            message: 'Business details updated successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                occupation: user.occupation,
                business: user.business
            }
        });
        
    } catch (error) {
        console.error('❌ [BUSINESS ERROR] Update business details failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update business details',
            error: error.message
        });
    }
};

// Placeholder functions for missing routes
exports.getUserCompletionStatus = async (req, res) => {
    res.json({ success: true, message: 'Placeholder function' });
};

exports.createOrUpdateOccupation = async (req, res) => {
    try {
        const userId = req.user._id; // Get user ID from authenticated token
        const { occupation } = req.body;
        
        console.log(`💼 [OCCUPATION DEBUG] Creating/updating occupation for userId: ${userId}`);
        console.log(`💼 [OCCUPATION DEBUG] Occupation data:`, { occupation });
        
        // Validate required fields
        if (!occupation) {
            console.log(`❌ [OCCUPATION DEBUG] Missing required field: occupation`);
            return res.status(400).json({
                success: false,
                message: 'Occupation is required'
            });
        }
        
        // Validate occupation enum values
        const validOccupations = ['school student', 'graduate student', 'working professional', 'business', 'public page'];
        if (!validOccupations.includes(occupation)) {
            console.log(`❌ [OCCUPATION DEBUG] Invalid occupation: ${occupation}`);
            return res.status(400).json({
                success: false,
                message: `Invalid occupation. Must be one of: ${validOccupations.join(', ')}`
            });
        }
        
        // Find user by ID
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [OCCUPATION DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Store old values for comparison
        const oldOccupation = user.occupation;
        const oldHasOccupation = user.hasOccupation;
        const oldOccupationCompleted = user.occupationCompleted;
        
        console.log(`💼 [OCCUPATION DEBUG] Before update:`, {
            oldOccupation,
            oldHasOccupation,
            oldOccupationCompleted
        });
        
        // Update occupation (simple string field)
        user.occupation = occupation;
        
        // Set occupation completion flags
        user.hasOccupation = true;
        user.occupationCompleted = true;
        
        console.log(`💼 [OCCUPATION DEBUG] Before save:`, {
            occupation: user.occupation,
            hasOccupation: user.hasOccupation,
            occupationCompleted: user.occupationCompleted
        });
        
        await user.save();
        
        // Verify the update worked
        console.log(`✅ [OCCUPATION DEBUG] Occupation updated successfully`);
        console.log(`💼 [OCCUPATION DEBUG] After save - occupation: ${user.occupation}`);
        console.log(`💼 [OCCUPATION DEBUG] After save - hasOccupation: ${user.hasOccupation}`);
        console.log(`💼 [OCCUPATION DEBUG] After save - occupationCompleted: ${user.occupationCompleted}`);
        console.log(`💼 [OCCUPATION DEBUG] After save - personalDetailsCompleted: ${user.personalDetailsCompleted}`);
        
        // Double-check by fetching from database
        const verifyUser = await User.findById(userId);
        console.log(`🔍 [OCCUPATION DEBUG] Database verification:`, {
            occupation: verifyUser.occupation,
            hasOccupation: verifyUser.hasOccupation,
            occupationCompleted: verifyUser.occupationCompleted
        });
        
        res.json({
            success: true,
            message: 'Occupation updated successfully',
            data: {
                userId: verifyUser._id,
                name: verifyUser.name,
                mobile: verifyUser.mobile,
                occupation: verifyUser.occupation,
                hasOccupation: verifyUser.hasOccupation,
                occupationCompleted: verifyUser.occupationCompleted,
                personalDetailsCompleted: verifyUser.personalDetailsCompleted,
                hasPersonalDetails: verifyUser.hasPersonalDetails
            },
            debug: {
                beforeUpdate: {
                    occupation: oldOccupation,
                    hasOccupation: oldHasOccupation,
                    occupationCompleted: oldOccupationCompleted
                },
                afterUpdate: {
                    occupation: verifyUser.occupation,
                    hasOccupation: verifyUser.hasOccupation,
                    occupationCompleted: verifyUser.occupationCompleted
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [OCCUPATION ERROR] Create/update occupation failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update occupation',
            error: error.message
        });
    }
};

exports.getOccupation = async (req, res) => {
    try {
        const userId = req.user._id; // Get user ID from authenticated token
        
        console.log(`💼 [GET OCCUPATION DEBUG] Getting occupation for userId: ${userId}`);
        
        // Find user by ID
        const user = await User.findById(userId).select('occupation hasOccupation occupationCompleted personalDetailsCompleted hasPersonalDetails name mobile');
        if (!user) {
            console.log(`❌ [GET OCCUPATION DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        console.log(`✅ [GET OCCUPATION DEBUG] User found:`, {
            userId: user._id,
            name: user.name,
            mobile: user.mobile,
            occupation: user.occupation,
            hasOccupation: user.hasOccupation,
            occupationCompleted: user.occupationCompleted,
            personalDetailsCompleted: user.personalDetailsCompleted,
            hasPersonalDetails: user.hasPersonalDetails
        });
        
        res.json({
            success: true,
            message: 'Occupation retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                occupation: user.occupation || null,
                hasOccupation: user.hasOccupation,
                occupationCompleted: user.occupationCompleted,
                personalDetailsCompleted: user.personalDetailsCompleted,
                hasPersonalDetails: user.hasPersonalDetails
            }
        });
        
    } catch (error) {
        console.error('❌ [GET OCCUPATION ERROR] Get occupation failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get occupation',
            error: error.message
        });
    }
};

exports.deleteOccupation = async (req, res) => {
    try {
        const userId = req.user._id; // Get user ID from authenticated token
        
        console.log(`💼 [DELETE OCCUPATION DEBUG] Deleting occupation for userId: ${userId}`);
        
        // Find user by ID
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [DELETE OCCUPATION DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Clear occupation details
        user.occupation = undefined;
        
        // Update occupation completion flags
        user.hasOccupation = false;
        user.occupationCompleted = false;
        
        await user.save();
        
        console.log(`✅ [DELETE OCCUPATION DEBUG] Occupation deleted successfully`);
        console.log(`💼 [DELETE OCCUPATION DEBUG] hasOccupation: ${user.hasOccupation}`);
        console.log(`💼 [DELETE OCCUPATION DEBUG] occupationCompleted: ${user.occupationCompleted}`);
        console.log(`💼 [DELETE OCCUPATION DEBUG] personalDetailsCompleted: ${user.personalDetailsCompleted}`);
        
        res.json({
            success: true,
            message: 'Occupation details deleted successfully',
            data: {
                userId: user._id,
                name: user.name,
                mobile: user.mobile,
                occupation: null,
                hasOccupation: user.hasOccupation,
                occupationCompleted: user.occupationCompleted,
                personalDetailsCompleted: user.personalDetailsCompleted,
                hasPersonalDetails: user.hasPersonalDetails
            }
        });
        
    } catch (error) {
        console.error('❌ [DELETE OCCUPATION ERROR] Delete occupation failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete occupation details',
            error: error.message
        });
    }
};

exports.getUserTabs = async (req, res) => {
    res.json({ success: true, message: 'Placeholder function' });
};

// Helper function to compress and save profile image
const compressAndSaveProfileImage = async (file, maxSizeKB = 100) => {
    try {
        console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Starting compression for: ${file.originalname}`);
        const originalSize = file.size;
        console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Original image size: ${(originalSize / 1024).toFixed(2)} KB`);
        console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Target size: ${maxSizeKB} KB`);
        
        // Get image metadata
        const sharp = require('sharp');
        const metadata = await sharp(file.buffer).metadata();
        console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Original dimensions: ${metadata.width}x${metadata.height}`);
        console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Image format: ${metadata.format}`);
        
        // Generate filename
        const timestamp = Date.now();
        const randomString = Math.random().toString(36).substring(2, 15);
        const filename = `profile_${timestamp}_${randomString}.jpg`;
        
        // Create profiles directory if it doesn't exist
        const profilesDir = path.join(__dirname, '..', 'uploads', 'profiles');
        if (!fs.existsSync(profilesDir)) {
            fs.mkdirSync(profilesDir, { recursive: true });
            console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Created profiles directory: ${profilesDir}`);
        }
        
        const filePath = path.join(profilesDir, filename);
        
        // Compress and save image
        let quality = 85;
        let compressedBuffer = file.buffer;
        
        // Try different quality levels until we get under the target size
        while (quality > 10) {
            compressedBuffer = await sharp(file.buffer)
                .resize(800, 800, { 
                    fit: 'inside',
                    withoutEnlargement: true 
                })
                .jpeg({ 
                    quality: quality,
                    progressive: true,
                    mozjpeg: true
                })
                .toBuffer();
            
            const compressedSize = compressedBuffer.length;
            console.log(`🖼️ [PROFILE IMAGE COMPRESSION DEBUG] Quality ${quality}: ${(compressedSize / 1024).toFixed(2)} KB`);
            
            if (compressedSize <= maxSizeKB * 1024) {
                break;
            }
            
            quality -= 10;
        }
        
        // Save the compressed image
        await fs.promises.writeFile(filePath, compressedBuffer);
        
        const finalSize = compressedBuffer.length;
        const compressionRatio = ((originalSize - finalSize) / originalSize * 100).toFixed(1);
        
        console.log(`✅ [PROFILE IMAGE COMPRESSION DEBUG] Compression completed:`);
        console.log(`✅ [PROFILE IMAGE COMPRESSION DEBUG] Final size: ${(finalSize / 1024).toFixed(2)} KB`);
        console.log(`✅ [PROFILE IMAGE COMPRESSION DEBUG] Compression ratio: ${compressionRatio}%`);
        console.log(`✅ [PROFILE IMAGE COMPRESSION DEBUG] Saved to: ${filePath}`);
        
        return {
            filePath: `uploads/profiles/${filename}`,
            url: `/uploads/profiles/${filename}`,
            originalSize: originalSize,
            compressedSize: finalSize,
            compressionRatio: parseFloat(compressionRatio),
            filename: filename
        };
        
    } catch (error) {
        console.error('❌ [PROFILE IMAGE COMPRESSION ERROR] Compression failed:', error);
        throw error;
    }
};

exports.uploadProfileImage = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`🖼️ [UPLOAD PROFILE IMAGE DEBUG] Upload request for user: ${userId}`);
        console.log(`🖼️ [UPLOAD PROFILE IMAGE DEBUG] Request body:`, req.body);
        console.log(`🖼️ [UPLOAD PROFILE IMAGE DEBUG] Request files:`, req.files);
        console.log(`🖼️ [UPLOAD PROFILE IMAGE DEBUG] Request file:`, req.file);
        
        // Check if file was uploaded
        if (!req.file) {
            console.log(`❌ [UPLOAD PROFILE IMAGE DEBUG] No file uploaded`);
            console.log(`❌ [UPLOAD PROFILE IMAGE DEBUG] Available fields:`, Object.keys(req.body));
            return res.status(400).json({
                success: false,
                message: 'No profile image file uploaded'
            });
        }
        
        // Validate file type (already validated by multer, but double-check)
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
        const allowedExtensions = ['jpg', 'jpeg', 'png', 'webp'];
        
        const ext = req.file.originalname.toLowerCase().split('.').pop();
        const isValidMimeType = allowedTypes.includes(req.file.mimetype);
        const isValidExtension = allowedExtensions.includes(ext);
        
        if (!isValidMimeType && !isValidExtension) {
            console.log(`❌ [UPLOAD PROFILE IMAGE DEBUG] Invalid file type: ${req.file.mimetype}, extension: ${ext}`);
            return res.status(400).json({
                success: false,
                message: `Invalid file type. Only JPEG, PNG, and WebP images are allowed. Received: ${req.file.mimetype} (${ext})`
            });
        }
        
        console.log(`✅ [UPLOAD PROFILE IMAGE DEBUG] File type validation passed: ${req.file.mimetype} (${ext})`);
        
        // Validate file size (max 10MB before compression)
        const maxSizeBeforeCompression = 10 * 1024 * 1024; // 10MB
        if (req.file.size > maxSizeBeforeCompression) {
            console.log(`❌ [UPLOAD PROFILE IMAGE DEBUG] File too large: ${(req.file.size / 1024 / 1024).toFixed(2)} MB`);
            return res.status(400).json({
                success: false,
                message: 'File too large. Maximum size is 10MB'
            });
        }
        
        console.log(`🖼️ [UPLOAD PROFILE IMAGE DEBUG] File details:`, {
            originalname: req.file.originalname,
            mimetype: req.file.mimetype,
            size: `${(req.file.size / 1024).toFixed(2)} KB`
        });
        
        // Find the user
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [UPLOAD PROFILE IMAGE DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Delete old profile image if it exists
        if (user.profileImage) {
            try {
                const oldImagePath = path.join(__dirname, '..', user.profileImage);
                if (fs.existsSync(oldImagePath)) {
                    fs.unlinkSync(oldImagePath);
                    console.log(`🗑️ [UPLOAD PROFILE IMAGE DEBUG] Deleted old profile image: ${user.profileImage}`);
                }
            } catch (deleteError) {
                console.log(`⚠️ [UPLOAD PROFILE IMAGE DEBUG] Could not delete old image:`, deleteError.message);
            }
        }
        
        // Compress and save the new image
        const imageResult = await compressAndSaveProfileImage(req.file, 100); // 100KB target
        
        // Update user's profile image path
        user.profileImage = imageResult.filePath;
        await user.save();
        
        console.log(`✅ [UPLOAD PROFILE IMAGE DEBUG] Profile image uploaded successfully`);
        console.log(`✅ [UPLOAD PROFILE IMAGE DEBUG] New profile image path: ${user.profileImage}`);
        
        res.json({
            success: true,
            message: 'Profile image uploaded successfully',
            data: {
                userId: user._id,
                name: user.name,
                profileImage: user.profileImage,
                profileImageUrl: `/${imageResult.filePath}`,
                imageDetails: {
                    filename: imageResult.filename,
                    originalSize: `${(imageResult.originalSize / 1024).toFixed(2)} KB`,
                    compressedSize: `${(imageResult.compressedSize / 1024).toFixed(2)} KB`,
                    compressionRatio: `${imageResult.compressionRatio}%`
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [UPLOAD PROFILE IMAGE ERROR] Upload failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to upload profile image',
            error: error.message
        });
    }
};

exports.getProfileImage = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`🖼️ [GET PROFILE IMAGE DEBUG] Request for user: ${userId}`);
        
        const user = await User.findById(userId).select('name profileImage');
        if (!user) {
            console.log(`❌ [GET PROFILE IMAGE DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        if (!user.profileImage) {
            console.log(`⚠️ [GET PROFILE IMAGE DEBUG] No profile image for user: ${userId}`);
            return res.json({
                success: true,
                message: 'No profile image found',
                data: {
                    userId: user._id,
                    name: user.name,
                    profileImage: null,
                    profileImageUrl: null
                }
            });
        }
        
        console.log(`✅ [GET PROFILE IMAGE DEBUG] Profile image found: ${user.profileImage}`);
        
        res.json({
            success: true,
            message: 'Profile image retrieved successfully',
            data: {
                userId: user._id,
                name: user.name,
                profileImage: user.profileImage,
                profileImageUrl: `/${user.profileImage}`
            }
        });
        
    } catch (error) {
        console.error('❌ [GET PROFILE IMAGE ERROR] Get profile image failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get profile image',
            error: error.message
        });
    }
};

exports.deleteProfileImage = async (req, res) => {
    try {
        const { userId } = req.params;
        
        console.log(`🗑️ [DELETE PROFILE IMAGE DEBUG] Delete request for user: ${userId}`);
        
        const user = await User.findById(userId);
        if (!user) {
            console.log(`❌ [DELETE PROFILE IMAGE DEBUG] User not found: ${userId}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        if (!user.profileImage) {
            console.log(`⚠️ [DELETE PROFILE IMAGE DEBUG] No profile image to delete for user: ${userId}`);
            return res.json({
                success: true,
                message: 'No profile image to delete',
                data: {
                    userId: user._id,
                    name: user.name,
                    profileImage: null
                }
            });
        }
        
        // Delete the file from filesystem
        try {
            const imagePath = path.join(__dirname, '..', user.profileImage);
            if (fs.existsSync(imagePath)) {
                fs.unlinkSync(imagePath);
                console.log(`🗑️ [DELETE PROFILE IMAGE DEBUG] Deleted file: ${user.profileImage}`);
            }
        } catch (deleteError) {
            console.log(`⚠️ [DELETE PROFILE IMAGE DEBUG] Could not delete file:`, deleteError.message);
        }
        
        // Clear the profile image path from user record
        const oldImagePath = user.profileImage;
        user.profileImage = null;
        await user.save();
        
        console.log(`✅ [DELETE PROFILE IMAGE DEBUG] Profile image deleted successfully`);
        
        res.json({
            success: true,
            message: 'Profile image deleted successfully',
            data: {
                userId: user._id,
                name: user.name,
                profileImage: null,
                deletedImagePath: oldImagePath
            }
        });
        
    } catch (error) {
        console.error('❌ [DELETE PROFILE IMAGE ERROR] Delete profile image failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete profile image',
            error: error.message
        });
    }
};

exports.updateProfileImage = async (req, res) => {
    // This is the same as uploadProfileImage - they can use the upload endpoint
    return exports.uploadProfileImage(req, res);
};

exports.updateUser = async (req, res) => {
    res.json({ success: true, message: 'Placeholder function' });
};

exports.deleteUser = async (req, res) => {
    res.json({ success: true, message: 'Placeholder function' });
};

exports.getUsers = async (req, res) => {
    res.json({ success: true, message: 'Placeholder function' });
};

exports.login = async (req, res) => {
    try {
        const { mobile, password } = req.body;
        
        console.log(`🔐 [LOGIN DEBUG] Login attempt for mobile: ${mobile}`);
        
        // Validate required fields
        if (!mobile || !password) {
            console.log(`❌ [LOGIN DEBUG] Missing required fields`);
            return res.status(400).json({
                success: false,
                message: 'Mobile and password are required'
            });
        }
        
        // Find user by mobile
        const user = await User.findOne({ mobile });
        if (!user) {
            console.log(`❌ [LOGIN DEBUG] User not found: ${mobile}`);
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }
        
        // Check if user is verified
        if (!user.isVerified) {
            console.log(`❌ [LOGIN DEBUG] User not verified: ${mobile}`);
            return res.status(400).json({
                success: false,
                message: 'Please verify your mobile number first'
            });
        }
        
        // Check password (simple comparison for now - in production, use bcrypt)
        if (user.password !== password) {
            console.log(`❌ [LOGIN DEBUG] Invalid password for: ${mobile}`);
            return res.status(401).json({
                success: false,
                message: 'Invalid password'
            });
        }
        
        // Generate JWT token
        const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET || 'your-secret-key', { expiresIn: '7d' });
        
        console.log(`✅ [LOGIN DEBUG] Login successful for: ${mobile}`);
        
        res.json({
            success: true,
            message: 'Login successful',
            data: {
                token,
                user: {
                    _id: user._id,
                    name: user.name,
                    mobile: user.mobile,
                    email: user.email,
                    isVerified: user.isVerified,
                    hasPersonalDetails: user.hasPersonalDetails,
                    hasOccupation: user.hasOccupation,
                    profession_status: user.profession_status,
                    schoolDetails: user.schoolDetails,
                    collegeDetails: user.collegeDetails,
                    about: user.about,
                    interests: user.interests
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [LOGIN ERROR] Login failed:', error);
        res.status(500).json({
            success: false,
            message: 'Login failed',
            error: error.message
        });
    }
};

module.exports = {
    register: exports.register,
    login: exports.login,
    verifyOTP: exports.verifyOTP,
    resendOTP: exports.resendOTP,
    getUserById: exports.getUserById,
    updateUser: exports.updateUser,
    deleteUser: exports.deleteUser,
    getUsers: exports.getUsers,
    getUserByMobile: exports.getUserByMobile,
    getProfileCompletion: exports.getProfileCompletion,
    getAllUsers: exports.getAllUsers,
    getProfessionStatus: exports.getProfessionStatus,
    updateProfessionStatus: exports.updateProfessionStatus,
    getSchoolDetails: exports.getSchoolDetails,
    updateSchoolDetails: exports.updateSchoolDetails,
    getCollegeDetails: exports.getCollegeDetails,
    updateCollegeDetails: exports.updateCollegeDetails,
    getUserAbout: exports.getUserAbout,
    updateUserAbout: exports.updateUserAbout,
    getUserInterests: exports.getUserInterests,
    updateUserInterests: exports.updateUserInterests,
    getUserAboutAndInterests: exports.getUserAboutAndInterests,
    createOrUpdateOccupation: exports.createOrUpdateOccupation,
    getOccupation: exports.getOccupation,
    deleteOccupation: exports.deleteOccupation,
    getUserCompletionStatus: exports.getUserCompletionStatus,
    getUserTabs: exports.getUserTabs,
    uploadProfileImage: exports.uploadProfileImage,
    getProfileImage: exports.getProfileImage,
    deleteProfileImage: exports.deleteProfileImage,
    updateProfileImage: exports.updateProfileImage,
    updateWorkingProfessionalDetails: exports.updateWorkingProfessionalDetails,
    updateBusinessDetails: exports.updateBusinessDetails
};
