// JNM Home Education Program - Complete Backend API Server
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

dotenv.config();

const app = express();
const PORT = process.env.PORT || 5000;

// Database connection
const pool = new Pool({
  user: process.env.DB_USER || 'homeschool_user',
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'jnm_homeschool_db'
});

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/uploads', express.static('uploads'));

// Create uploads directory
if (!fs.existsSync('./uploads')) fs.mkdirSync('./uploads');

// File upload config
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, './uploads'),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const upload = multer({ storage, limits: { fileSize: 10 * 1024 * 1024 } });

// JWT middleware
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Access denied' });
  jwt.verify(token, process.env.JWT_SECRET || 'jnm_secret_key', (err, user) => {
    if (err) return res.status(403).json({ error: 'Invalid token' });
    req.user = user;
    next();
  });
};

// Letter grade calculator
function getLetterGrade(percentage) {
  if (percentage >= 97) return 'A+';
  if (percentage >= 93) return 'A';
  if (percentage >= 90) return 'A-';
  if (percentage >= 87) return 'B+';
  if (percentage >= 83) return 'B';
  if (percentage >= 80) return 'B-';
  if (percentage >= 77) return 'C+';
  if (percentage >= 73) return 'C';
  if (percentage >= 70) return 'C-';
  if (percentage >= 67) return 'D+';
  if (percentage >= 63) return 'D';
  if (percentage >= 60) return 'D-';
  return 'F';
}

// Weighted grade calculator
function calculateWeightedGrade(homeworkAvg, quizAvg, testAvg) {
  const hw = homeworkAvg || 0;
  const qz = quizAvg || 0;
  const ts = testAvg || 0;
  return (hw * 0.40) + (qz * 0.30) + (ts * 0.30);
}

// Test database connection
pool.query('SELECT NOW()', (err, res) => {
  if (err) console.error('Database connection error:', err.message);
  else console.log('Database connected:', res.rows[0].now);
});

// =============================================
// ENSURE LOCAL PARENT ACCOUNT (Option A real auth)
// =============================================
// Guarantees parent@jnm.com / parent123 exists with a valid bcrypt hash
// generated by the running bcrypt version. Runs once on startup.
async function ensureParentAccount() {
  try {
    const email = 'parent@jnm.com';
    const hash = await bcrypt.hash('parent123', 10);
    const existing = await pool.query('SELECT id, password_hash FROM users WHERE email = $1', [email]);
    if (existing.rows.length === 0) {
      await pool.query(
        "INSERT INTO users (email, password_hash, first_name, last_name, role) VALUES ($1, $2, 'JNM', 'Parent', 'parent')",
        [email, hash]
      );
      console.log('Created local parent account: parent@jnm.com / parent123');
    } else if (existing.rows[0].password_hash === 'PENDING_BACKEND_HASH' || !existing.rows[0].password_hash) {
      await pool.query('UPDATE users SET password_hash = $1, role = $2 WHERE email = $3', [hash, 'parent', email]);
      console.log('Set password for local parent account: parent@jnm.com / parent123');
    }
  } catch (e) {
    console.error('ensureParentAccount error:', e.message);
  }
}
ensureParentAccount();

// =============================================
// AUTHENTICATION ROUTES
// =============================================

// Parent/Teacher Login
app.post('/api/auth/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
    if (result.rows.length === 0) return res.status(401).json({ error: 'Invalid credentials' });
    const user = result.rows[0];
    const validPassword = await bcrypt.compare(password, user.password_hash);
    if (!validPassword) return res.status(401).json({ error: 'Invalid credentials' });
    const token = jwt.sign({ id: user.id, role: user.role, email: user.email }, process.env.JWT_SECRET || 'jnm_secret_key', { expiresIn: '24h' });
    res.json({ token, user: { id: user.id, email: user.email, first_name: user.first_name, last_name: user.last_name, role: user.role } });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Student Login
app.post('/api/auth/student-login', async (req, res) => {
  try {
    const { school_id, password } = req.body;
    const result = await pool.query('SELECT * FROM students WHERE school_id = $1', [school_id]);
    if (result.rows.length === 0) return res.status(401).json({ error: 'Invalid School ID' });
    const student = result.rows[0];
    if (student.password_hash) {
      const validPassword = await bcrypt.compare(password, student.password_hash);
      if (!validPassword) return res.status(401).json({ error: 'Invalid password' });
    }
    const token = jwt.sign({ id: student.id, role: 'student', school_id: student.school_id }, process.env.JWT_SECRET || 'jnm_secret_key', { expiresIn: '24h' });
    res.json({ token, student: { id: student.id, school_id: student.school_id, first_name: student.first_name, last_name: student.last_name, grade_level: student.grade_level } });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Register Parent
app.post('/api/auth/register', async (req, res) => {
  try {
    const { email, password, first_name, last_name, phone } = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    const result = await pool.query(
      'INSERT INTO users (email, password_hash, first_name, last_name, phone) VALUES ($1, $2, $3, $4, $5) RETURNING id, email, first_name, last_name, role',
      [email, hashedPassword, first_name, last_name, phone]
    );
    const user = result.rows[0];
    const token = jwt.sign({ id: user.id, role: user.role, email: user.email }, process.env.JWT_SECRET || 'jnm_secret_key', { expiresIn: '24h' });
    res.status(201).json({ token, user });
  } catch (error) {
    if (error.code === '23505') return res.status(400).json({ error: 'Email already exists' });
    res.status(500).json({ error: error.message });
  }
});

// =============================================
// STUDENT MANAGEMENT ROUTES
// =============================================

// Get all students for a parent (active by default)
app.get('/api/students', authenticateToken, async (req, res) => {
  try {
    const { includeInactive } = req.query;
    const query = includeInactive === 'true'
      ? 'SELECT * FROM students WHERE user_id = $1 ORDER BY first_name'
      : "SELECT * FROM students WHERE user_id = $1 AND status = 'active' ORDER BY first_name";
    const result = await pool.query(query, [req.user.id]);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Add a student
app.post('/api/students', authenticateToken, async (req, res) => {
  try {
    const { school_id, first_name, last_name, email, password, date_of_birth, grade_level } = req.body;
    let password_hash = null;
    if (password) password_hash = await bcrypt.hash(password, 10);
    const result = await pool.query(
      'INSERT INTO students (user_id, school_id, first_name, last_name, email, password_hash, date_of_birth, grade_level) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *',
      [req.user.id, school_id, first_name, last_name, email, password_hash, date_of_birth, grade_level]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) {
    if (error.code === '23505') return res.status(400).json({ error: 'School ID already exists' });
    res.status(500).json({ error: error.message });
  }
});

// Update a student
app.put('/api/students/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { first_name, last_name, email, grade_level, school_id } = req.body;
    const result = await pool.query(
      'UPDATE students SET first_name=$1, last_name=$2, email=$3, grade_level=$4, school_id=$5, updated_at=CURRENT_TIMESTAMP WHERE id=$6 AND user_id=$7 RETURNING *',
      [first_name, last_name, email, grade_level, school_id, id, req.user.id]
    );
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Delete a student (soft delete - preserves grades/submissions/enrollments)
app.delete('/api/students/:id', authenticateToken, async (req, res) => {
  try {
    const { hard } = req.query;
    if (hard === 'true') {
      await pool.query('DELETE FROM students WHERE id = $1 AND user_id = $2', [req.params.id, req.user.id]);
      return res.json({ message: 'Student permanently deleted' });
    }
    await pool.query(
      "UPDATE students SET status = 'inactive', updated_at = CURRENT_TIMESTAMP WHERE id = $1 AND user_id = $2",
      [req.params.id, req.user.id]
    );
    res.json({ message: 'Student deactivated' });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get student dashboard
app.get('/api/students/:id/dashboard', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const student = await pool.query('SELECT * FROM students WHERE id = $1', [id]);
    const courses = await pool.query(
      'SELECT c.*, e.enrolled_date, e.status as enrollment_status FROM courses c JOIN enrollments e ON c.id = e.course_id WHERE e.student_id = $1 AND e.status = $2',
      [id, 'active']
    );
    const recentGrades = await pool.query(
      'SELECT g.*, a.title as assignment_title, c.name as course_name, c.subject FROM grades g JOIN assignments a ON g.assignment_id = a.id 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 WHERE g.student_id = $1 ORDER BY g.graded_date DESC LIMIT 20',
      [id]
    );
    const pendingAssignments = await pool.query(
      'SELECT a.*, c.name as course_name, c.subject 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.id NOT IN (SELECT assignment_id FROM grades WHERE student_id = $1) AND a.is_active = true ORDER BY a.due_date',
      [id]
    );
    const notifications = await pool.query(
      'SELECT * FROM notifications WHERE student_id = $1 AND is_read = false ORDER BY created_at DESC LIMIT 10',
      [id]
    );
    res.json({
      student: student.rows[0],
      courses: courses.rows,
      recentGrades: recentGrades.rows,
      pendingAssignments: pendingAssignments.rows,
      notifications: notifications.rows
    });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// COURSE ROUTES
// =============================================

// Get courses by grade level
app.get('/api/courses/grade/:gradeLevel', async (req, res) => {
  try {
    const result = await pool.query(
      'SELECT * FROM courses WHERE grade_level = $1 AND is_active = true ORDER BY course_type, subject',
      [req.params.gradeLevel]
    );
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get assignments by grade level (no auth required - bridges demo to live data)
app.get('/api/assignments/grade/:gradeLevel', async (req, res) => {
  try {
    const { gradeLevel } = req.params;
    const { studentId } = req.query;

    const result = await pool.query(
      `SELECT a.id, a.title, a.description, a.due_date, a.assignment_type,
              a.point_value, a.weight_category, a.passing_grade,
              c.name as course_name, c.subject,
              l.title as lesson_title, l.video_url, l.video_verified, l.video_title,
              u.unit_number, l.lesson_number
       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
       WHERE c.grade_level = $1 AND a.is_active = true
       ORDER BY c.subject, u.unit_number, l.lesson_number`,
      [gradeLevel]
    );

    let grades = [];
    let submissions = [];

    if (studentId) {
      try {
        const gradesResult = await pool.query(
          'SELECT * FROM grades WHERE student_id = $1', [studentId]
        );
        grades = gradesResult.rows;
      } catch (e) { /* no grades yet */ }

      try {
        const submissionsResult = await pool.query(
          "SELECT * FROM submissions WHERE student_id = $1 AND status = 'submitted'", [studentId]
        );
        submissions = submissionsResult.rows;
      } catch (e) { /* no submissions yet */ }
    }

    const assignments = result.rows.map(a => {
      const grade = grades.find(g => g.assignment_id === a.id);
      const submission = submissions.find(s => s.assignment_id === a.id);

      let status = 'pending';
      if (grade) status = 'graded';
      else if (submission) status = 'submitted';

      return {
        ...a,
        status,
        percentage: grade ? parseFloat(grade.percentage) : null,
        letter_grade: grade ? grade.letter_grade : null,
        points_earned: grade ? parseInt(grade.points_earned) : null,
        feedback: grade ? grade.feedback : null
      };
    });

    res.json(assignments);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get single lesson with full content (no auth - bridges demo to live data)
app.get('/api/lessons/:id', async (req, res) => {
  try {
    const result = await pool.query(
      `SELECT l.*, u.title as unit_title, u.unit_number,
              c.name as course_name, c.subject, c.grade_level, c.id as course_id
       FROM lessons l
       JOIN units u ON l.unit_id = u.id
       JOIN courses c ON u.course_id = c.id
       WHERE l.id = $1`, [req.params.id]
    );
    if (result.rows.length === 0) return res.status(404).json({ error: 'Lesson not found' });
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get all lessons for a course with content (no auth)
app.get('/api/courses/:courseId/lessons', async (req, res) => {
  try {
    const result = await pool.query(
      `SELECT l.id, l.title, l.lesson_number, l.learning_objectives, l.video_url, l.video_source,
              u.title as unit_title, u.unit_number, u.id as unit_id
       FROM lessons l
       JOIN units u ON l.unit_id = u.id
       WHERE u.course_id = $1
       ORDER BY u.unit_number, l.lesson_number`, [req.params.courseId]
    );
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get assignment detail with questions (no auth - bridges demo to live data)
app.get('/api/assignments/:id/detail', async (req, res) => {
  try {
    const { id } = req.params;
    const result = await pool.query(
      `SELECT a.id, a.title, a.description, a.instructions, a.questions,
              a.due_date, a.assignment_type, a.point_value, a.weight_category, a.passing_grade,
              c.name as course_name, c.subject, c.grade_level,
              l.id as lesson_id, l.title as lesson_title, l.description as lesson_description,
              l.video_url, l.video_source, l.video_verified, l.video_title,
              l.learning_objectives, l.instructional_content, l.vocabulary, l.examples, l.guided_practice,
              l.passage_title, l.passage_type, l.reading_passage, l.passage_source,
              l.reading_level, l.grade_band, l.audio_url, l.audio_title, l.read_aloud_available,
              l.concept_title, l.concept_explanation, l.formula_text,
              l.step_by_step_examples, l.common_mistakes,
              l.materials_needed, l.safety_notes, l.experiment_steps,
              l.observation_questions, l.conclusion_prompt,
              l.source_title, l.source_type, l.source_text,
              l.historical_context, l.timeline_points, l.map_activity_prompt,
              l.real_world_application, l.word_list,
              u.title as unit_title, u.unit_number
       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
       WHERE a.id = $1`,
      [id]
    );
    if (result.rows.length === 0) return res.status(404).json({ error: 'Assignment not found' });
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Submit assignment answers and auto-grade (no auth - bridges demo to live data)
app.post('/api/assignments/:id/submit', async (req, res) => {
  try {
    const { id } = req.params;
    const { student_id, answers, written_response } = req.body;

    // Fetch assignment with questions
    const assignResult = await pool.query('SELECT * FROM assignments WHERE id = $1', [id]);
    if (assignResult.rows.length === 0) return res.status(404).json({ error: 'Assignment not found' });

    const assignment = assignResult.rows[0];
    const questions = assignment.questions || [];

    // Auto-grade auto-gradeable questions
    let autoGradeableCount = 0;
    let correctCount = 0;
    const questionResults = questions.map((q, idx) => {
      const studentAnswer = answers ? answers[idx] : null;

      if (q.type === 'multiple_choice' || q.type === 'true_false') {
        autoGradeableCount++;
        const isCorrect = studentAnswer && studentAnswer.toString().trim().toLowerCase() === q.correct_answer.toString().trim().toLowerCase();
        if (isCorrect) correctCount++;
        return { question_id: q.id, type: q.type, student_answer: studentAnswer, correct_answer: q.correct_answer, is_correct: isCorrect };
      } else if (q.type === 'short_answer' && q.correct_answer) {
        autoGradeableCount++;
        const isCorrect = studentAnswer && studentAnswer.toString().trim().toLowerCase() === q.correct_answer.toString().trim().toLowerCase();
        if (isCorrect) correctCount++;
        return { question_id: q.id, type: q.type, student_answer: studentAnswer, correct_answer: q.correct_answer, is_correct: isCorrect };
      } else {
        return { question_id: q.id, type: q.type, student_answer: studentAnswer || written_response, is_correct: null, needs_review: true };
      }
    });

    // Calculate score
    const hasManualGrading = questionResults.some(r => r.is_correct === null);
    let percentage, pointsEarned, letterGrade, status;

    if (autoGradeableCount > 0) {
      percentage = parseFloat(((correctCount / autoGradeableCount) * 100).toFixed(2));
      pointsEarned = Math.round((correctCount / autoGradeableCount) * assignment.point_value);
      letterGrade = getLetterGrade(percentage);
      status = hasManualGrading ? 'partially_graded' : 'graded';
    } else {
      percentage = null;
      pointsEarned = null;
      letterGrade = null;
      status = 'submitted';
    }

    // Save submission (upsert on the unique (assignment_id, student_id) constraint)
    const submissionResult = await pool.query(
      `INSERT INTO submissions (assignment_id, student_id, submission_text, status, hours_spent)
       VALUES ($1, $2, $3, $4, 0)
       ON CONFLICT (assignment_id, student_id) DO UPDATE SET
         submission_text = EXCLUDED.submission_text,
         status = EXCLUDED.status,
         submission_date = CURRENT_TIMESTAMP
       RETURNING id`,
      [id, student_id, JSON.stringify({ answers, written_response, results: questionResults }), status]
    );
    const submissionId = submissionResult.rows[0].id;

    // Save grade if auto-gradeable (upsert on unique (assignment_id, student_id))
    if (autoGradeableCount > 0 && percentage !== null) {
      await pool.query(
        `INSERT INTO grades (submission_id, assignment_id, student_id, points_earned, point_value, percentage, letter_grade, weight_category, feedback, graded_by)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL)
         ON CONFLICT (assignment_id, student_id) DO UPDATE SET
           submission_id = EXCLUDED.submission_id,
           points_earned = EXCLUDED.points_earned,
           percentage = EXCLUDED.percentage,
           letter_grade = EXCLUDED.letter_grade,
           feedback = EXCLUDED.feedback,
           graded_date = CURRENT_TIMESTAMP`,
        [submissionId, id, student_id, pointsEarned, assignment.point_value, percentage, letterGrade, assignment.weight_category,
         hasManualGrading ? 'Auto-graded (some questions pending review)' : 'Auto-graded']
      );
    }

    res.json({
      status,
      score: { correct: correctCount, total: autoGradeableCount, percentage, points_earned: pointsEarned, point_value: assignment.point_value, letter_grade: letterGrade },
      results: questionResults,
      has_manual_grading: hasManualGrading,
      message: status === 'graded' ? `Score: ${percentage}% (${letterGrade})` :
               status === 'partially_graded' ? `Auto-graded score: ${percentage}% - some answers need review` :
               'Submitted for review'
    });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get full course with units, lessons, assignments
app.get('/api/courses/:courseId/full', authenticateToken, async (req, res) => {
  try {
    const { courseId } = req.params;
    const course = await pool.query('SELECT * FROM courses WHERE id = $1', [courseId]);
    const units = await pool.query('SELECT * FROM units WHERE course_id = $1 ORDER BY unit_number', [courseId]);
    const lessons = await pool.query(
      'SELECT l.* FROM lessons l JOIN units u ON l.unit_id = u.id WHERE u.course_id = $1 ORDER BY u.unit_number, l.lesson_number',
      [courseId]
    );
    const assignments = await pool.query(
      'SELECT a.*, l.lesson_number, u.unit_number FROM assignments a JOIN lessons l ON a.lesson_id = l.id JOIN units u ON l.unit_id = u.id WHERE u.course_id = $1 ORDER BY u.unit_number, l.lesson_number',
      [courseId]
    );
    res.json({ course: course.rows[0], units: units.rows, lessons: lessons.rows, assignments: assignments.rows });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Enroll student in course
app.post('/api/enrollments', authenticateToken, async (req, res) => {
  try {
    const { student_id, course_id } = req.body;
    const result = await pool.query(
      'INSERT INTO enrollments (student_id, course_id) VALUES ($1, $2) ON CONFLICT (student_id, course_id) DO UPDATE SET status = $3 RETURNING *',
      [student_id, course_id, 'active']
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// COURSE/UNIT/LESSON NAVIGATION ROUTES
// =============================================

// Get all courses (optionally filtered by grade via query)
app.get('/api/courses', authenticateToken, async (req, res) => {
  try {
    const { grade } = req.query;
    let result;
    if (grade) {
      result = await pool.query(
        'SELECT * FROM courses WHERE grade_level = $1 AND is_active = true ORDER BY course_type, subject',
        [grade]
      );
    } else {
      result = await pool.query('SELECT * FROM courses WHERE is_active = true ORDER BY grade_level, course_type, subject');
    }
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get units for a course, each with assignment counts
app.get('/api/courses/:courseId/units', authenticateToken, async (req, res) => {
  try {
    const { courseId } = req.params;
    const { studentId } = req.query;
    const units = await pool.query(
      'SELECT * FROM units WHERE course_id = $1 AND is_active = true ORDER BY unit_number',
      [courseId]
    );
    // Attach assignment counts per unit (and graded count if studentId provided)
    for (const unit of units.rows) {
      const counts = await pool.query(
        `SELECT COUNT(*)::int AS total
         FROM assignments a JOIN lessons l ON a.lesson_id = l.id
         WHERE l.unit_id = $1 AND a.is_active = true`,
        [unit.id]
      );
      unit.assignment_count = counts.rows[0].total;
      if (studentId) {
        const graded = await pool.query(
          `SELECT COUNT(*)::int AS graded
           FROM grades g JOIN assignments a ON g.assignment_id = a.id JOIN lessons l ON a.lesson_id = l.id
           WHERE l.unit_id = $1 AND g.student_id = $2`,
          [unit.id, studentId]
        );
        unit.graded_count = graded.rows[0].graded;
      }
    }
    res.json(units.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get lessons for a unit, each with its assignments (and student status)
app.get('/api/units/:unitId/lessons', authenticateToken, async (req, res) => {
  try {
    const { unitId } = req.params;
    const { studentId } = req.query;
    const lessons = await pool.query(
      'SELECT id, title, lesson_number, video_url, video_title, video_verified FROM lessons WHERE unit_id = $1 AND is_active = true ORDER BY lesson_number',
      [unitId]
    );
    let grades = [], submissions = [];
    if (studentId) {
      const g = await pool.query('SELECT assignment_id, percentage, letter_grade FROM grades WHERE student_id = $1', [studentId]);
      grades = g.rows;
      const s = await pool.query("SELECT assignment_id, status FROM submissions WHERE student_id = $1", [studentId]);
      submissions = s.rows;
    }
    for (const lesson of lessons.rows) {
      const a = await pool.query(
        'SELECT id, title, assignment_type, weight_category, point_value, due_date FROM assignments WHERE lesson_id = $1 AND is_active = true ORDER BY id',
        [lesson.id]
      );
      lesson.assignments = a.rows.map(assignment => {
        const grade = grades.find(x => x.assignment_id === assignment.id);
        const sub = submissions.find(x => x.assignment_id === assignment.id);
        let status = 'pending';
        if (grade) status = 'graded';
        else if (sub) status = sub.status;
        return {
          ...assignment,
          status,
          percentage: grade ? parseFloat(grade.percentage) : null,
          letter_grade: grade ? grade.letter_grade : null
        };
      });
    }
    res.json(lessons.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get assignments for a lesson
app.get('/api/lessons/:lessonId/assignments', authenticateToken, async (req, res) => {
  try {
    const { lessonId } = req.params;
    const { studentId } = req.query;
    const result = await pool.query(
      'SELECT a.*, l.title as lesson_title, l.video_url, l.video_verified, l.video_title FROM assignments a JOIN lessons l ON a.lesson_id = l.id WHERE a.lesson_id = $1 AND a.is_active = true ORDER BY a.id',
      [lessonId]
    );
    let grades = [], submissions = [];
    if (studentId) {
      const g = await pool.query('SELECT assignment_id, percentage, letter_grade FROM grades WHERE student_id = $1', [studentId]);
      grades = g.rows;
      const s = await pool.query("SELECT assignment_id, status FROM submissions WHERE student_id = $1", [studentId]);
      submissions = s.rows;
    }
    const assignments = result.rows.map(a => {
      const grade = grades.find(x => x.assignment_id === a.id);
      const sub = submissions.find(x => x.assignment_id === a.id);
      let status = 'pending';
      if (grade) status = 'graded';
      else if (sub) status = sub.status;
      return { ...a, status, percentage: grade ? parseFloat(grade.percentage) : null, letter_grade: grade ? grade.letter_grade : null };
    });
    res.json(assignments);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get assignments grouped for a whole course (course -> unit -> lesson -> assignment)
app.get('/api/courses/:courseId/assignments', authenticateToken, async (req, res) => {
  try {
    const { courseId } = req.params;
    const { studentId } = req.query;
    const result = await pool.query(
      `SELECT a.id as assignment_id, a.title as assignment_title, a.assignment_type, a.weight_category,
              a.point_value, a.due_date,
              c.id as course_id, c.name as course_name, c.subject,
              u.id as unit_id, u.unit_number, u.title as unit_title,
              l.id as lesson_id, l.lesson_number, l.title as lesson_title,
              l.video_url, l.video_verified, l.video_title
       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
       WHERE c.id = $1 AND a.is_active = true
       ORDER BY u.unit_number, l.lesson_number, a.id`,
      [courseId]
    );
    let grades = [];
    if (studentId) {
      const g = await pool.query('SELECT assignment_id, percentage, letter_grade FROM grades WHERE student_id = $1', [studentId]);
      grades = g.rows;
    }
    const rows = result.rows.map(r => {
      const grade = grades.find(x => x.assignment_id === r.assignment_id);
      return { ...r, status: grade ? 'graded' : 'pending', percentage: grade ? parseFloat(grade.percentage) : null, letter_grade: grade ? grade.letter_grade : null };
    });
    res.json(rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get a student's enrolled (active) courses
app.get('/api/students/:studentId/courses', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query(
      `SELECT c.*, e.status as enrollment_status, e.enrolled_date
       FROM courses c JOIN enrollments e ON c.id = e.course_id
       WHERE e.student_id = $1 AND e.status = 'active'
       ORDER BY c.course_type, c.subject`,
      [req.params.studentId]
    );
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Assign a course to a student
app.post('/api/students/:studentId/courses/:courseId', authenticateToken, async (req, res) => {
  try {
    const { studentId, courseId } = req.params;
    const result = await pool.query(
      "INSERT INTO enrollments (student_id, course_id, status) VALUES ($1, $2, 'active') ON CONFLICT (student_id, course_id) DO UPDATE SET status = 'active' RETURNING *",
      [studentId, courseId]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Remove a course from a student (soft: set enrollment inactive)
app.delete('/api/students/:studentId/courses/:courseId', authenticateToken, async (req, res) => {
  try {
    const { studentId, courseId } = req.params;
    await pool.query(
      "UPDATE enrollments SET status = 'dropped' WHERE student_id = $1 AND course_id = $2",
      [studentId, courseId]
    );
    res.json({ message: 'Course removed from student' });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Add custom course
app.post('/api/courses', authenticateToken, async (req, res) => {
  try {
    const { name, grade_level, subject, course_type, description, credit_hours } = req.body;
    const result = await pool.query(
      'INSERT INTO courses (name, grade_level, subject, course_type, description, credit_hours, created_by) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *',
      [name, grade_level, subject, course_type || 'elective', description, credit_hours || 1.0, req.user.id]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Edit course
app.put('/api/courses/:id', authenticateToken, async (req, res) => {
  try {
    const { name, description, credit_hours } = req.body;
    const result = await pool.query(
      'UPDATE courses SET name=$1, description=$2, credit_hours=$3, updated_at=CURRENT_TIMESTAMP WHERE id=$4 RETURNING *',
      [name, description, credit_hours, req.params.id]
    );
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// ASSIGNMENT ROUTES
// =============================================

// Get assignments for student
app.get('/api/assignments/student/:studentId', authenticateToken, async (req, res) => {
  try {
    const { studentId } = req.params;
    const { courseId, status } = req.query;
    let query = 'SELECT a.*, c.name as course_name, c.subject, l.title as lesson_title, l.video_url, u.unit_number, l.lesson_number 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.is_active = true';
    const params = [studentId];
    if (courseId) { query += ' AND c.id = $' + (params.length + 1); params.push(courseId); }
    query += ' ORDER BY a.due_date, u.unit_number, l.lesson_number';
    const result = await pool.query(query, params);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Create assignment
app.post('/api/assignments', authenticateToken, async (req, res) => {
  try {
    const { lesson_id, title, description, instructions, due_date, assignment_type, point_value, weight_category, passing_grade } = req.body;
    const result = await pool.query(
      'INSERT INTO assignments (lesson_id, title, description, instructions, due_date, assignment_type, point_value, weight_category, passing_grade, created_by) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING *',
      [lesson_id, title, description, instructions, due_date, assignment_type || 'homework', point_value || 100, weight_category || 'homework', passing_grade || 70, req.user.id]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Edit assignment
app.put('/api/assignments/:id', authenticateToken, async (req, res) => {
  try {
    const { title, description, instructions, due_date, point_value, weight_category } = req.body;
    const result = await pool.query(
      'UPDATE assignments SET title=$1, description=$2, instructions=$3, due_date=$4, point_value=$5, weight_category=$6, updated_at=CURRENT_TIMESTAMP WHERE id=$7 RETURNING *',
      [title, description, instructions, due_date, point_value, weight_category, req.params.id]
    );
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// SUBMISSION ROUTES
// =============================================

// Submit assignment
app.post('/api/submissions', authenticateToken, upload.single('file'), async (req, res) => {
  try {
    const { assignment_id, student_id, submission_text, hours_spent, is_retake, retake_number } = req.body;
    const file_url = req.file ? '/uploads/' + req.file.filename : null;
    const file_name = req.file ? req.file.originalname : null;
    const result = await pool.query(
      'INSERT INTO submissions (assignment_id, student_id, submission_text, submission_file_url, submission_file_name, hours_spent, is_retake, retake_number, status) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING *',
      [assignment_id, student_id, submission_text, file_url, file_name, hours_spent || 0, is_retake || false, retake_number || 0, 'submitted']
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get pending submissions
app.get('/api/submissions/pending', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query(
      "SELECT s.*, a.title as assignment_title, a.point_value, st.first_name, st.last_name, st.school_id, c.name as course_name, c.subject FROM submissions s JOIN assignments a ON s.assignment_id = a.id JOIN students st ON s.student_id = st.id 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 WHERE s.status = 'submitted' AND st.user_id = $1 ORDER BY s.submission_date DESC",
      [req.user.id]
    );
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get ALL submitted/graded work for the parent's students (Grade Work page)
app.get('/api/gradework', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query(
      `SELECT s.id as submission_id, s.assignment_id, s.student_id, s.submission_date, s.status, s.submission_text,
              a.title as assignment_title, a.point_value, a.weight_category,
              st.first_name, st.last_name, st.school_id,
              c.name as course_name, c.subject,
              g.percentage, g.letter_grade, g.points_earned, g.feedback, g.graded_date
       FROM submissions s
       JOIN assignments a ON s.assignment_id = a.id
       JOIN students st ON s.student_id = st.id
       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
       LEFT JOIN grades g ON g.assignment_id = s.assignment_id AND g.student_id = s.student_id
       WHERE st.user_id = $1
       ORDER BY s.submission_date DESC`,
      [req.user.id]
    );
    // Derive a display status and whether manual review is needed
    const rows = result.rows.map(r => {
      let displayStatus = r.status;
      let needsReview = false;
      if (r.percentage !== null && r.status !== 'partially_graded') displayStatus = 'graded';
      if (r.status === 'submitted' && r.percentage === null) { displayStatus = 'needs_review'; needsReview = true; }
      if (r.status === 'partially_graded') { displayStatus = 'partially_graded'; needsReview = true; }
      return { ...r, display_status: displayStatus, needs_review: needsReview };
    });
    res.json(rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get the full submission detail (answers + results) for review
app.get('/api/submissions/:id/detail', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query(
      `SELECT s.*, a.title as assignment_title, a.questions, a.point_value,
              st.first_name, st.last_name, c.name as course_name
       FROM submissions s
       JOIN assignments a ON s.assignment_id = a.id
       JOIN students st ON s.student_id = st.id
       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
       WHERE s.id = $1 AND st.user_id = $2`,
      [req.params.id, req.user.id]
    );
    if (result.rows.length === 0) return res.status(404).json({ error: 'Submission not found' });
    const row = result.rows[0];
    let parsed = null;
    try { parsed = typeof row.submission_text === 'string' ? JSON.parse(row.submission_text) : row.submission_text; } catch { parsed = null; }
    res.json({ ...row, parsed_submission: parsed });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// GRADING ROUTES
// =============================================

// Grade a submission
app.post('/api/grades', authenticateToken, async (req, res) => {
  try {
    const { submission_id, assignment_id, student_id, points_earned, feedback } = req.body;
    const assignment = await pool.query('SELECT point_value, weight_category, passing_grade FROM assignments WHERE id = $1', [assignment_id]);
    const pointValue = assignment.rows[0].point_value;
    const percentage = (points_earned / pointValue) * 100;
    const letterGrade = getLetterGrade(percentage);
    const weightCategory = assignment.rows[0].weight_category;
    const result = await pool.query(
      `INSERT INTO grades (submission_id, assignment_id, student_id, points_earned, point_value, percentage, letter_grade, weight_category, feedback, graded_by)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
       ON CONFLICT (assignment_id, student_id) DO UPDATE SET
         submission_id = EXCLUDED.submission_id,
         points_earned = EXCLUDED.points_earned,
         percentage = EXCLUDED.percentage,
         letter_grade = EXCLUDED.letter_grade,
         feedback = EXCLUDED.feedback,
         graded_by = EXCLUDED.graded_by,
         graded_date = CURRENT_TIMESTAMP
       RETURNING *`,
      [submission_id, assignment_id, student_id, points_earned, pointValue, percentage.toFixed(2), letterGrade, weightCategory, feedback, req.user.id]
    );
    if (submission_id) await pool.query("UPDATE submissions SET status = 'graded' WHERE id = $1", [submission_id]);
    if (percentage < assignment.rows[0].passing_grade) {
      await pool.query(
        "INSERT INTO notifications (user_id, student_id, notification_type, title, message, priority) VALUES ($1, $2, 'failed_assignment', $3, $4, 'high')",
        [req.user.id, student_id, 'Assignment Failed - Retake Available', 'Grade: ' + letterGrade + ' (' + percentage.toFixed(1) + '%). Retake is available.']
      );
    }
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// Get grades for student
app.get('/api/grades/student/:studentId', authenticateToken, async (req, res) => {
  try {
    const { studentId } = req.params;
    const { courseId } = req.query;
    let query = 'SELECT g.*, a.title as assignment_title, c.name as course_name, c.subject FROM grades g JOIN assignments a ON g.assignment_id = a.id 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 WHERE g.student_id = $1';
    const params = [studentId];
    if (courseId) { query += ' AND c.id = $' + (params.length + 1); params.push(courseId); }
    query += ' ORDER BY g.graded_date DESC';
    const result = await pool.query(query, params);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// ANALYTICS ROUTES
// =============================================

// Get student analytics
app.get('/api/analytics/:studentId', authenticateToken, async (req, res) => {
  try {
    const { studentId } = req.params;
    const gpaBySubject = await pool.query(
      'SELECT c.name, c.subject, c.course_type, AVG(g.percentage) as avg_percentage, COUNT(g.id) as total_graded, COUNT(CASE WHEN g.letter_grade = $2 THEN 1 END) as failed_count FROM grades g JOIN assignments a ON g.assignment_id = a.id 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 WHERE g.student_id = $1 GROUP BY c.id, c.name, c.subject, c.course_type ORDER BY c.subject',
      [studentId, 'F']
    );
    const assignmentStats = await pool.query(
      "SELECT COUNT(DISTINCT a.id) as total_assignments, COUNT(DISTINCT CASE WHEN g.id IS NOT NULL THEN a.id END) as completed, COUNT(DISTINCT CASE WHEN g.letter_grade = 'F' THEN a.id END) as failed, COUNT(DISTINCT CASE WHEN g.id IS NULL THEN a.id END) as pending 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 LEFT JOIN grades g ON a.id = g.assignment_id AND g.student_id = $1 WHERE e.student_id = $1 AND a.is_active = true",
      [studentId]
    );
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - weekStart.getDay());
    const hoursThisWeek = await pool.query(
      'SELECT COALESCE(SUM(total_hours), 0) as total_hours FROM daily_logs WHERE student_id = $1 AND log_date >= $2',
      [studentId, weekStart.toISOString().split('T')[0]]
    );
    const weightedGrades = await pool.query(
      "SELECT c.name, c.subject, AVG(CASE WHEN g.weight_category = 'homework' THEN g.percentage END) as homework_avg, AVG(CASE WHEN g.weight_category = 'quiz' THEN g.percentage END) as quiz_avg, AVG(CASE WHEN g.weight_category = 'test' THEN g.percentage END) as test_avg FROM grades g JOIN assignments a ON g.assignment_id = a.id 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 WHERE g.student_id = $1 GROUP BY c.id, c.name, c.subject",
      [studentId]
    );
    const attendanceSummary = await pool.query(
      "SELECT COUNT(CASE WHEN status = 'present' THEN 1 END) as present_days, COUNT(CASE WHEN status = 'absent' THEN 1 END) as absent_days, COUNT(CASE WHEN status = 'late' THEN 1 END) as late_days, COUNT(*) as total_days FROM attendance WHERE student_id = $1",
      [studentId]
    );
    res.json({
      gpaBySubject: gpaBySubject.rows,
      assignmentStats: assignmentStats.rows[0],
      hoursThisWeek: hoursThisWeek.rows[0],
      weightedGrades: weightedGrades.rows,
      attendanceSummary: attendanceSummary.rows[0]
    });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// DAILY LOG & TIME TRACKING ROUTES
// =============================================

// Get recent daily logs for dashboard (no auth - bridges demo to live data)
app.get('/api/daily-logs/student/:studentId/week', async (req, res) => {
  try {
    const { studentId } = req.params;
    const today = new Date();
    const weekAgo = new Date(today);
    weekAgo.setDate(today.getDate() - 7);
    const result = await pool.query(
      'SELECT * FROM daily_logs WHERE student_id = $1 AND log_date >= $2 ORDER BY log_date DESC LIMIT 7',
      [studentId, weekAgo.toISOString().split('T')[0]]
    );
    res.json(result.rows);
  } catch (error) {
    // Table might not have data yet - return empty array
    res.json([]);
  }
});

app.post('/api/daily-logs', authenticateToken, async (req, res) => {
  try {
    const { student_id, log_date, total_hours, math_hours, ela_hours, science_hours, social_studies_hours, elective_hours, subjects_covered, notes, day_status } = req.body;
    const result = await pool.query(
      'INSERT INTO daily_logs (student_id, log_date, total_hours, math_hours, ela_hours, science_hours, social_studies_hours, elective_hours, subjects_covered, notes, day_status, logged_by) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT (student_id, log_date) DO UPDATE SET total_hours=$3, math_hours=$4, ela_hours=$5, science_hours=$6, social_studies_hours=$7, elective_hours=$8, subjects_covered=$9, notes=$10, day_status=$11, updated_at=CURRENT_TIMESTAMP RETURNING *',
      [student_id, log_date, total_hours, math_hours || 0, ela_hours || 0, science_hours || 0, social_studies_hours || 0, elective_hours || 0, subjects_covered, notes, day_status || 'school_day', req.user.id]
    );
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

app.get('/api/daily-logs/:studentId', authenticateToken, async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    let query = 'SELECT * FROM daily_logs WHERE student_id = $1';
    const params = [req.params.studentId];
    if (startDate) { query += ' AND log_date >= $' + (params.length + 1); params.push(startDate); }
    if (endDate) { query += ' AND log_date <= $' + (params.length + 1); params.push(endDate); }
    query += ' ORDER BY log_date DESC';
    const result = await pool.query(query, params);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// ATTENDANCE ROUTES
// =============================================

app.post('/api/attendance', authenticateToken, async (req, res) => {
  try {
    const { student_id, attendance_date, status, check_in_time, check_out_time, total_hours, notes } = req.body;
    const result = await pool.query(
      'INSERT INTO attendance (student_id, attendance_date, status, check_in_time, check_out_time, total_hours, notes, recorded_by) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT (student_id, attendance_date) DO UPDATE SET status=$3, check_in_time=$4, check_out_time=$5, total_hours=$6, notes=$7 RETURNING *',
      [student_id, attendance_date, status, check_in_time, check_out_time, total_hours, notes, req.user.id]
    );
    res.json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

app.get('/api/attendance/:studentId', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM attendance WHERE student_id = $1 ORDER BY attendance_date DESC', [req.params.studentId]);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// COMMENTS ROUTES
// =============================================

app.post('/api/comments', authenticateToken, async (req, res) => {
  try {
    const { student_id, assignment_id, course_id, comment_text, comment_type, is_private } = req.body;
    const result = await pool.query(
      'INSERT INTO comments (student_id, assignment_id, course_id, user_id, comment_text, comment_type, is_private) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *',
      [student_id, assignment_id, course_id, req.user.id, comment_text, comment_type || 'general', is_private || false]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

app.get('/api/comments/:studentId', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query('SELECT c.*, u.first_name as teacher_name FROM comments c JOIN users u ON c.user_id = u.id WHERE c.student_id = $1 ORDER BY c.created_at DESC', [req.params.studentId]);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// CALENDAR ROUTES
// =============================================

app.get('/api/calendar', async (req, res) => {
  try {
    const { schoolYear } = req.query;
    let query = 'SELECT * FROM calendar_events';
    const params = [];
    if (schoolYear) { query += ' WHERE school_year = $1'; params.push(schoolYear); }
    query += ' ORDER BY event_date';
    const result = await pool.query(query, params);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// NOTIFICATIONS ROUTES
// =============================================

app.get('/api/notifications', authenticateToken, async (req, res) => {
  try {
    const result = await pool.query('SELECT * FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50', [req.user.id]);
    res.json(result.rows);
  } catch (error) { res.status(500).json({ error: error.message }); }
});

app.put('/api/notifications/:id/read', authenticateToken, async (req, res) => {
  try {
    await pool.query('UPDATE notifications SET is_read = true WHERE id = $1', [req.params.id]);
    res.json({ message: 'Notification marked as read' });
  } catch (error) { res.status(500).json({ error: error.message }); }
});

// =============================================
// HEALTH CHECK
// =============================================

app.get('/api/health', (req, res) => {
  res.json({ status: 'JNM Home Education Program API running', version: '1.0.0' });
});

// Start server
app.listen(PORT, () => {
  console.log('=================================');
  console.log('JNM Home Education Program API Server');
  console.log('Running on port ' + PORT);
  console.log('=================================');
});

module.exports = app;
