"/**
 * Generates a formatted PDF report based on inputs from the "Main" sheet.
 * Features:
 * 1. Displays report generation time in "Main" sheet (H2).
 * 2. Supports different report types ("PnL", "PF", "Trade Log") from "Main" sheet (I3).
 * 3. Filters data based on start and end dates from "Main" sheet (I4, K4).
 * 4. Option to send email with the generated report (I5, J5).
 * 5. Filters data based on Asset Class, Broker, and User with support for "ALL" options (I7, J7, K7).
 * 6. Ensures barcode does not overlap with text by placing it in a separate cell.
 * 7. Generates unique 5-digit report numbers.
 * 8. Includes report generation time in the PDF.
 * 9. Places total rows at the top of the PDF.
 * 10. Starts Intraday report on a new page.
 * 11. Updates "% P/L (Abs.)" in the PDF.
 * 12. Logs each report generation in the "Log(s)" sheet with detailed information.
 * 13. Updates cell A2 in "Log(s)" sheet with the report generation completion time.
 */
function generateFreePDFReport() {
  const startTime = new Date(); // Capture the start time
  
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const mainSheet = ss.getSheetByName("Main");
  const logSheetName = "Log(s)";
  
  // Fetch inputs from Main sheet
  const reportType = mainSheet.getRange("I3").getValue().toString().trim(); // "PnL", "PF", "Trade Log"
  const startDate = mainSheet.getRange("I4").getValue(); // Start Date
  const endDate = mainSheet.getRange("K4").getValue(); // End Date
  const sendEmailFlag = mainSheet.getRange("I5").getValue().toString().trim().toLowerCase(); // "yes" or "no"
  const emailRecipient = mainSheet.getRange("J5").getValue().toString().trim(); // Email address
  const assetClassFilter = mainSheet.getRange("I7").getValue().toString().trim(); // Asset Class or "ALL"
  const brokerFilter = mainSheet.getRange("J7").getValue().toString().trim(); // Broker or "ALL"
  const userFilter = mainSheet.getRange("K7").getValue().toString().trim(); // User or "ALL"
  
  // Validate report type
  if (!["PnL", "PF", "Trade Log"].includes(reportType)) {
    Logger.log(`Invalid report type selected: ${reportType}. Please choose from "PnL", "PF", "Trade Log".`);
    mainSheet.getRange("H2").setValue("Invalid report type selected.");
    return;
  }
  
  if (reportType === "PnL") {
    generatePnLReport(ss, mainSheet, startDate, endDate, sendEmailFlag, emailRecipient, assetClassFilter, brokerFilter, userFilter, reportType);
  }
  
  // Future implementations for "PF" and "Trade Log" can be added here
  
  // Capture end time after report generation
  const endTime = new Date();
  const timeTakenSeconds = ((endTime - startTime) / 1000).toFixed(2);
  
  // Display the time taken in the Main sheet
  mainSheet.getRange("H2").setValue(`Report generated in ${timeTakenSeconds} seconds`);
  
  // Update cell A2 in "Log(s)" sheet with the completion time
  const logSheet = ss.getSheetByName(logSheetName);
  if (logSheet) {
    const formattedEndTime = Utilities.formatDate(endTime, Session.getScriptTimeZone(), "dd-MMM-yyyy HH:mm:ss");
    logSheet.getRange("A2").setValue(`Report last updated at: ${formattedEndTime}`);
  } else {
    Logger.log(`Log sheet "${logSheetName}" not found. Cannot update cell A2 with completion time.`);
  }
}

/**
 * Generates the PnL Report based on the provided filters and inputs.
 */
function generatePnLReport(ss, mainSheet, startDate, endDate, sendEmailFlag, emailRecipient, assetClassFilter, brokerFilter, userFilter, reportType) {
  // Sheet names
  const PNL_SHEET_NAME = "PnL";
  const PNL_I_SHEET_NAME = "PnL_i";
  const REPORT_SHEET_NAME = "Report";
  const LOG_SHEET_NAME = "Log(s)";
  
  // Retrieve and increment the unique report number
  const reportNumber = getNextReportNumber(ss, LOG_SHEET_NAME);
  const formattedReportNumber = Utilities.formatString("%05d", reportNumber);
  
  // Capture generation time for consistent timestamps
  const generationTime = new Date();
  
  // PDF file name using the consistent generation time
  const pdfName = `${reportType}_Report_${formattedReportNumber}_${Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "yyyyMMdd_HHmmss")}.pdf`;
  
  // Report Drive folder (ensure this folder exists)
  const folderName = "Trading Reports"; // Ensure this folder exists in your Drive
  const folder = getExistingFolder(folderName);
  
  if (!folder) {
    Logger.log(`Folder "${folderName}" not found. Please create it in Google Drive.`);
    mainSheet.getRange("H2").setValue(`Folder "${folderName}" not found.`);
    return;
  }
  
  // Create or clear the Report sheet
  let reportSheet = ss.getSheetByName(REPORT_SHEET_NAME);
  if (reportSheet) {
    reportSheet.clear();
  } else {
    reportSheet = ss.insertSheet(REPORT_SHEET_NAME);
  }
  
  // Insert Report Header (Report Number and Barcode)
  insertReportHeader(reportSheet, formattedReportNumber, generationTime);
  
  // Apply filters based on Main sheet inputs
  const filters = {
    assetClass: assetClassFilter,
    broker: brokerFilter,
    user: userFilter,
    startDate: startDate,
    endDate: endDate
  };
  
  // Append content from PnL and PnL_i with formatting and totals
  appendPnLSection(ss, reportSheet, PNL_SHEET_NAME, "Delivery Trades", filters);
  appendPnLSection(ss, reportSheet, PNL_I_SHEET_NAME, "Intraday Trades", filters, true); // Start Intraday on new page
  
  // Apply formatting to the Report sheet
  formatReportSheet(reportSheet);
  
  // Export to PDF
  const pdfBlob = exportSheetAsPDF(ss, REPORT_SHEET_NAME, pdfName, formattedReportNumber, generationTime);
  
  if (pdfBlob) {
    // Save PDF to Drive
    const pdfFile = folder.createFile(pdfBlob);
    Logger.log(`PDF report generated: ${pdfFile.getUrl()}`);
    
    // Email the PDF if required
    if (sendEmailFlag === "yes" && emailRecipient) {
      sendEmailWithReport(pdfFile, formattedReportNumber, generationTime, emailRecipient, reportType);
    }
    
    // Log the report generation with detailed information
    logReportGeneration(ss, LOG_SHEET_NAME, formattedReportNumber, reportType, sendEmailFlag, assetClassFilter, brokerFilter, userFilter, generationTime);
    
    // Delete the Report sheet to clean up
    ss.deleteSheet(reportSheet);
  } else {
    Logger.log("PDF blob was not created.");
    mainSheet.getRange("H2").setValue("Failed to generate PDF.");
  }
}

/**
 * Retrieves an existing folder by name. If it doesn't exist, returns null.
 * @param {string} folderName - The name of the folder.
 * @return {Folder|null} - The Google Drive folder or null if not found.
 */
function getExistingFolder(folderName) {
  const folders = DriveApp.getFoldersByName(folderName);
  if (folders.hasNext()) {
    return folders.next();
  } else {
    return null;
  }
}

/**
 * Retrieves the next unique report number from the Log(s) sheet and increments it.
 * @param {Spreadsheet} ss - The active spreadsheet.
 * @param {string} logSheetName - The name of the Log(s) sheet.
 * @return {number} - The unique report number.
 */
function getNextReportNumber(ss, logSheetName) {
  const logSheet = ss.getSheetByName(logSheetName);
  if (!logSheet) {
    Logger.log(`Log sheet "${logSheetName}" not found. Please create it with headers in row 4: Sl, Date time, Note.`);
    throw new Error(`Log sheet "${logSheetName}" not found.`);
  }
  
  const lastRow = logSheet.getLastRow();
  let nextReportNumber = 1;
  
  if (lastRow >= 4) { // Assuming data starts at row 4
    const lastReportNumber = logSheet.getRange(lastRow, 1).getValue();
    if (!isNaN(lastReportNumber) && lastReportNumber >= 1) {
      nextReportNumber = lastReportNumber + 1;
    }
  }
  
  return nextReportNumber;
}

/**
 * Inserts the report header including the report number and barcode into the Report sheet.
 * Ensures barcode is placed in a separate cell to avoid overlap.
 * @param {Sheet} reportSheet - The report sheet.
 * @param {string} reportNumber - The unique 5-digit report number.
 * @param {Date} generationTime - The consistent generation time.
 */
function insertReportHeader(reportSheet, reportNumber, generationTime) {
  // Insert Report Title
  reportSheet.appendRow([`Trading Report - Report #${reportNumber}`]);
  const titleRange = reportSheet.getRange(1, 1, 1, 1);
  titleRange.setFontWeight("bold").setFontSize(16);
  
  // Insert the generation timestamp
  const generatedAt = Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "dd-MMM-yyyy HH:mm:ss");
  reportSheet.appendRow([`Generated At: ${generatedAt}`]);
  const genAtRange = reportSheet.getRange(2, 1, 1, 1);
  genAtRange.setFontSize(12);
  
  // Insert a blank row
  reportSheet.appendRow(['']);
  
  // Generate Barcode Image URL using QuickChart
  const barcodeURL = `https://quickchart.io/barcode?text=${reportNumber}&format=png&type=code128&height=50`;
  
  try {
    const response = UrlFetchApp.fetch(barcodeURL);
    const barcodeBlob = response.getBlob().setName(`Barcode_Report_${reportNumber}.png`);
    
    // Insert the barcode image in a separate cell (e.g., Column A, Row 4)
    reportSheet.insertImage(barcodeBlob, 1, 4); // Column 1 (A), Row 4
  } catch (error) {
    Logger.log(`Error fetching barcode image: ${error}`);
  }
  
  // Add a blank row after the barcode
  reportSheet.appendRow(['']);
}

/**
 * Appends a PnL section (Delivery or Intraday) to the Report sheet, including data, formatting, and totals.
 * @param {Spreadsheet} ss - The active spreadsheet.
 * @param {Sheet} reportSheet - The report sheet.
 * @param {string} sheetName - The name of the PnL sheet ("PnL" or "PnL_i").
 * @param {string} sectionTitle - The title of the section ("Delivery Trades" or "Intraday Trades").
 * @param {Object} filters - Filters for Asset Class, Broker, User, Start Date, End Date.
 * @param {boolean} newPage - If true, starts the section on a new page.
 */
function appendPnLSection(ss, reportSheet, sheetName, sectionTitle, filters, newPage = false) {
  const pnlSheet = ss.getSheetByName(sheetName);
  if (!pnlSheet) {
    Logger.log(`Sheet "${sheetName}" not found.`);
    return;
  }
  
  // Apply filters and fetch data
  const { data, formats, headers } = getFilteredData(pnlSheet, filters);
  Logger.log(`${sectionTitle} Sheet filtered row count: ${data.length}`);
  
  if (data.length > 0) {
    if (newPage) {
      // Insert a page break by adding sufficient blank rows (Google Sheets doesn't support explicit page breaks)
      const blankRows = 10; // Adjust as needed for visual separation
      const blankRowData = Array(pnlSheet.getLastColumn()).fill('');
      for (let i = 0; i < blankRows; i++) {
        reportSheet.appendRow(blankRowData);
      }
    }
    
    // Append section title
    const startRow = reportSheet.getLastRow() + 1;
    reportSheet.appendRow([`${sectionTitle} - ${sheetName}`]);
    
    // Apply title formatting
    const titleRange = reportSheet.getRange(startRow, 1, 1, 1);
    titleRange.setFontWeight("bold").setFontSize(14);
    
    // Append headers from the original sheet
    reportSheet.appendRow(headers);
    
    // Apply header formatting
    const headerRange = reportSheet.getRange(startRow + 1, 1, 1, headers.length);
    headerRange.setFontWeight("bold").setBackground("#d3d3d3"); // Light gray background for headers
    
    // Append the data
    const dataStartRow = reportSheet.getLastRow() + 1;
    reportSheet.getRange(dataStartRow, 1, data.length, data[0].length).setValues(data);
    
    // Apply data formatting
    const dataRange = reportSheet.getRange(dataStartRow, 1, data.length, data[0].length);
    dataRange.setBackgrounds(formats.backgrounds);
    dataRange.setFontStyles(formats.fontStyles);
    dataRange.setFontSizes(formats.fontSizes);
    dataRange.setNumberFormats(formats.numberFormats);
    dataRange.setFontWeights(formats.fontWeights);
    dataRange.setFontColors(formats.fontColors);
    
    // Determine which columns to sum based on headers
    const columnsToSum = ["Value @ Buy", "Value @ Sell", "Gross PnP", "Fees", "Net PnL (After Fees)", "% P/L (Abs.)"];
    const columnIndices = getColumnIndices(headers, columnsToSum);
    
    if (columnIndices.length > 0) {
      // Insert Total Row immediately after data
      insertTotalRowAfter(reportSheet, dataStartRow, data.length, columnIndices, headers.length);
    }
  }
}

/**
 * Retrieves and filters data from a sheet based on provided filters.
 * Updates the existing "% P/L (Abs.)" column.
 * @param {Sheet} sheet - The sheet to retrieve data from.
 * @param {Object} filters - Filters for Asset Class, Broker, User, Start Date, End Date.
 * @return {Object} - An object containing data, formats, and headers arrays.
 */
function getFilteredData(sheet, filters) {
  const headerRow = 4; // Header is in row 4, data starts from row 5
  const lastRow = sheet.getLastRow();
  const lastColumn = sheet.getLastColumn();
  
  if (lastRow < headerRow + 1) { // No data
    return { data: [], formats: {}, headers: [] };
  }
  
  const dataRange = sheet.getRange(headerRow + 1, 1, lastRow - headerRow, lastColumn); // Data starts from row 5
  const data = dataRange.getValues();
  
  // Retrieve headers once to avoid multiple calls
  const headers = getHeaders(sheet);
  
  // Identify Date Column based on sheet name
  let dateHeaderName = "";
  const sheetName = sheet.getName();
  if (sheetName === "PnL") {
    dateHeaderName = "Sell Date";
  } else if (sheetName === "PnL_i") {
    dateHeaderName = "Trade Date"; // Corrected casing
  } else {
    throw new Error(`Unknown sheet name "${sheetName}".`);
  }
  
  const dateColumnIndex = headers.findIndex(header => header.toString().toLowerCase() === dateHeaderName.toLowerCase()) + 1; // 1-based index
  
  if (dateColumnIndex === 0) {
    throw new Error(`"${dateHeaderName}" column not found in headers.`);
  }
  
  // Determine the indices for necessary columns using case-insensitive matching
  const assetClassIndex = headers.findIndex(header => header.toString().toLowerCase() === "asset class") + 1;
  const brokerIndex = headers.findIndex(header => header.toString().toLowerCase() === "broker") + 1;
  const userIndex = headers.findIndex(header => header.toString().toLowerCase() === "user") + 1;
  const netProfitLossIndex = headers.findIndex(header => header.toString().toLowerCase() === "net pnl (after fees)") + 1;
  const valueBuyIndex = headers.findIndex(header => header.toString().toLowerCase() === "value @ buy") + 1;
  const percentPnLIndex = headers.findIndex(header => header.toString().toLowerCase() === "% p/l (abs.)") + 1; // 1-based
  
  // Validate essential headers
  if (
    assetClassIndex === 0 || 
    brokerIndex === 0 || 
    userIndex === 0 || 
    netProfitLossIndex === 0 || 
    valueBuyIndex === 0 || 
    percentPnLIndex === 0
  ) {
    throw new Error(`One or more required columns ("Asset Class", "Broker", "User", "Net PnL (After Fees)", "Value @ Buy", "% P/L (Abs.)") not found in headers.`);
  }
  
  // Filter data based on provided filters
  const filteredData = data.filter(row => {
    const date = row[dateColumnIndex - 1];
    if (!(date instanceof Date) || isNaN(date)) return false;
    if (filters.startDate && new Date(date) < new Date(filters.startDate)) return false;
    if (filters.endDate && new Date(date) > new Date(filters.endDate)) return false;
    
    if (filters.assetClass !== "ALL" && row[assetClassIndex - 1] !== filters.assetClass) return false;
    if (filters.broker !== "ALL" && row[brokerIndex - 1] !== filters.broker) return false;
    if (filters.user !== "ALL" && row[userIndex - 1] !== filters.user) return false;
    
    return true;
  });
  
  // Get formatting for filtered rows
  const backgrounds = [];
  const fontStyles = [];
  const fontSizes = [];
  const numberFormats = [];
  const fontWeights = [];
  const fontColors = [];
  
  filteredData.forEach((row, index) => {
    const sheetRow = headerRow + 1 + data.indexOf(row) + 1; // Adjusted to get correct row number
    const rowRange = sheet.getRange(sheetRow, 1, 1, lastColumn);
    backgrounds.push(rowRange.getBackgrounds()[0]);
    fontStyles.push(rowRange.getFontStyles()[0]);
    fontSizes.push(rowRange.getFontSizes()[0]);
    numberFormats.push(rowRange.getNumberFormats()[0]);
    fontWeights.push(rowRange.getFontWeights()[0]);
    fontColors.push(rowRange.getFontColors()[0]);
  });
  
  // Prepare data by updating "% P/L (Abs.)" calculation
  const finalData = filteredData.map(row => {
    const netProfitLoss = row[netProfitLossIndex - 1];
    const valueBuy = row[valueBuyIndex - 1];
    const percentPnL = valueBuy !== 0 ? (netProfitLoss / valueBuy) * 100 : 0;
    
    // Update the existing "% P/L (Abs.)" column
    row[percentPnLIndex - 1] = percentPnL.toFixed(2);
    
    return row;
  });
  
  return {
    data: finalData,
    formats: {
      backgrounds: backgrounds.length > 0 ? backgrounds : [[]],
      fontStyles: fontStyles.length > 0 ? fontStyles : [[]],
      fontSizes: fontSizes.length > 0 ? fontSizes : [[]],
      numberFormats: numberFormats.length > 0 ? numberFormats : [[]],
      fontWeights: fontWeights.length > 0 ? fontWeights : [[]],
      fontColors: fontColors.length > 0 ? fontColors : [[]]
    },
    headers: headers
  };
}

/**
 * Retrieves headers from the sheet.
 * @param {Sheet} sheet - The sheet from which to retrieve headers.
 * @return {Array} - An array of header names.
 */
function getHeaders(sheet) {
  const headers = sheet.getRange(4, 1, 1, sheet.getLastColumn()).getValues()[0]; // Header row is 4
  Logger.log(`Headers in sheet "${sheet.getName()}": ${headers}`);
  return headers;
}

/**
 * Retrieves the indices (1-based) of specified headers in a header row.
 * @param {Array} headers - The array of header names.
 * @param {Array} targetHeaders - The headers to find.
 * @return {Array} - The 1-based column indices of the target headers.
 */
function getColumnIndices(headers, targetHeaders) {
  const indices = [];
  const lowerCaseHeaders = headers.map(header => header.toString().toLowerCase());
  targetHeaders.forEach(targetHeader => {
    const targetIndex = lowerCaseHeaders.indexOf(targetHeader.toLowerCase());
    if (targetIndex !== -1) {
      indices.push(targetIndex + 1); // Convert to 1-based index
    }
  });
  return indices;
}

/**
 * Inserts a total row by summing specified columns after the data rows.
 * @param {Sheet} reportSheet - The report sheet.
 * @param {number} dataStartRow - The starting row number of the data (1-based).
 * @param {number} numRows - The number of data rows.
 * @param {Array<number>} columnIndices - The 1-based indices of the columns to sum.
 * @param {number} totalColumns - Total number of columns in the data.
 */
function insertTotalRowAfter(reportSheet, dataStartRow, numRows, columnIndices, totalColumns) {
  const totalRow = [];
  
  for (let i = 1; i <= totalColumns; i++) {
    if (i === 1) {
      totalRow.push("Total");
    } else if (columnIndices.includes(i)) {
      const columnLetter = columnToLetter(i);
      const formula = `=SUM(${columnLetter}${dataStartRow}:${columnLetter}${dataStartRow + numRows - 1})`;
      totalRow.push(formula);
    } else {
      totalRow.push('');
    }
  }
  
  // Insert the total row immediately after data
  reportSheet.appendRow(totalRow);
  
  const totalRowNumber = dataStartRow + numRows;
  
  // Apply formatting to the total row
  const totalRange = reportSheet.getRange(totalRowNumber, 1, 1, totalRow.length);
  totalRange.setFontWeight("bold").setBackground("#d3d3d3"); // Light gray background
  
  // Set number formats for total cells (adjust as needed)
  for (let i = 2; i <= totalRow.length; i++) { // Starting from column B
    if (columnIndices.includes(i)) {
      // Assuming numeric columns; adjust format as needed
      reportSheet.getRange(totalRowNumber, i).setNumberFormat("#,##0.00");
    }
  }
}

/**
 * Converts a column index (1-based) to its corresponding letter (e.g., 1 -> A).
 * @param {number} column - The 1-based column index.
 * @return {string} - The corresponding column letter.
 */
function columnToLetter(column) {
  let temp;
  let letter = '';
  while (column > 0) {
    temp = (column - 1) % 26;
    letter = String.fromCharCode(temp + 65) + letter;
    column = Math.floor((column - temp - 1) / 26);
  }
  return letter;
}

/**
 * Applies formatting to the Report sheet to make it systematic and beautiful.
 * Sets column widths, text alignment, frozen rows, and alternating row colors.
 * @param {Sheet} reportSheet - The report sheet.
 */
function formatReportSheet(reportSheet) {
  // Adjust column widths to fit content
  reportSheet.autoResizeColumns(1, reportSheet.getLastColumn());
  
  // Set text alignment to left for all cells
  const range = reportSheet.getDataRange();
  range.setHorizontalAlignment("left");
  
  // Freeze the top rows where headers and barcode are placed
  reportSheet.setFrozenRows(5); // Adjust based on the number of header rows
  
  // Apply alternating row colors (Zebra Striping) efficiently
  const numRows = reportSheet.getLastRow();
  const numColumns = reportSheet.getLastColumn();
  
  if (numRows > 5) { // Adjust based on frozen rows
    // Define the range excluding headers
    const dataRange = reportSheet.getRange(6, 1, numRows - 5, numColumns);
    
    // Create a 2D array for background colors
    const backgrounds = [];
    for (let i = 0; i < (numRows - 5); i++) {
      const isEven = (i + 1) % 2 === 0; // Start from the first data row as odd
      const rowColor = isEven ? "#f9f9f9" : "#ffffff"; // Light gray for even rows
      const rowBackground = Array(numColumns).fill(rowColor);
      backgrounds.push(rowBackground);
    }
    
    // Apply all background colors at once
    dataRange.setBackgrounds(backgrounds);
  }
}

/**
 * Exports a specific sheet as a PDF blob, including report number and generation time.
 * @param {Spreadsheet} ss - The active spreadsheet.
 * @param {string} sheetName - The name of the sheet to export.
 * @param {string} pdfName - The desired PDF file name.
 * @param {string} reportNumber - The unique report number.
 * @param {Date} generationTime - The consistent generation time.
 * @return {Blob|null} - The PDF blob of the sheet or null if export fails.
 */
function exportSheetAsPDF(ss, sheetName, pdfName, reportNumber, generationTime) {
  const sheet = ss.getSheetByName(sheetName);
  if (!sheet) {
    Logger.log(`Sheet "${sheetName}" not found.`);
    return null;
  }
  
  const sheetId = sheet.getSheetId();
  const url_base = ss.getUrl().replace(/edit$/, '');
  const exportUrl = url_base + 'export?' +
    'format=pdf&' + // export format
    'size=letter&' + // paper size
    'portrait=true&' + // orientation
    'fitw=true&' + // fit to width
    'sheetnames=false&' + // hide sheet names
    'printtitle=false&' + // hide title
    'pagenumbers=true&' + // show page numbers
    'gridlines=false&' + // hide gridlines
    'fzr=true&' + // repeat frozen rows on each page
    'gid=' + sheetId + '&' + // sheet ID
    'horizontal_alignment=LEFT&' + // alignment
    'vertical_alignment=TOP&' + // Changed from MIDDLE to TOP
    'top_margin=0.5&' + // margins in inches
    'bottom_margin=0.5&' + 
    'left_margin=0.5&' +
    'right_margin=0.5&';
  
  const options = {
    headers: {
      'Authorization': `Bearer ${ScriptApp.getOAuthToken()}`
    },
    muteHttpExceptions: true
  };
  
  try {
    const response = UrlFetchApp.fetch(exportUrl, options);
    if (response.getResponseCode() !== 200) {
      Logger.log(`Failed to fetch PDF. Response Code: ${response.getResponseCode()}`);
      return null;
    }
    const blob = response.getBlob().setName(pdfName);
    return blob;
  } catch (error) {
    Logger.log(`Error exporting sheet "${sheetName}" as PDF: ${error}`);
    return null;
  }
}

/**
 * Sends an email with the PDF report attached, including the unique report number and generation time.
 * @param {Blob} pdfFile - The PDF file blob to attach.
 * @param {string} reportNumber - The unique report number.
 * @param {Date} generationTime - The consistent generation time.
 * @param {string} emailRecipient - The recipient's email address.
 * @param {string} reportType - The type of report generated.
 */
function sendEmailWithReport(pdfFile, reportNumber, generationTime, emailRecipient, reportType) {
  const recipients = [emailRecipient]; // emailRecipient comes from Main sheet
  const subject = `${reportType} Report - Report #${reportNumber}`;
  
  const reportGenerationTime = Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "dd-MMM-yyyy HH:mm:ss");
  const body = `Please find attached the latest ${reportType} Report (Report #${reportNumber}) generated on ${reportGenerationTime}.\n\nRegards,\nNeeraj`;
  
  try {
    MailApp.sendEmail({
      to: recipients.join(","),
      subject: subject,
      body: body,
      attachments: [pdfFile]
    });
    Logger.log("PDF report emailed to recipients.");
  } catch (error) {
    Logger.log(`Error sending email: ${error}`);
  }
}

/**
 * Logs the report generation with report number, type, email status, and applied filters in the "Log(s)" sheet.
 * Does NOT modify cell A2.
 * @param {Spreadsheet} ss - The active spreadsheet.
 * @param {string} logSheetName - The name of the Log(s) sheet.
 * @param {string} reportNumber - The unique report number.
 * @param {string} reportType - The type of report generated.
 * @param {string} sendEmailFlag - "yes" or "no" indicating if email was sent.
 * @param {string} assetClassFilter - The Asset Class filter applied.
 * @param {string} brokerFilter - The Broker filter applied.
 * @param {string} userFilter - The User filter applied.
 * @param {Date} generationTime - The consistent generation time.
 */
function logReportGeneration(ss, logSheetName, reportNumber, reportType, sendEmailFlag, assetClassFilter, brokerFilter, userFilter, generationTime) {
  const logSheet = ss.getSheetByName(logSheetName);
  if (!logSheet) {
    Logger.log(`Log sheet "${logSheetName}" not found. Please create it with headers in row 4: Sl, Date time, Note.`);
    return;
  }
  
  // Find the next empty row starting from row 4
  const lastRow = logSheet.getLastRow();
  const nextRow = lastRow >= 4 ? lastRow + 1 : 4;
  
  // Prepare log data with detailed information
  const mailStatus = sendEmailFlag.toLowerCase() === "yes" ? "Mail_Sent" : "Mail_Void";
  const note = `${reportType} Report generated with Report Number ${reportNumber}_${mailStatus}_${assetClassFilter} | ${brokerFilter} | ${userFilter}`;
  
  // Prepare log data
  const logData = [
    reportNumber, // A: Sl (Seq Number)
    Utilities.formatDate(generationTime, Session.getScriptTimeZone(), "dd-MMM-yyyy HH:mm:ss"), // B: Date time
    note, // C: Note
    '', // D: (Reserved for future use)
    '', // E: 
    '', // F: 
    ''  // G: 
  ];
  
  // Fill A4:G accordingly
  logSheet.getRange(nextRow, 1, 1, logData.length).setValues([logData]);
  
  // **Important:** Do NOT update cell A2 to preserve its existing value
  // The following lines have been removed/commented out to prevent modifying A2
  /*
  // Update the last updated time in A2 with descriptive text
  const formattedUpdateTime = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd-MMM-yyyy HH:mm:ss");
  logSheet.getRange("A2").setValue(`Report Record last updated at : ${formattedUpdateTime}`);
  */
}

"

this script is working very correctly . isko more fast efficient optimise advanced krnah. core functionality bilbil i repeat bilkul touch nhi krnah .