const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken } = require('../middleware/auth');
const jwt = require('jsonwebtoken');

// OTP-based login system
router.post('/send-otp', async (req, res) => {
  try {
    const { phone_number } = req.body;
    
    // Check if parent exists
    const [parentRows] = await db.execute(
      'SELECT pp.*, u.id as user_id, u.first_name, u.last_name FROM parent_profiles pp JOIN users u ON pp.user_id = u.id WHERE pp.phone_number = ?',
      [phone_number]
    );
    
    if (parentRows.length === 0) {
      return res.status(404).json({ message: 'Parent not found with this phone number' });
    }
    
    // Generate 6-digit OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();
    const otpExpiry = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
    
    // Update OTP in database
    await db.execute(
      'UPDATE parent_profiles SET otp_code = ?, otp_expiry = ? WHERE phone_number = ?',
      [otp, otpExpiry, phone_number]
    );
    
    // In production, send SMS here
    console.log(`OTP for ${phone_number}: ${otp}`);
    
    res.json({ message: 'OTP sent successfully', otp_for_testing: otp }); // Remove otp_for_testing in production
  } catch (error) {
    console.error('Error sending OTP:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

router.post('/verify-otp', async (req, res) => {
  try {
    const { phone_number, otp } = req.body;
    
    const [parentRows] = await db.execute(
      `SELECT pp.*, u.id as user_id, u.first_name, u.last_name, u.email 
       FROM parent_profiles pp 
       JOIN users u ON pp.user_id = u.id 
       WHERE pp.phone_number = ? AND pp.otp_code = ? AND pp.otp_expiry > NOW()`,
      [phone_number, otp]
    );
    
    if (parentRows.length === 0) {
      return res.status(401).json({ message: 'Invalid or expired OTP' });
    }
    
    const parent = parentRows[0];
    
    // Clear OTP
    await db.execute(
      'UPDATE parent_profiles SET otp_code = NULL, otp_expiry = NULL, is_phone_verified = TRUE WHERE phone_number = ?',
      [phone_number]
    );
    
    // Generate JWT token
    const token = jwt.sign(
      { id: parent.user_id, phone: phone_number, role: 'parent' },
      process.env.JWT_SECRET,
      { expiresIn: '30d' }
    );
    
    res.json({
      token,
      user: {
        id: parent.user_id,
        name: `${parent.first_name} ${parent.last_name}`,
        phone: phone_number,
        email: parent.email,
        role: 'parent'
      }
    });
  } catch (error) {
    console.error('Error verifying OTP:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Get parent's children
router.get('/children', authenticateToken, async (req, res) => {
  try {
    const parentId = req.user.id;
    
    const query = `
      SELECT c.id, c.first_name, c.last_name, c.standard, c.division, c.roll_number,
             c.device_id, c.parent_mobile_1, c.parent_mobile_2,
             'SchoolTrack' as school_name
      FROM children c
      WHERE c.parent_id = ?
      ORDER BY c.first_name
    `;
    
    const [rows] = await db.execute(query, [parentId]);
    res.json(rows);
  } catch (error) {
    console.error('Error fetching children:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

// Test endpoint for parent children (no auth required)
router.get('/children-test', async (req, res) => {
  try {
    const { parent_email } = req.query;
    
    if (!parent_email) {
      return res.status(400).json({ message: 'Parent email is required' });
    }
    
    // Get parent ID from email
    const [parentRows] = await db.execute(
      'SELECT id FROM users WHERE email = ? AND user_type = ?',
      [parent_email, 'parent']
    );
    
    if (parentRows.length === 0) {
      return res.json([]);
    }
    
    const parentId = parentRows[0].id;
    
    const query = `
      SELECT c.id, c.first_name, c.last_name, c.standard, c.division, c.roll_number,
             c.device_id, c.parent_mobile_1, c.parent_mobile_2,
             'SchoolTrack' as school_name
      FROM children c
      WHERE c.parent_id = ?
      ORDER BY c.first_name
    `;
    
    const [rows] = await db.execute(query, [parentId]);
    res.json(rows);
  } catch (error) {
    console.error('Error fetching children:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;