const nodemailer = require('nodemailer');

let db;
let settingsModule;

function init(database, settings) {
    db = database;
    settingsModule = settings;
}

function getSettings(callback) {
    settingsModule.getAll((err, all) => {
        if (err) return callback(err);
        callback(null, all);
    });
}

function createTransport(settings, callback) {
    if (!settings.smtp_host) return callback(new Error('SMTP host not configured'));
    const transport = nodemailer.createTransport({
        host: settings.smtp_host,
        port: parseInt(settings.smtp_port) || 587,
        secure: settings.smtp_secure === 'true',
        auth: {
            user: settings.smtp_user || '',
            pass: settings.smtp_pass || ''
        }
    });
    callback(null, transport);
}

function sendTestEmail(settings, to, callback) {
    createTransport(settings, (err, transport) => {
        if (err) return callback(err);
        transport.sendMail({
            from: settings.smtp_from || settings.smtp_user,
            to: to,
            subject: 'Hotel 777 — Тестовое письмо',
            html: `<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px;">
                <h2 style="color:#c9a84c;">Hotel 777</h2>
                <p>Это тестовое письмо. Настройки SMTP работают корректно.</p>
                <p style="color:#999;font-size:12px;">Отправлено: ${new Date().toLocaleString('ru-RU')}</p>
            </div>`
        }, (err, info) => {
            callback(err, info);
        });
    });
}

function sendBookingConfirmation(booking) {
    if (!booking.phone) return;
    getSettings((err, settings) => {
        if (err || settings.email_notifications_enabled !== 'true') return;
        createTransport(settings, (err, transport) => {
            if (err) { console.error('Email transport error:', err.message); return; }
            transport.sendMail({
                from: settings.smtp_from || settings.smtp_user,
                to: settings.admin_email || settings.smtp_user,
                subject: `Новая бронь: ${booking.name} — ${booking.room_type || 'Номер'} — с ${booking.checkin_date}`,
                html: `
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px;border:1px solid #e2e8f0;border-radius:12px;">
    <h2 style="color:#c9a84c;margin:0 0 16px;">Hotel 777 — Новая бронь</h2>
    <table style="width:100%;border-collapse:collapse;">
        <tr><td style="padding:8px;color:#64748b;">Имя:</td><td style="padding:8px;font-weight:600;">${booking.name}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Телефон:</td><td style="padding:8px;font-weight:600;">${booking.phone}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Номер:</td><td style="padding:8px;font-weight:600;">${booking.room_type || '—'}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Гостей:</td><td style="padding:8px;">${booking.adults} взр.${booking.children ? ', ' + booking.children + ' дет.' : ''}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Заезд:</td><td style="padding:8px;">${booking.checkin_date}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Выезд:</td><td style="padding:8px;">${booking.checkout_date}</td></tr>
        <tr><td style="padding:8px;color:#64748b;">Сумма:</td><td style="padding:8px;font-weight:700;color:#c9a84c;">${booking.total_price || booking.base_price || 0} ₽</td></tr>
        ${booking.wishes ? `<tr><td style="padding:8px;color:#64748b;">Пожелания:</td><td style="padding:8px;">${booking.wishes}</td></tr>` : ''}
    </table>
    <p style="margin-top:20px;color:#999;font-size:12px;">Зайдите в <a href="https://hotel777.ru/admin" style="color:#2563eb;">админ-панель</a> для управления бронью.</p>
</div>`
            }, (err) => {
                if (err) console.error('Booking confirmation email error:', err.message);
            });
        });
    });
}

function sendStatusChange(booking, oldStatus, newStatus) {
    getSettings((err, settings) => {
        if (err || settings.email_notifications_enabled !== 'true') return;
        if (oldStatus === newStatus) return;
        createTransport(settings, (err, transport) => {
            if (err) { console.error('Email transport error:', err.message); return; }
            transport.sendMail({
                from: settings.smtp_from || settings.smtp_user,
                to: settings.admin_email || settings.smtp_user,
                subject: `Статус брони #${booking.id} изменён: ${oldStatus} → ${newStatus}`,
                html: `
<div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px;border:1px solid #e2e8f0;border-radius:12px;">
    <h2 style="color:#c9a84c;">Hotel 777 — Изменение статуса</h2>
    <p>Бронь <strong>#${booking.id}</strong> — ${booking.name}</p>
    <p>Статус изменён: <span style="text-decoration:line-through;color:#ef4444;">${oldStatus}</span> → <span style="color:#16a34a;font-weight:600;">${newStatus}</span></p>
    <p style="color:#999;font-size:12px;">${new Date().toLocaleString('ru-RU')}</p>
</div>`
            }, (err) => {
                if (err) console.error('Status change email error:', err.message);
            });
        });
    });
}

function setupRoutes(app, authenticateToken, requireAdmin) {
}

module.exports = { init, setupRoutes, sendTestEmail, sendBookingConfirmation, sendStatusChange, getSettings };
