import axios from 'axios';
import CustomRequest from "../types/requestType";
import { Response } from "express";
import fs from 'fs';
import { promises as fsPromises } from 'fs';
// @ts-ignore
import pdf from "pdf-creator-node";
import CONSTANTS from '../config/constants';
import log from '../config/log';
import getRentReciptPoints from './getRentReciptPoints';
import settingsDB from '../models/settings.model';
import tenantDB from '../models/tenant.model';
import moment from 'moment';
import transactionDB from '../models/transaction.model';
export const generateRentReciept = async (details: any) => {
  try {
    let transactionId = details.transGId;
    // if (transactionId.length > 16) {
    //   transactionId = `${details.transGId.substring(0, 20)}`;
    // }
    const { tenantId, clientId, propId, roomId, bedId, rent } = details.occupancy;
    let extraData = "";
    if(clientId === 329 || clientId === 157) {
      let transData = await transactionDB.getByGId({gId: transactionId});
      if(transData?.bankRefNum) {
        extraData += `<p><strong>Bank Ref.:</strong> ${transData?.bankRefNum}</p>`;
      }
      if(transData?.remarks) {
        extraData += `<p><strong>Remark:</strong> ${transData?.remarks}</p>`;
      }
    }
    let settings = await settingsDB.getByClientIdAndPropId({
      clientId: clientId,
      propId: propId,
    });
    let propertyName = details.propName;
    if(settings?.brandName) {
      propertyName = settings?.brandName;
    }
    //details.address = details.address.length > 40 ? details.address.substring(0, 40) + "..." : details.address;
    let terms = await getRentReciptPoints(clientId);
    
    //let templatePath = "http://172.208.33.94:3001/uploads/documents/defaults/rent-reciept.html";
    let templatePath = process.env.RENT_RECEIPT!;
    let { data: html } = await axios.get(templatePath);
    
    let tenant = await tenantDB.getById ({
      id: tenantId,
    });
    let unitNum = `${details.roomNum}`;
    if (details.propType === CONSTANTS.PROPERTY_TYPE.FLAT) {
      unitNum = `${details.flatName} (${details.roomNum})`;
    }
    let propName = propertyName;
    let address = details.address;
    let tenantName = details.tenantName;
    let tenantMobile = tenant?.mobile;
    let tenantEmail = tenant?.email || '-';
    // let flatName = `Flat`;
    // let roomNum = `201`;
    //let rent = `9000`;
    let landlord = details.landlord;
    let landlordMobile = details.landlordNumber;
    let transGId = transactionId;
    let paidDate = details.paidDate;
    let amount = details?.amount;
    let recordedBy = details?.recordedBy || "Kipinn App";
    let mode = details?.mode;
    let logo = details.logo;
    let gst = "";
    if(details.isGstEnabled) {
      gst = `<p><span style="color:#888888">Invoice No:</span> ${details.transactionInvoiceNo}</p>
            <p><span style="color:#888888">GST No:</span> ${details.gstNo}</p>`;
    }
    html = html.toString();
    html = html.replace(/{{logo}}/g, logo);
    html = html.replace(/{{propName}}/g, propName);
    html = html.replace(/{{address}}/g, address);
    html = html.replace(/{{tenantName}}/g, tenantName);
    html = html.replace(/{{tenantMobile}}/g, tenantMobile);
    html = html.replace(/{{tenantEmail}}/g, tenantEmail);
    html = html.replace(/{{flatName}}/g, `${unitNum}`);

    html = html.replace(/{{rent}}/g, rent);
    html = html.replace(/{{managedBy}}/g, landlord);
    html = html.replace(/{{landlordMobile}}/g, landlordMobile);
    html = html.replace(/{{transGId}}/g, transGId);
    html = html.replace(/{{paidDate}}/g, paidDate);
    html = html.replace(/{{gst}}/g, gst);
    
    let trans = "";
    for (const dueStat of details.dueStats) {
      trans += `
        <tr style="border-bottom:1px solid #0078BD;">
            <td style="padding:8px;text-align: left;width:50%">${dueStat.title}</td>
            <td style="padding:8px;text-align: left;width:20%"></td>
            ${dueStat.amount < 0
          ? `<td style="padding:8px;text-align: center;width:30%">-₹${Math.abs(dueStat.amount)}</td>`
          : `<td style="padding:8px;text-align: center;width:30%">₹${dueStat.amount}</td>`
        } 
        </tr>`;
    }
    html = html.replace(/{{trans}}/g, trans);
    html = html.replace(/{{amount}}/g, amount);
    if(961 === clientId || 157 === clientId){
      recordedBy = "";
    } else {
      recordedBy = `<p>Recorded by: <strong>${recordedBy}</strong></p>`
    }
    html = html.replace(/{{recordedBy}}/g, recordedBy);
    html = html.replace(/{{mode}}/g, mode);
    html = html.replace(/{{terms}}/g, terms);
    html = html.replace(/{{extraData}}/g, extraData);
    html = html.replace(/\n/g, "");

    const options = {
      format: "A4",
      orientation: "portrait",
      border: "10mm",
      childProcessOptions: {
        env: {
          OPENSSL_CONF: "/dev/null",
        },
      },
    };

    const folderName = `tenant_${tenantId}`;
    const currentYear = moment().year();
    //const folderPath = `uploads/documents/${folderName}`;
    const folderPath = `uploads/documents/${currentYear}/receipt/${clientId}/${propId}/${roomId}_${bedId}/${folderName}`;

    if (!fs.existsSync(folderPath)) {
      await fsPromises.mkdir(folderPath, { recursive: true });
    }

    //const urlBasePath = `${process.env.UPLOAD_PATH}/documents/${folderName}`;
    const urlBasePath = `${process.env.UPLOAD_PATH}/documents/${currentYear}/receipt/${clientId}/${propId}/${roomId}_${bedId}/${folderName}`;
    //const filename = "reciept.pdf";
    const filename = `Receipt_${moment(details.paidDate).format("YYYYMMDD")}_${bedId}_${new Date().getTime().toString().slice(5)}.pdf`;
    let url = `${urlBasePath}/${filename}`;

    var document = {
      html: html,
      path: `${folderPath}/${filename}`,
      data: {},
      type: "",
    };

    await pdf.create(document, options);
    return url;
  } catch (error: any) {
    log.info(
      `[generateRentReciept], Tenant Name [${details.tenantName
      }], Start Date [${details.paidDate}], Error: ${JSON.stringify(error?.response?.data) || error?.message || error
      }`
    );

    return false;
  }
}
