const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const db = require("../db");

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

const upload = multer({ storage });

// ✅ Allow these 4 file fields
router.post(
  "/upload",
  upload.fields([
    { name: "profile_photo", maxCount: 1 },
    { name: "pan_photo", maxCount: 1 },
    { name: "address_proof", maxCount: 1 },
    { name: "bank_proof", maxCount: 1 },
  ]),
  (req, res) => {
    const {
      user_id,
      full_name,
     
      phone,
      address,
      pan_number,
      bank_name,
      account_number,
      ifsc_code,
    } = req.body;

    const profile_photo = req.files["profile_photo"]
      ? req.files["profile_photo"][0].filename
      : "";
    const pan_photo = req.files["pan_photo"]
      ? req.files["pan_photo"][0].filename
      : "";
    const address_proof = req.files["address_proof"]
      ? req.files["address_proof"][0].filename
      : "";
    const bank_proof = req.files["bank_proof"]
      ? req.files["bank_proof"][0].filename
      : "";

    // ✅ Step 1: Check if phone already exists
    const checkQuery = "SELECT * FROM kyc_details WHERE phone = ? and status!='Rejected'";
    db.query(checkQuery, [phone], (checkErr, results) => {
      if (checkErr) {
        console.error("Database Error:", checkErr);
        return res.status(500).json({
          error: true,
          message: checkErr.sqlMessage || checkErr.message,
          code: checkErr.code,
        });
      }

      if (results.length > 0) {
        // 🚫 Phone already registered
        return res.status(400).json({
          error: true,
          message: "❌ Mobile number already registered",
        });
      }

      // ✅ Step 2: Insert new KYC record
      const sql = `INSERT INTO kyc_details (
        user_id, full_name, phone, address, pan_number,
        bank_name, account_number, ifsc_code,
        profile_photo, pan_photo, address_proof, bank_proof
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

      db.query(
        sql,
        [
          user_id,
          full_name,
       
          phone,
          address,
          pan_number,
          bank_name,
          account_number,
          ifsc_code,
          profile_photo,
          pan_photo,
          address_proof,
          bank_proof,
        ],
        (err) => {
          if (err) {
            console.error("Database Error:", err);
            return res.status(500).json({
              error: true,
              message: err.sqlMessage || err.message,
              code: err.code,
            });
          }

          res.json({ message: "✅ KYC uploaded successfully" });
        }
      );
    });
  }
);

module.exports = router;
