const Visitor = require('../models/Visitor');

// Get all visitors
exports.getVisitors = async (req, res) => {
    try {
        const visitors = await Visitor.findAll();
        res.json(visitors);
    } catch (error) {
        res.status(500).json({ error: "Error fetching visitors" });
    }
};

// Get a single visitor by ID
exports.getVisitorById = async (req, res) => {
    try {
        const visitor = await Visitor.findByPk(req.params.id);
        if (!visitor) {
            return res.status(404).json({ error: "Visitor not found" });
        }
        res.json(visitor);
    } catch (error) {
        res.status(500).json({ error: "Error fetching visitor" });
    }
};

// Create a new visitor
exports.createVisitor = async (req, res) => {
    try {
        const { name, gender, email, mobile, date_of_visit,id_number } = req.body;
        const newVisitor = await Visitor.create({ name, gender, email, mobile, date_of_visit,id_number });
        res.status(201).json(newVisitor);
    } catch (error) {
        res.status(500).json({ error: "Error creating visitor" });
    }
};

// Update an existing visitor
exports.updateVisitor = async (req, res) => {
    try {
        const { name, gender, email, mobile, date_of_visit,id_number } = req.body;
        const visitor = await Visitor.findByPk(req.params.id);
        if (!visitor) {
            return res.status(404).json({ error: "Visitor not found" });
        }

        await visitor.update({ name, gender, email, mobile, date_of_visit,id_number });
        res.json(visitor);
    } catch (error) {
        res.status(500).json({ error: "Error updating visitor" });
    }
};

// Delete a visitor
exports.deleteVisitor = async (req, res) => {
    try {
        const visitor = await Visitor.findByPk(req.params.id);
        if (!visitor) {
            return res.status(404).json({ error: "Visitor not found" });
        }

        await visitor.destroy();
        res.json({ message: "Visitor deleted successfully" });
    } catch (error) {
        res.status(500).json({ error: "Error deleting visitor" });
    }
};
