const express = require('express');
const router = express.Router();
const VCard = require('../models/VCard'); // Adjust path to your model
const upload = require('../config/multer'); // Import multer config


// Create a new vCard
router.post('/',upload.single('image'), async (req, res) => {
  try {
    const image_url = req.file ? `/uploads/${req.file.filename}` : null;
console.log("image url is", req.params.id);
    
const vCardData = {
    id: req.body.id,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    organization: req.body.organization,
    title: req.body.title,
    workPhone: req.body.workPhone,
    workPhone2: req.body.workPhone2,
    email: req.body.email,
    url: req.body.url,
    address:req.body.address,
    map:req.body.map,
    note: req.body.note,
    image_url: req.file ? `/uploads/${req.file.filename}` : null, // Save uploaded image path
  };

  console.log('vCard saved:', vCardData );





const newVCard = new VCard(vCardData ); // Use request body to populate the vCard
    const savedVCard = await newVCard.save();
    res.status(201).json({savedVCard,message:"successfully saved"});
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});


// Update a vCard by ID


// Update a vCard by ID with Image Upload
router.put('/:id', upload.single('image'), async (req, res) => {
    try {

        console.log("body is",req.body,req.params.id );

      const vCard = await VCard.findOne({ _id: req.params.id });
      if (!vCard) return res.status(404).json({ error: 'vCard not found' });
  
      // Check if a new image is provided
      let image_url = vCard.image_url; // Keep the current image by default
      if (req.file) {
        image_url = `/uploads/${req.file.filename}`; // Set the new image path
  
        // Optional: Remove the old image file
        const fs = require('fs');
        if (vCard.image_url) {
          const oldImagePath = `./public${vCard.image_url}`; // Adjust path as per your setup
          if (fs.existsSync(oldImagePath)) {
            fs.unlinkSync(oldImagePath); // Delete the old image
          }
        }
      }
  
      // Update vCard fields
      const updatedData = {
        ...req.body,
        image_url,
      };
  
      const updatedVCard = await VCard.findOneAndUpdate(
        { _id: req.params.id },
        updatedData,
        { new: true, runValidators: true }
      );
  console.log("updated data",updatedVCard);
  res.status(200).json({updatedVCard,message:"successfully updated"});
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  });
  

// Read all vCards
router.get('/', async (req, res) => {
  try {
    const vCards = await VCard.find();
    res.status(200).json(vCards);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Read a single vCard by ID
router.get('/:id', async (req, res) => {
  try {
    const vCard = await VCard.findOne({ _id: req.params.id });
    if (!vCard) return res.status(404).json({ error: 'vCard not found' });
    res.status(200).json(vCard);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});



// Delete a vCard by ID
router.delete('/:id', async (req, res) => {
  try {
    const deletedVCard = await VCard.findOneAndDelete({ _id: req.params.id });
    if (!deletedVCard) return res.status(404).json({ error: 'vCard not found' });
    res.status(200).json({ message: 'vCard deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
