const express = require('express');
const router = express.Router();
const db = require('../db');

// --------------------------------------
// CHECK IF MOBILE NUMBER IS REGISTERED
// --------------------------------------
router.post('/', (req, res) => {
  const { mobileno } = req.body;

  if (!mobileno) {
    return res.status(400).json({ message: 'Mobile number is required' });
  }

  db.query('SELECT id, name, phone FROM users WHERE phone = ?', [mobileno], (err, results) => {
    if (err) {
      console.error('DB Error:', err);
      return res.status(500).json({ message: 'Database error', error: err });
    }

    if (results.length > 0) {
      return res.status(200).json({
        registered: true,
        message: 'Mobile number is already registered',
        user: results[0],
      });
    } else {
      return res.status(200).json({
        registered: false,
        message: 'Mobile number is not registered',
      });
    }
  });
});

module.exports = router;
