// const express = require('express');
// const multer = require('multer');
// const cors = require('cors');
// const path = require('path');
// const app = express();
// const routes = require('./routes/panRoutes');
// const panVerifyRoute = require('./routes/panRoutes.js');  // Ensure this is correct
// app.use(panVerifyRoute); // or './routes/index.js'


// // Enable CORS and JSON parsing
// const corsOptions = {
//     origin: 'http://localhost:5174',
//     methods: ['GET', 'POST'],
//     allowedHeaders: ['Content-Type', 'Authorization'],
//     credentials: true,
//   };
//   app.use(cors(corsOptions));
  
// app.use(express.json());

// // File storage config (uploads will be stored in ./uploads folder)
// const storage = multer.diskStorage({
//   destination: (req, file, cb) => {
//     cb(null, './uploads');
//   },
//   filename: (req, file, cb) => {    
//     cb(null, Date.now() + path.extname(file.originalname)); // e.g., 1746543152975.png
//   }
// });

// const upload = multer({ storage });

// // API: Verify PAN and Image
// app.post('/api/verify-pan', upload.single('image'), (req, res) => {
//   const pan = req.body.pan;
//   const image = req.file;

//   if (!pan || !image) {
//     return res.status(400).json({ error: 'PAN number and image file are required.' });
//   }

//   console.log('Received PAN:', pan);
//   console.log('Uploaded image:', image.filename);

//   // Simulate processing here — e.g., verifying PAN from DB or calling API

//   res.json({
//     message: 'PAN and image received successfully.',
//     pan,
//     imageFilename: image.filename,
//   });
// });
// app.use(routes); // add this


// // Start server if this is the entry file
// const PORT = 5002;
// app.listen(PORT, () => {
//   console.log(`Backend running on http://localhost:${PORT}`);
// });




const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const app = express();

// First set up middleware before routes
// Enable CORS
const corsOptions = {
  origin: 'http://localhost:5174',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
};
app.use(cors(corsOptions));

// Enable JSON parsing
app.use(express.json());

// File storage config
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads');
  },
  filename: (req, file, cb) => {    
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage });

// Now define routes

// Direct route definition for PAN verification
// app.post('/api/verify-pan', upload.single('panImage'), (req, res) => {
//   const pan = req.body.pan;
//   const image = req.file;

//   if (!pan || !image) {
//     return res.status(400).json({ error: 'PAN number and image file are required.' });
//   }

//   console.log('Received PAN:', pan);
//   console.log('Uploaded image:', image.filename);

//   // Simulate verification - in a real app, do actual verification here
//   // For now, always return verified: true
//   res.json({
//     verified: true,
//     message: 'PAN and image received successfully.',
//     pan,
//     imageFilename: image.filename,
//   });
// });
// In your app.js or a dedicated route file

// Updated PAN verification endpoint
app.post('/api/verify-pan', upload.single('panImage'), (req, res) => {
    try {
      const pan = req.body.pan;
      const image = req.file;
  
      if (!pan || !image) {
        return res.status(400).json({ 
          verified: false,
          error: 'PAN number and image file are required.' 
        });
      }
  
      console.log('Received PAN:', pan);
      console.log('Uploaded image:', image.filename);
  
      // Validate PAN format - PAN format is typically 5 letters + 4 numbers + 1 letter
      const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
      if (!panRegex.test(pan)) {
        return res.status(400).json({
          verified: false,
          message: 'Invalid PAN format. It should be in the format ABCDE1234F.'
        });
      }
  
      // In a real app, you would:
      // 1. Perform OCR on the image to extract PAN details
      // 2. Verify against a database or external service
      // 3. Compare the extracted data with the provided PAN number
  
      // For testing purposes, let's simulate verification
      // Here we're just checking if the PAN follows the pattern and assumes it's valid
      // In production, replace this with actual verification logic
      
      const isValid = true; // Set to true for testing, but in production use actual verification
  
      if (isValid) {
        res.json({
          verified: true,
          message: 'PAN verified successfully.',
          pan,
          imageFilename: image.filename,
        });
      } else {
        res.json({
          verified: false,
          message: 'PAN verification failed. The provided PAN number does not match our records.'
        });
      }
    } catch (error) {
      console.error('Error verifying PAN:', error);
      res.status(500).json({
        verified: false,
        message: 'An error occurred during PAN verification.'
      });
    }
  });

// Add route for form submission
app.post('/api/vvet/add', upload.array('images'), (req, res) => {
  try {
    console.log('Form submission received:', req.body);
    console.log('Files received:', req.files);
    
    // Process the form data
    // Save to database, etc.
    
    res.json({ success: true, message: 'Form submitted successfully' });
  } catch (error) {
    console.error('Error processing form submission:', error);
    res.status(500).json({ success: false, message: 'Error processing form' });
  }
});

// Import other routes if needed
// Note: Only import panRoutes once
const routes = require('./routes/panRoutes');
app.use(routes);

// Start server
const PORT = 5002;
app.listen(PORT, () => {
  console.log(`Backend running on http://localhost:${PORT}`);
});
