const nodemailer = require('nodemailer');

// SMTP_SECURE=true → SSL port 465 (Hostinger cPanel)
// SMTP_SECURE=false/kosong → STARTTLS port 587 (Gmail, dev)
const isSecure = (process.env.SMTP_SECURE || '').toLowerCase() === 'true';
const smtpPort = parseInt(process.env.SMTP_PORT || (isSecure ? '465' : '587'));

const smtpTransporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST || 'smtp.gmail.com',
  port: smtpPort,
  secure: isSecure,
  auth: {
    user: process.env.SMTP_USER || '',
    pass: process.env.SMTP_PASS || ''
  },
  tls: {
    // Hostinger shared hosting kadang pakai self-signed cert
    rejectUnauthorized: process.env.NODE_ENV === 'production' ? true : false
  }
});

const SMTP_FROM = process.env.SMTP_FROM || process.env.SMTP_USER || 'noreply@nuralilm.id';

async function notifySubscribers(db, type, title, extraInfo = '') {
  try {
    const [subscribers] = await db.query("SELECT email FROM newsletter WHERE status = 'Aktif'");
    if (subscribers.length === 0) return;
    const emails = subscribers.map(s => s.email);
    const typeLabels = { materi: 'Materi Baru', risalah: 'Risalah Jumat', berita: 'Berita & Blog', program: 'Agenda Baru', galeri: 'Galeri Baru' };
    const typeEmojis = { materi: '📖', risalah: '🕌', berita: '📰', program: '📅', galeri: '🖼️' };
    const label = typeLabels[type] || 'Konten Baru';
    const emoji = typeEmojis[type] || '✨';
    await smtpTransporter.sendMail({
      from: `"Nūr Al-'Ilm" <${SMTP_FROM}>`,
      bcc: emails,
      subject: `${label}: ${title}`,
      html: `
        <div style="font-family:Arial,sans-serif;max-width:480px;margin:0 auto;padding:20px">
          <div style="text-align:center;padding:20px;background:linear-gradient(135deg,#0d7c3d,#10a94a);border-radius:12px 12px 0 0">
            <h2 style="color:#fff;margin:0">Nūr Al-'Ilm</h2>
            <p style="color:rgba(255,255,255,.8);margin:4px 0 0">${label}</p>
          </div>
          <div style="background:#fff;padding:30px;border:1px solid #e0e0e0;border-top:none;border-radius:0 0 12px 12px">
            <p>Assalamu'alaikum,</p>
            <p>Ada konten baru dari Nūr Al-'Ilm:</p>
            <div style="background:#f0faf4;border:1px solid #d1fae5;border-radius:12px;padding:20px;margin:16px 0">
              <h3 style="margin:0 0 8px;color:#0d7c3d">${emoji} ${title}</h3>
              ${extraInfo ? `<p style="margin:4px 0;font-size:13px;color:#666">${extraInfo}</p>` : ''}
            </div>
            <hr style="border:none;border-top:1px solid #eee;margin:20px 0">
            <p style="color:#999;font-size:11px;text-align:center">Anda menerima email ini karena berlangganan newsletter Nūr Al-'Ilm.</p>
          </div>
        </div>
      `
    });
    console.log(`📧 Notifikasi ${label} dikirim ke ${emails.length} subscriber`);
  } catch (mailErr) {
    console.error('Gagal kirim notifikasi subscriber:', mailErr.message);
  }
}

module.exports = { smtpTransporter, notifySubscribers, SMTP_FROM };
