// ==========================================
// EMAIL NOTIFICATION SYSTEM
// Add these routes to server.js (before the health check route)
// ==========================================

// Requires: npm install nodemailer (already in package.json)

const nodemailer = require('nodemailer');

// Email transporter setup
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST || 'smtp.gmail.com',
  port: process.env.SMTP_PORT || 587,
  secure: false,
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS
  }
});

// Send notification email
async function sendNotificationEmail(to, subject, htmlBody) {
  try {
    if (!process.env.SMTP_USER) {
      console.log('Email not configured, skipping notification');
      return false;
    }
    await transporter.sendMail({
      from: process.env.NOTIFICATION_FROM || '"JNM Home Education" <noreply@jnmhomeschool.com>',
      to: to,
      subject: subject,
      html: htmlBody
    });
    console.log('Email sent to: ' + to);
    return true;
  } catch (error) {
    console.error('Email error:', error.message);
    return false;
  }
}

// Route: Send overdue assignment notification
app.post('/api/notifications/overdue', authenticateToken, async (req, res) => {
  try {
    const { student_id } = req.body;

    // Get overdue assignments
    const overdue = await pool.query(
      "SELECT a.title, a.due_date, c.name as course_name FROM assignments a JOIN lessons l ON a.lesson_id = l.id JOIN units u ON l.unit_id = u.id JOIN courses c ON u.course_id = c.id JOIN enrollments e ON c.id = e.course_id WHERE e.student_id = $1 AND a.due_date < CURRENT_DATE AND a.id NOT IN (SELECT assignment_id FROM submissions WHERE student_id = $1) AND a.is_active = true",
      [student_id]
    );

    if (overdue.rows.length === 0) {
      return res.json({ message: 'No overdue assignments' });
    }

    // Get parent email
    const parent = await pool.query(
      'SELECT u.email, u.first_name, s.first_name as student_name FROM users u JOIN students s ON s.user_id = u.id WHERE s.id = $1',
      [student_id]
    );

    if (parent.rows.length === 0) return res.status(404).json({ error: 'Parent not found' });

    const parentEmail = parent.rows[0].email;
    const studentName = parent.rows[0].student_name;

    // Build email
    let assignmentList = overdue.rows.map(a =>
      '<tr><td style="padding:8px;border-bottom:1px solid #eee;">' + a.title + '</td><td style="padding:8px;border-bottom:1px solid #eee;">' + a.course_name + '</td><td style="padding:8px;border-bottom:1px solid #eee;color:#f44336;">' + new Date(a.due_date).toLocaleDateString() + '</td></tr>'
    ).join('');

    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;">
        <div style="background:linear-gradient(135deg,#667eea,#764ba2);padding:30px;text-align:center;border-radius:12px 12px 0 0;">
          <h1 style="color:white;margin:0;">🎓 JNM Home Education Program</h1>
        </div>
        <div style="padding:30px;background:white;border:1px solid #eee;">
          <h2 style="color:#333;">Overdue Assignment Alert</h2>
          <p style="color:#666;">Hi ${parent.rows[0].first_name},</p>
          <p style="color:#666;">${studentName} has <strong style="color:#f44336;">${overdue.rows.length} overdue assignment(s)</strong> that need attention:</p>
          <table style="width:100%;border-collapse:collapse;margin:20px 0;">
            <thead><tr style="background:#f8f9fa;"><th style="padding:10px;text-align:left;">Assignment</th><th style="padding:10px;text-align:left;">Course</th><th style="padding:10px;text-align:left;">Due Date</th></tr></thead>
            <tbody>${assignmentList}</tbody>
          </table>
          <p style="color:#666;">Please have ${studentName} complete these assignments as soon as possible.</p>
          <a href="${process.env.FRONTEND_URL || 'http://localhost:3000'}" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#667eea,#764ba2);color:white;text-decoration:none;border-radius:8px;margin-top:10px;">View Dashboard</a>
        </div>
        <div style="padding:20px;text-align:center;color:#999;font-size:12px;">
          JNM Home Education Program — Nevada Home Education
        </div>
      </div>
    `;

    const sent = await sendNotificationEmail(parentEmail, 'Overdue Assignments - ' + studentName, html);

    // Create notification in database
    await pool.query(
      "INSERT INTO notifications (user_id, student_id, notification_type, title, message, priority) VALUES ($1, $2, 'overdue', $3, $4, 'high')",
      [parent.rows[0].id || req.user.id, student_id, 'Overdue Assignments', studentName + ' has ' + overdue.rows.length + ' overdue assignment(s)']
    );

    res.json({ message: 'Notification sent', emailed: sent, overdueCount: overdue.rows.length });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Route: Send failed assignment notification
app.post('/api/notifications/failed', authenticateToken, async (req, res) => {
  try {
    const { student_id, assignment_title, percentage, letter_grade } = req.body;

    const parent = await pool.query(
      'SELECT u.email, u.first_name, s.first_name as student_name FROM users u JOIN students s ON s.user_id = u.id WHERE s.id = $1',
      [student_id]
    );

    if (parent.rows.length === 0) return res.status(404).json({ error: 'Parent not found' });

    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;">
        <div style="background:linear-gradient(135deg,#667eea,#764ba2);padding:30px;text-align:center;border-radius:12px 12px 0 0;">
          <h1 style="color:white;margin:0;">🎓 JNM Home Education Program</h1>
        </div>
        <div style="padding:30px;background:white;border:1px solid #eee;">
          <h2 style="color:#f44336;">Assignment Below Passing Grade</h2>
          <p style="color:#666;">Hi ${parent.rows[0].first_name},</p>
          <p style="color:#666;">${parent.rows[0].student_name} received a grade below passing on:</p>
          <div style="background:#fff3f3;padding:20px;border-radius:8px;border-left:4px solid #f44336;margin:20px 0;">
            <h3 style="margin:0 0 8px 0;color:#333;">${assignment_title}</h3>
            <p style="margin:0;color:#666;">Grade: <strong style="color:#f44336;">${letter_grade} (${percentage}%)</strong></p>
            <p style="margin:8px 0 0 0;color:#666;">Passing grade: 70% (C-)</p>
          </div>
          <p style="color:#666;">A retake is available. ${parent.rows[0].student_name} can review the material and resubmit.</p>
          <a href="${process.env.FRONTEND_URL || 'http://localhost:3000'}" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#667eea,#764ba2);color:white;text-decoration:none;border-radius:8px;margin-top:10px;">View Dashboard</a>
        </div>
      </div>
    `;

    const sent = await sendNotificationEmail(parent.rows[0].email, 'Grade Alert - ' + parent.rows[0].student_name, html);
    res.json({ message: 'Notification sent', emailed: sent });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Route: Send weekly progress summary
app.post('/api/notifications/weekly-summary', authenticateToken, async (req, res) => {
  try {
    const { student_id } = req.body;

    const parent = await pool.query(
      'SELECT u.email, u.first_name, s.first_name as student_name, s.grade_level FROM users u JOIN students s ON s.user_id = u.id WHERE s.id = $1',
      [student_id]
    );

    // Get this week stats
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - 7);

    const weekGrades = await pool.query(
      'SELECT COUNT(*) as count, AVG(percentage) as avg FROM grades WHERE student_id = $1 AND graded_date >= $2',
      [student_id, weekStart.toISOString()]
    );

    const weekHours = await pool.query(
      'SELECT COALESCE(SUM(total_hours), 0) as hours FROM daily_logs WHERE student_id = $1 AND log_date >= $2',
      [student_id, weekStart.toISOString().split('T')[0]]
    );

    const avg = weekGrades.rows[0].avg ? parseFloat(weekGrades.rows[0].avg).toFixed(1) : 'N/A';

    const html = `
      <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;">
        <div style="background:linear-gradient(135deg,#667eea,#764ba2);padding:30px;text-align:center;border-radius:12px 12px 0 0;">
          <h1 style="color:white;margin:0;">🎓 JNM Home Education Program</h1>
        </div>
        <div style="padding:30px;background:white;border:1px solid #eee;">
          <h2 style="color:#333;">Weekly Progress Summary</h2>
          <p style="color:#666;">Hi ${parent.rows[0].first_name}, here is ${parent.rows[0].student_name}'s weekly summary:</p>
          <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin:20px 0;">
            <div style="text-align:center;padding:20px;background:#f0f2ff;border-radius:10px;"><div style="font-size:2rem;font-weight:800;color:#667eea;">${weekGrades.rows[0].count}</div><div style="color:#888;font-size:0.85rem;">Assignments Graded</div></div>
            <div style="text-align:center;padding:20px;background:#f0fff0;border-radius:10px;"><div style="font-size:2rem;font-weight:800;color:#4caf50;">${avg}%</div><div style="color:#888;font-size:0.85rem;">Average Grade</div></div>
            <div style="text-align:center;padding:20px;background:#fff8f0;border-radius:10px;"><div style="font-size:2rem;font-weight:800;color:#ff9800;">${weekHours.rows[0].hours}h</div><div style="color:#888;font-size:0.85rem;">Hours Logged</div></div>
          </div>
          <a href="${process.env.FRONTEND_URL || 'http://localhost:3000'}" style="display:inline-block;padding:12px 24px;background:linear-gradient(135deg,#667eea,#764ba2);color:white;text-decoration:none;border-radius:8px;">View Full Dashboard</a>
        </div>
      </div>
    `;

    const sent = await sendNotificationEmail(parent.rows[0].email, 'Weekly Progress - ' + parent.rows[0].student_name, html);
    res.json({ message: 'Weekly summary sent', emailed: sent });
  } catch (error) { res.status(500).json({ error: error.message }); }
});
