// controllers/customerController.js
const Customer = require('../models/Customer');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const { generateEmailHTML } = require('../utils/emailTemplates');
require('dotenv').config();

// --- NEW ADDITION: Import the email service ---
// (This assumes you have the utils/emailService.js file from our previous conversations)
const emailService = require('../utils/emailService');
// --- END NEW ADDITION ---


exports.registerCustomer = async (req, res) => {
    try {
        // --- MODIFIED: Added 'email' to be received from the request body ---
        const { name, email, phone, password } = req.body;

        // Check if customer with phone or email already exists
        const existingCustomer = await Customer.findOne({ $or: [{ phone }, { email }] });
        if (existingCustomer) {
            return res.status(400).json({ message: 'A customer with this phone number or email already exists.' });
        }

        const hashedPassword = await bcrypt.hash(password, 10);

        const newCustomer = new Customer({
            name,
            email, // <-- MODIFIED: Added email to save
            phone,
            password: hashedPassword
        });
        await newCustomer.save();

        // --- NEW ADDITION: Send welcome email ---
        try {
            if (email) { // Only send if email is provided
                await emailService.sendEmail({
                    to: email,
                    subject: 'Welcome! Your Registration was Successful',
                    text: `Hello ${name},\n\nWelcome! Your account has been created successfully. You can now log in and start using our services.\n\nThank you,\nYour LaborPK team`,
                    html: `
                        <p>Hello ${name},</p>
                        <p>Welcome! Your account has been created successfully. You can now log in and start using our services.</p>
                        <p>Thank you,<br>Your LaborPK team</p>
                    `
                });
            }
        } catch (emailError) {
            // Log the error but don't prevent the user from being registered
            console.error("Failed to send registration email for customer:", email, emailError);
        }
        // --- END NEW ADDITION ---

        // --- REAL-TIME ADDITION: Notify admin (or relevant parties) of new customer registration ---
        const io = req.app.get('io');
        io.emit('newCustomerRegistered', {
            customerId: newCustomer._id,
            customerName: newCustomer.name,
            phone: newCustomer.phone,
            message: `New customer registered: ${newCustomer.name}`
        });
        console.log(`Emitted 'newCustomerRegistered' for customer ${newCustomer._id}`);
        // --- END REAL-TIME ADDITION ---

        res.status(201).json({ message: 'Customer registration successful.' });
    } catch (error) {
        console.error('Customer registration error:', error);
        res.status(500).json({ message: 'Server error during registration.', error: error.message });
    }
};

exports.login = async (req, res) => {
    const { phone, password } = req.body;

    try {
        const customer = await Customer.findOne({ phone });
        if (!customer) {
            return res.status(400).json({ message: 'Invalid phone or password.' });
        }

        const isMatch = await bcrypt.compare(password, customer.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid phone or password.' });
        }

        // Generate JWT token with 1 day expiration
        const token = jwt.sign(
            { id: customer._id, userType: 'customer' },
            process.env.JWT_SECRET || 'secretkey',
            { expiresIn: '1d' } // Changed from '1h' to '1d' (1 day)
        );

        // --- REAL-TIME ADDITION: Notify the specific customer's socket that they've logged in ---
        const io = req.app.get('io'); // Get the Socket.IO instance
        // This event can signal the frontend to join the customer's specific room
        io.to(`customer_${customer._id}`).emit('customerLoggedIn', {
            customerId: customer._id,
            customerName: customer.name,
            message: 'You have successfully logged in.'
        });
        console.log(`Emitted 'customerLoggedIn' to customer_${customer._id}`);
        // --- END REAL-TIME ADDITION ---

        res.json({
            message: 'Login successful',
            token,
            customerId: customer._id,
            customerName: customer.name
        });

    } catch (error) {
        console.error('Customer login error:', error);
        res.status(500).json({ message: 'Server error during login.', error: error.message });
    }
};


exports.forgotPassword = async (req, res) => {
    try {
        const { email } = req.body;
        const customer = await Customer.findOne({ email });

        if (!customer) {
            // To prevent email enumeration, always send a success-like response
            return res.status(200).json({ message: 'If an account with that email exists, a password reset link has been sent.' });
        }

        const resetToken = crypto.randomBytes(32).toString('hex');
        customer.resetPasswordToken = resetToken;
        customer.resetPasswordExpires = Date.now() + 15 * 60 * 1000; // Token expires in 15 minutes

        await customer.save();

        const resetUrl = `${process.env.FRONTEND_URL}/reset-customer-password/${resetToken}`;

        const emailInfo = {
            title: 'Password Reset Request',
            name: customer.name,
            message: `You requested a password reset for your LaborPK account. Please click the button below to set a new password. This link is only valid for 15 minutes.`,
            buttonUrl: resetUrl,
            buttonText: 'Reset Your Password'
        };
        
        await emailService.sendEmail({
            to: customer.email,
            subject: 'Your laborPK Password Reset Link',
            html: generateEmailHTML(emailInfo)
        });

        res.status(200).json({ message: 'If an account with that email exists, a password reset link has been sent.' });

    } catch (error) {
        console.error('Customer Forgot Password Error:', error);
        res.status(500).json({ message: 'An error occurred. Please try again later.' });
    }
};

exports.resetPassword = async (req, res) => {
    try {
        const { token, password } = req.body;

        const customer = await Customer.findOne({
            resetPasswordToken: token,
            resetPasswordExpires: { $gt: Date.now() }
        });

        if (!customer) {
            return res.status(400).json({ message: 'Password reset token is invalid or has expired.' });
        }

        customer.password = await bcrypt.hash(password, 10);
        customer.resetPasswordToken = undefined;
        customer.resetPasswordExpires = undefined;
        // Optionally: customer.passwordChangedAt = Date.now();

        await customer.save();
        
        res.status(200).json({ message: 'Your password has been successfully updated.' });

    } catch (error) {
        console.error('Customer Reset Password Error:', error);
        res.status(500).json({ message: 'An error occurred. Please try again later.' });
    }
};
