const base64 = require("base-64");
const moment = require("moment/moment");

exports.getAccessToken = async (req, res, next) => {
  var headers = new Headers();
  headers.append("Content-Type", "application/x-www-form-urlencoded");
  headers.append(
    "Authorization",
    "Basic " +
      base64.encode(
        `${process.env.PAYPAL_CLIENT_ID}:${process.env.PAYPAL_CLIENT_SECRET}`
      )
  );

  var requestOptions = {
    method: "POST",
    headers: headers,
    body: "grant_type=client_credentials",
  };

  fetch("https://api-m.sandbox.paypal.com/v1/oauth2/token", requestOptions)
    .then((response) => response.text())
    .then((result) => {
      const { access_token } = JSON.parse(result);
      console.log(access_token);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "access token fetched successfully.",
        IsSuccess: true,
        Status_Code: 200,
        Data: access_token,
      });
    })
    .catch((error) => {
      console.log("error raised", error);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "Error fetching access token.",
        IsSuccess: false,
        Status_Code: 200,
        Data: null,
      });
    });
};

exports.createOrder = async (req, res, next) => {
  const body = req.body;
  var requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${body.token}`,
    },
    body: JSON.stringify(body.orderDetail),
  };

  fetch("https://api-m.sandbox.paypal.com/v2/checkout/orders", requestOptions)
    .then((response) => response.text())
    .then((result) => {
      const resp = JSON.parse(result);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "order created successfully.",
        IsSuccess: true,
        Status_Code: 200,
        Data: resp,
      });
    })
    .catch((error) => {
      console.log("error raised", error);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "Error creating order.",
        IsSuccess: false,
        Status_Code: 200,
        Data: null,
      });
    });
};

exports.capturePayment = async (req, res, next) => {
  const body = req.body;
  console.log(body);
  var requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${body.token}`,
    },
  };

  fetch(
    `https://api-m.sandbox.paypal.com/v2/checkout/orders/${body.id}/capture`,
    requestOptions
  )
    .then((response) => response.text())
    .then((result) => {
      console.log(result);
      const resp = JSON.parse(result);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "payment captured successfully.",
        IsSuccess: true,
        Status_Code: 200,
        Data: resp,
      });
    })
    .catch((error) => {
      console.log("error raised", error);

      res.setHeader("Content-Type", "application/javascript");
      res.status(200).send({
        message: "Error capturing payment.",
        IsSuccess: false,
        Status_Code: 200,
        Data: null,
      });
    });
};
