const User = require("../../models").users;
const Pakages = require("../../models").packages;
const Activity = require("../helpers/activity.helper");
const PaystackDetails = require("../../models").paystack_details;
const paymentHistory = require("../../models").payment_history;
const BindingPayment = require("../../models").binding_payments;
const txnCode = require("../helpers/transactionCode.helper");
const e = require("express");
const TEST_SECRET_KEY = "sk_test_4f152f4b8ab4b91185b8731245869ff013513a6e";
const LIVE_SECRET_KEY = "sk_live_eea57e506b4376d66ad62dd27e7f4edb9e914922";

exports.initializeTransaction = async (req, res) => {
  try {
    const paystackKey = await PaystackDetails.findAll();
    const paystack = require("paystack")(paystackKey[0].LIVE_SECRET_KEY);
    // const paystack = require("paystack")(paystackKey[0].TEST_SECRET_KEY);
    const charges = 300.0;

    var getPakages = await Pakages.findOne({
      where: {
        id: req.body.paymentHash,
        active: 1,
      },
    });

    if (!getPakages) {
      return res.send({
        success: false,
        message: "ERROR",
        error: "An error ocurred, try again",
      });
    }

    const username = req.user.username;
    const amount = Number(getPakages.amount) + Number(charges);
    const pakageAmount = Number(getPakages.amount);
    const fullname = `${req.profile.firstname} ${req.profile.lastname} ${req.profile.middlename}`;
    const userEmail = req.user.email.toLowerCase().trim();

    var New_Txn_Ref = await txnCode();
    paystack.transaction
      .initialize({
        name: fullname,
        email: userEmail,
        amount: amount * 100, // this because paystack also send kobo
        reference: New_Txn_Ref,
        split_code: "SPL_GIWRjyY0sH",
        quantity: "1",
        metadata: {
          //other information you want to send with the transaction and check when verifying
          matricNumber: username,
          fullname,
        },
      })
      .then(async (transaction) => {
        const createTxnHistory = await paymentHistory.create({
          username,
          amount: pakageAmount,
          txn_ref: transaction.data.reference,
          package_id: getPakages.id,
        });

        const saveActivity = await Activity(
          "payment",
          "User initiate one-time access fee payment",
          req.user.username
        );

        if (createTxnHistory && transaction && saveActivity) {
          res.send({
            success: true,
            message: transaction.data.authorization_url,
          });
        } else {
          res.send({
            success: false,
            message: "ERROR",
            error: "An error ocurred, try again",
          });
        }
      });
  } catch (e) {
    res.send({
      success: false,
      message: "ERROR",
      error: "An error ocurred, try again",
    });
  }
};

exports.initializeTransactionBinding = async (req, res) => {
  try {
    const paystackKey = await PaystackDetails.findAll();
    const paystack = require("paystack")(LIVE_SECRET_KEY);
    // const paystack = require("paystack")(TEST_SECRET_KEY);
    const username = req.user.username;
    const amount = 3000;
    const fullname = `${req.profile.firstname} ${req.profile.lastname} ${req.profile.middlename}`;
    const userEmail = req.user.email.toLowerCase().trim();

    var New_Txn_Ref = await txnCode();
    paystack.transaction
      .initialize({
        name: fullname,
        email: userEmail,
        amount: amount * 100, // this because paystack also send kobo
        reference: New_Txn_Ref,
        quantity: "1",
        metadata: {
          //other information you want to send with the transaction and check when verifying
          matricNumber: username,
          fullname,
          paymentType: "Project Binding",
          user_id: req.user.id,
        },
      })
      .then(async (transaction) => {
        const createTxnHistory = await BindingPayment.create({
          user_id: req.user.id,
          amount: amount - 300,
          txn_ref: transaction.data.reference,
        });

        const saveActivity = await Activity(
          "payment",
          "User paid for project binding",
          req.user.username
        );

        if (createTxnHistory && transaction && saveActivity) {
          res.send({
            success: true,
            message: transaction.data.authorization_url,
          });
        } else {
          res.send({
            success: false,
            message: "ERROR",
            error: "An error ocurred, try again",
          });
        }
      });
  } catch (e) {
    console.log(e);
    res.send({
      success: false,
      message: "ERROR",
      error: "An error ocurred, try again",
    });
  }
};
exports.verifyPayment = async (paystackReference) => {
  console.log("verifyPayment-=========>" + paystackReference);
  try {
    const paystack = require("paystack")(TEST_SECRET_KEY);
    // const paystack = require("paystack")(LIVE_SECRET_KEY);

    var paystackCallbackRes;
    const verifyPay = await paystack.transaction
      .verify(paystackReference)
      .then((transaction) => {
        paystackCallbackRes = transaction.data;
      });

    if (paystackCallbackRes?.status != undefined) {
      if (paystackCallbackRes.status === "success") {
        const updateUser = {
          status: "PAID",
        };
        await BindingPayment.update(updateUser, {
          where: {
            txn_ref: paystackCallbackRes.reference,
            user_id: paystackCallbackRes.metadata.user_id,
          },
        });
        const updatePayment = {
          txn_desc: paystackCallbackRes.gateway_response,
          txn_status: paystackCallbackRes.status,
          txn_channel: paystackCallbackRes.channel,
        };

        await BindingPayment.update(updatePayment, {
          where: {
            txn_ref: paystackCallbackRes.reference,
            user_id: paystackCallbackRes.metadata.user_id,
          },
        });
        return true;
      } else {
        const updatePayment = {
          txn_desc: paystackCallbackRes.gateway_response,
          txn_status: paystackCallbackRes.status,
          txn_channel: paystackCallbackRes.channel,
        };

        const updateHistory = await paymentHistory.update(updatePayment, {
          where: {
            txn_ref: paystackCallbackRes.reference,
            user_id: paystackCallbackRes.metadata.user_id,
          },
        });
        return true;
      }
    }
  } catch (e) {
    console.log(e);
  }
};
exports.verifyPaymentBinding = async (req, res) => {
  try {
    const paystackKey = await PaystackDetails.findAll();
    const paystack = require("paystack")(LIVE_SECRET_KEY);
    //   const paystack = require("paystack")(TEST_SECRET_KEY);

    const paystackReference = req.body.reference;
    let paystackCallbackRes; // Use let instead of var for better scoping
    const verifyPay = await paystack.transaction
      .verify(paystackReference)
      .then((transaction) => {
        paystackCallbackRes = transaction.data;
      });

    if (paystackCallbackRes?.status !== undefined) {
      if (paystackCallbackRes.status === "success") {
        const updatePayment = {
          txn_desc: paystackCallbackRes.gateway_response,
          txn_status: paystackCallbackRes.status,
          txn_channel: paystackCallbackRes.channel,
        };

        // Update the payment details
        await BindingPayment.update(updatePayment, {
          where: {
            txn_ref: paystackCallbackRes.reference,
            user_id: paystackCallbackRes.metadata.user_id,
          },
        });

        // Update the user status
        const updateUser = {
          status: "PAID",
        };
        await BindingPayment.update(updateUser, {
          where: {
            txn_ref: paystackCallbackRes.reference,
            user_id: paystackCallbackRes.metadata.user_id,
          },
        });

        return res.status(200).send({
          statusCode: "200",
          success: true,
          message: paystackCallbackRes.gateway_response,
        });
      } else {
        return res.status(200).send({
          statusCode: "200",
          success: true,
          message: paystackCallbackRes.gateway_response,
        });
      }
    }
  } catch (e) {
    return res.status(500).send({
      statusCode: "500",
      success: false,
      message: "Error",
      error: e.message,
    });
  }
};
exports.initializeTransactionBindingMannually = async (req, res) => {
  const { payload, secretKey } = req.body;
  if(secretKey !== "b8ab4b91185b8731245869ff013513a6e"){
    return res.status(401).send({success:false, message:"Invalid Authentication!"})
  }
  if (!payload)
    return res
      .status(400)
      .send({ success: false, message: "Payload can not be empty" });

  let errorData = [];
  try {
    for (const username of payload) {
      const student = await User.findOne({ where: { username }, raw: true });
      if (student) {
        var New_Txn_Ref = await txnCode();
        try {
          await BindingPayment.create({
            user_id: student.id,
            amount: 9000,
            txn_ref: New_Txn_Ref,
            txn_status:"success",
            txn_channel:"school portal",
            status:"PAID"
          });
          await User.update(
            { 
                payment_status: "PAID",
                active: true
            },
            { where: { username } }
          );
          await Activity(
            "payment",
            "User project binding lodged",
            username
          );
        } catch (error) {
          errorData.push({
            matricNumber: username,
            message: error.message,
          });
        }
      } else {
        errorData.push({
          matricNumber: username,
          error: "Student Not found",
        });
      }
    }
    res.send({
      success: true,
      errorData,
    });
  } catch (e) {
    console.log(e);
    return res.status(500).send({
      success: false,
      message: e.message,
    });
  }
};
