const RpafPaymentHead = require("../models/RpafPaymentHead");
const jwt = require("jsonwebtoken");
const errorHandler = require("../util/errorHandler");
const multer = require('multer');

// Get all Rpaf
exports.getAllRpafPaymentHead = async (req, res) => {
  try {
    const rpafhp = await RpafPaymentHead.findAll();

    const rpafPHresponse = rpafhp.map(rpafPH = ({
        reference_no,
        file_attach,
        cheque_amount,
        actual_amount_paid,
        CWT,
   }) => ({
        reference_no: reference_no,
        file_attach: file_attach,
        cheque_amount: cheque_amount,
        actual_amount_paid: actual_amount_paid,
        CWT:CWT,
   })
   
   );
   res.status(200).json(rpafPHresponse);
  }
   catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

exports.createRpafPaymentHead = (req, res, next) => {
  // Log the request body
  const { data } = req.body;
  const {
      cheque_amount,
      actual_amount_paid,
      CWT,
  } = data;

  // Generate a random reference number with the letters "REFNO"
  const reference_no = "REFNO" + Math.random().toString(36).substring(2, 10).toUpperCase();

  if (!req.files || !req.files.rpafpaymentheadPhoto) {
      return errorHandler("RpafPaymentHead photo is missing from the request.", 500);
  }

  const { rpafpaymentheadPhoto } = req.files;

  RpafPaymentHead.findOne({
      where: {
          reference_no: reference_no,
      },
  })
      .then((rpafPH) => {
          if (rpafPH) {
              return errorHandler("RpafPaymentHead ID already exists!", 401);
          }

          return new RpafPaymentHead({
              reference_no: reference_no,
              file_attach: rpafpaymentheadPhoto[0].filename || null,
              cheque_amount: cheque_amount,
              actual_amount_paid: actual_amount_paid,
              CWT: CWT,
          }).save();
      })
      .then(() => {
          res.status(201).json({ success: true });
      })
      .catch((err) => {
          next(err);
      });
};

  // Get a specific product by ID
exports.getrpafPHId =  async (req, res) => {
    const { rpafPHID } = req.params;
  
    try {
      const rpafPH = await RpafPaymentHead.findByPk(rpafPHID);
  
      if (!rpafPH) {
        return res.status(404).json({ error: "RpafPaymentHead ID not found" });
      }
  
      res.status(200).json(rpafPH);
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: "Internal Server Error" });
    }
  };
  exports.deleterpafPH = (req, res) => {
    const { rpafPHID } = req.params;
  
    try {
      const deletedRowCount = RpafPaymentHead.destroy({
        where: {
          id: rpafPHID,
        },
      });
  
      if (deletedRowCount === 0) {
        return res.status(404).json({ error: "Rpaf-Payment-Head not found" });
      }
  
      res.status(204).send();
    } catch (error) {
      console.error(error);
      res.status(500).json({ error: "Internal Server Error" });
    }
  };

  // Update a product by ID
  exports.updaterpafPH =  (req, res) => {
    const { rpafPHID } = req.params; // id
    const { data } = req.body;
    const { 
      cheque_amount,
      actual_amount_paid,
      CWT
    } = data;
  
     
    const { rpafpaymentheadPhoto } = req.files;
  
    RpafPaymentHead.findOne ({
        where:{
            id: rpafPHID,
              },
    })
    .then ((rpafph) => {
        if(!rpafph) {
            return errorHandler("Rpaf Payment Head ID does not exists!", 404);
        }
  
        if (rpafpaymentheadPhoto && rpafpaymentheadPhoto.length > 0) {
          rpafph.file_attach = rpafpaymentheadPhoto[0].filename;
        } 
        else {
          rpafph.file_attach = null;
        }

        rpafph.cheque_amount = cheque_amount,
        rpafph.actual_amount_paid = actual_amount_paid,
        rpafph.CWT = CWT;
  
        return rpafph.save();
    })
    .then(() => {
        res.status(200).json({ success: true });
    })
  };