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

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

    const rpafPresponse = rpaf.map(
      (rpafP = ({
        customer_id,
        status,
        remarks,
        agent_email,
        agent_code,
        applicant_signature,
        credit_limit,
        company_name,
        contact_person,
        company_email,
        phone,
        landline,
        area,
        address,
        addi_information,
        cement,
        finishing,
        fixtures,
        steel,
        aggregates,
        bankName,
        bankBranchName,
        bankAccountName,
        bankManagerName,
        bankAccNum,
        bankManagerPhone,
        bankEmail,
        storeFileName,
        birFile,
        mayorFileName,
        dtiFileName,
        bankFileName,
        bankAuthorizationFile,
        otherFileName,
        approvalFileName,
        govFileName,
        tinFileName,
        company__name,
        contact__name,
        address2,
        phone2,
        account_opened,
        credit_date_limit,
        phone3,
        current_bal,
      }) => ({
        customer_id: customer_id,
        status: status,
        remarks: remarks,
        agent_email: agent_email,
        agent_code: agent_code,
        applicant_signature: applicant_signature,
        credit_limit: credit_limit,
        company_name: company_name,
        contact_person: contact_person,
        company_email: company_email,
        phone: phone,
        landline: landline,
        area: area,
        address: address,
        addi_information: addi_information,
        cement: cement,
        finishing: finishing,
        fixtures: fixtures,
        steel: steel,
        aggregates: aggregates,
        bankName: bankName,
        bankBranchName: bankBranchName,
        bankAccountName: bankAccountName,
        bankManagerName: bankManagerName,
        bankAccNum: bankAccNum,
        bankManagerPhone: bankManagerPhone,
        bankEmail: bankEmail,
        storeFileName: storeFileName,
        birFile: birFile,
        mayorFileName: mayorFileName,
        dtiFileName: dtiFileName,
        bankFileName: bankFileName,
        bankAuthorizationFile: bankAuthorizationFile,
        otherFileName: otherFileName,
        approvalFileName: approvalFileName,
        govFileName: govFileName,
        tinFileName: tinFileName,
        company__name: company__name,
        contact__name: contact__name,
        address2: address2,
        phone2: phone2,
        account_opened: account_opened,
        credit_date_limit: credit_date_limit,
        phone3: phone3,
        current_bal: current_bal,
      }))
    );
    res.status(200).json(rpafPresponse);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

// Get a specific product by ID
exports.getrpafId = async (req, res) => {
  const { rpafID } = req.params;

  try {
    const rpaf = await Rpaf.findByPk(rpafID);

    if (!rpaf) {
      return res.status(404).json({ error: "Rpaf ID not found" });
    }

    res.status(200).json(rpaf);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

// Delete a product by ID
exports.deleterpaf = (req, res) => {
  const { rpafID } = req.params;

  try {
    const deletedRowCount = Rpaf.destroy({
      where: {
        id: rpafID,
      },
    });

    if (deletedRowCount === 0) {
      return res.status(404).json({ error: "Rpaf not found" });
    }

    res.status(204).send();
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

//Create
exports.createRpaf = (req, res, next) => {
  try {
    const { data } = req.body;
    const {
      customer_id,
      status,
      remarks,
      agent_email,
      agent_code,
      credit_limit,
      company_name,
      contact_person,
      company_email,
      phone,
      landline,
      area,
      address,
      addi_information,
      cement,
      finishing,
      fixtures,
      steel,
      aggregates,
      bankName,
      bankBranchName,
      bankAccountName,
      bankManagerName,
      bankAccNum,
      bankManagerPhone,
      bankEmail,
      storeFileName,
      mayorFileName,
      dtiFileName,
      bankFileName,
      bankAuthorizationFile,
      otherFileName,
      approvalFileName,
      govFileName,
      tinFileName,
      company__name,
      contact__name,
      address2,
      phone2,
      credit_date_limit,
      phone3,
      current_bal,
      // Segregate addresses
      city,
      barangay,
      address_line_1,
      address_line_2,
    } = data;

    const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(
      agent_email && company_email && bankEmail
    );
    if (!isValidEmail) {
      return res
        .status(400)
        .json({ error: "Please enter a valid email address" });
    }

    const currentDate = new Date();

    if (
      status !== "Approved" &&
      status !== "Suspended" &&
      status !== "Pending" &&
      status !== "Draft"
    ) {
      return errorHandler(
        'status must be "Approved", "Suspended", "Pending" , "Draft"',
        404
      );
    }

    if (!customer_id) {
      return errorHandler("Customer ID is missing from the request.", 400);
    }

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

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

    const { rpafPhoto } = req.files;
    const { applicant_signaturePhoto } = req.files;

    Rpaf.findOne({
      where: {
        customer_id: customer_id,
      },
    })
      .then((rpaf) => {
        if (rpaf) {
          return errorHandler("Rpaf ID already exists!", 401);
        }

        return new Rpaf({
          customer_id: customer_id,
          status: status,
          remarks: remarks,
          agent_email: isValidEmail,
          agent_code: agent_code,
          applicant_signature: applicant_signaturePhoto[0].filename || null,
          credit_limit: credit_limit,
          company_name: company_name,
          contact_person: contact_person,
          company_email: isValidEmail,
          phone: phone,
          landline: landline,
          area: area,
          address: address,
          addi_information: addi_information,
          cement: cement,
          finishing: finishing,
          fixtures: fixtures,
          steel: steel,
          aggregates: aggregates,
          bankName: bankName,
          bankBranchName: bankBranchName,
          bankAccountName: bankAccountName,
          bankManagerName: bankManagerName,
          bankAccNum: bankAccNum,
          bankManagerPhone: bankManagerPhone,
          bankEmail: isValidEmail,
          storeFileName: storeFileName,
          birFile: rpafPhoto[0].filename || null,
          mayorFileName: mayorFileName,
          dtiFileName: dtiFileName,
          bankFileName: bankFileName,
          bankAuthorizationFile: bankAuthorizationFile,
          otherFileName: otherFileName,
          approvalFileName: approvalFileName,
          govFileName: govFileName,
          tinFileName: tinFileName,
          company__name: company__name,
          contact__name: contact__name,
          address2: address2,
          phone2: phone2,
          account_opened: currentDate,
          credit_date_limit: credit_date_limit,
          phone3: phone3,
          current_bal: current_bal,
          // Segregate addresses
          city,
          barangay,
          address_line_1,
          address_line_2,
        }).save();
      })
      .then(() => {
        res.status(201).json({ success: true });
      })
      .catch((err) => {
        next(err);
      });
  } catch (error) {
    next(error);
  }
};

//Update

exports.updateRpaf = (req, res) => {
  const { rpafID } = req.params; // id
  const { data } = req.body;
  const {
    status,
    remarks,
    agent_email,
    agent_code,
    credit_limit,
    company_name,
    contact_person,
    company_email,
    phone,
    landline,
    area,
    address,
    addi_information,
    cement,
    finishing,
    fixtures,
    steel,
    aggregates,
    bankName,
    bankBranchName,
    bankAccountName,
    bankManagerName,
    bankAccNum,
    bankManagerPhone,
    bankEmail,
    storeFileName,
    mayorFileName,
    dtiFileName,
    bankFileName,
    bankAuthorizationFile,
    otherFileName,
    approvalFileName,
    govFileName,
    tinFileName,
    company__name,
    contact__name,
    address2,
    phone2,
    credit_date_limit,
    phone3,
    current_bal,
    // Segregate addresses
    city,
    barangay,
    address_line_1,
    address_line_2,
  } = data;
  const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(
    agent_email && company_email && bankEmail
  );
  if (!isValidEmail) {
    return res
      .status(400)
      .json({ error: "Please enter a valid email address" });
  }

  const currentDate = new Date();

  const { rpafPhoto } = req.files;
  const { applicant_signaturePhoto } = req.files;

  Rpaf.findOne({
    where: {
      id: rpafID,
    },
  })
    .then((rpaf) => {
      if (!rpaf) {
        return errorHandler("Rpaf ID does not exists!", 404);
      }

      if (
        status !== "Approved" &&
        status !== "Suspended" &&
        status !== "Pending" &&
        status !== "Draft"
      ) {
        return errorHandler(
          'status must be "Approved", "Suspended", "Pending" , "Draft"',
          404
        );
      }

      if (rpafPhoto && rpafPhoto.length > 0) {
        rpaf.birFile = rpafPhoto[0].filename;
      } else {
        rpaf.birFile = null;
      }
      if (applicant_signaturePhoto && applicant_signaturePhoto.length > 0) {
        rpaf.applicant_signature = applicant_signaturePhoto[0].filename;
      } else {
        rpaf.applicant_signature = null;
      }

      (rpaf.status = status),
        (rpaf.remarks = remarks),
        (rpaf.agent_email = isValidEmail),
        (rpaf.agent_code = agent_code),
        (rpaf.credit_limit = credit_limit),
        (rpaf.company_name = company_name),
        (rpaf.contact_person = contact_person),
        (rpaf.company_email = isValidEmail),
        (rpaf.phone = phone),
        (rpaf.landline = landline),
        (rpaf.area = area),
        (rpaf.address = address),
        (rpaf.addi_information = addi_information),
        (rpaf.cement = cement),
        (rpaf.finishing = finishing),
        (rpaf.fixtures = fixtures),
        (rpaf.steel = steel),
        (rpaf.aggregates = aggregates),
        (rpaf.bankName = bankName),
        (rpaf.bankBranchName = bankBranchName),
        (rpaf.bankAccountName = bankAccountName),
        (rpaf.bankManagerName = bankManagerName),
        (rpaf.bankAccNum = bankAccNum),
        (rpaf.bankManagerPhone = bankManagerPhone),
        (rpaf.bankEmail = isValidEmail),
        (rpaf.storeFileName = storeFileName),
        (rpaf.mayorFileName = mayorFileName),
        (rpaf.dtiFileName = dtiFileName),
        (rpaf.bankFileName = bankFileName),
        (rpaf.bankAuthorizationFile = bankAuthorizationFile),
        (rpaf.otherFileName = otherFileName),
        (rpaf.approvalFileName = approvalFileName),
        (rpaf.govFileName = govFileName),
        (rpaf.tinFileName = tinFileName),
        (rpaf.company__name = company__name),
        (rpaf.contact__name = contact__name),
        (rpaf.address2 = address2),
        (rpaf.phone2 = phone2),
        (rpaf.account_opened = currentDate),
        (rpaf.credit_date_limit = credit_date_limit),
        (rpaf.phone3 = phone3),
        (rpaf.current_bal = current_bal),
        (rpaf.city = city),
        (rpaf.barangay = barangay),
        (rpaf.address_line_1 = address_line_1),
        (rpaf.address_line_2 = address_line_2);

      return rpaf.save();
    })
    .then(() => {
      res.status(200).json({ success: true });
    });
};
