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

// ----------------------------
// UPDATE PROFILE
// ----------------------------
router.put('/edit', (req, res) => {
  const { id, name, email, phone, password } = req.body;

  if (!id) return res.status(400).json({ message: 'User ID is required' });

  // Prepare query and parameters
  let updateQuery = '';
  let params = [];

  if (password && password.trim() !== '') {
    const hashedPassword = bcrypt.hashSync(password, 10);
    updateQuery = 'UPDATE users SET name=?, email=?, phone=?, password=? WHERE id=?';
    params = [name, email, phone, hashedPassword, id];
  } else {
    updateQuery = 'UPDATE users SET name=?, email=?, phone=? WHERE id=?';
    params = [name, email, phone, id];
  }

  db.query(updateQuery, params, (err, result) => {
    if (err) return res.status(500).json({ error: err });

    // Return updated user info
    db.query('SELECT id, name, email, phone FROM users WHERE id=?', [id], (err2, results) => {
      if (err2) return res.status(500).json({ error: err2 });
      res.json({ message: 'Profile updated successfully', user: results[0] });
    });
  });
});

// ----------------------------
// GET PROFILE
// ----------------------------
router.get('/edit', (req, res) => {
  const id = req.query.id;

  if (!id) return res.status(400).json({ message: 'User ID is required' });

  db.query('SELECT id, name, email, phone FROM users WHERE id=?', [id], (err, results) => {
    if (err) return res.status(500).json({ error: err });
    if (results.length === 0) return res.status(404).json({ message: 'User not found' });

    res.json({ user: results[0] });
  });
});

module.exports = router;
