const express = require('express');
const router = express.Router();
const { db } = require("../config/dbConfig");

router.get('/api/customer-suggestions', (req, res) => {
    const { name, phone } = req.query;
    let query = '';
    let params = [];

    if (name) {
        query = 'SELECT id, name, mobile FROM users WHERE name LIKE ? LIMIT 5';
        params = [`%${name}%`];
    } else if (phone) {
        query = 'SELECT id, name, mobile FROM users WHERE mobile LIKE ? LIMIT 5';
        params = [`%${phone}%`];
    } else {
        return res.status(400).json({ message: 'Name or phone parameter is required' });
    }

    db.query(query, params, (error, results) => {
        if (error) {
            console.error('Error fetching customer suggestions:', error);
            return res.status(500).json({ message: 'Error fetching customer suggestions' });
        }
        res.json(results);
    });
});

// Customer details route
router.get('/api/customer-details', (req, res) => {
    const { id } = req.query;
    const query = 'SELECT id, name, mobile, district, state FROM users WHERE id = ?';

    db.query(query, [id], (error, results) => {
        if (error) {
            console.error('Error fetching customer details:', error);
            return res.status(500).json({ message: 'Error fetching customer details' });
        }
        if (results.length === 0) {
            return res.status(404).json({ message: 'Customer not found' });
        }
        res.json(results[0]);
    });
});




module.exports = router;