
/**
 * STAFF DISPOSITION DATA COLLECTION
 * Creates a Google Form, linked Google Sheet,
 * and automatic staff email confirmation.
 *
 * Run createStaffDispositionCollection() ONCE.
 */

function createStaffDispositionCollection() {

  // 1. Create the central Google Spreadsheet
  const ss = SpreadsheetApp.create(
    "LAGOS STATE LGs and LCDAs - STAFF DISPOSITION DATA"
  );

  const linksSheet = ss.getSheets()[0];
  linksSheet.setName("ACCESS LINKS");

  // 2. Create the Google Form
  const form = FormApp.create(
    "LAGOS STATE LGs AND LCDAs - STAFF DISPOSITION DATA COLLECTION"
  );

  form.setDescription(
    "Official staff disposition data collection for Lagos State Local Government Service Commission. " +
    "Please provide accurate and current information. All required questions must be completed."
  );

  form.setConfirmationMessage(
    "SUCCESS! Your Staff Disposition information has been successfully submitted and recorded. " +
    "A confirmation email will be sent to the email address you provided. Thank you."
  );

  form.setAllowResponseEdits(false);
  form.setAcceptingResponses(true);

  // 3. Create form questions

  form.addTextItem()
    .setTitle("ORACLE ID")
    .setRequired(true);

  form.addTextItem()
    .setTitle("FULL NAME (SURNAME FIRST)")
    .setRequired(true);

  form.addTextItem()
    .setTitle("COMMISSION FILE NUMBER")
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE OF BIRTH")
    .setRequired(true);

  form.addTextItem()
    .setTitle("POST OF FIRST APPOINTMENT")
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE OF FIRST APPOINTMENT")
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE OF CONFIRMATION")
    .setRequired(false);

  form.addTextItem()
    .setTitle("CADRE")
    .setRequired(true);

  form.addTextItem()
    .setTitle("PRESENT POST / DESIGNATION")
    .setRequired(true);

  form.addTextItem()
    .setTitle("GRADE LEVEL")
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE OF APPOINTMENT TO PRESENT POST")
    .setRequired(false);

  form.addTextItem()
    .setTitle("STATE OF ORIGIN")
    .setRequired(true);

  form.addTextItem()
    .setTitle("PRESENT LGA / LCDA")
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE DEPLOYED TO PRESENT LGA / LCDA")
    .setRequired(false);

  form.addTextItem()
    .setTitle("EDUCATIONAL QUALIFICATION")
    .setRequired(true);

  form.addParagraphTextItem()
    .setTitle("PROFESSIONAL QUALIFICATION")
    .setRequired(false);

  form.addDateItem()
    .setTitle("EXIT / RETIREMENT DATE (IF APPLICABLE)")
    .setRequired(false);

  form.addTextItem()
    .setTitle("PHONE NUMBER")
    .setRequired(true);

  const emailItem = form.addTextItem()
    .setTitle("EMAIL ADDRESS")
    .setRequired(true);

  emailItem.setValidation(
    FormApp.createTextValidation()
      .requireTextIsEmail()
      .setHelpText("Please enter a valid email address.")
      .build()
  );

  form.addListItem()
    .setTitle("CURRENT EMPLOYMENT STATUS")
    .setChoiceValues([
      "In Active Service",
      "Retired",
      "Resigned",
      "Deceased",
      "Other"
    ])
    .setRequired(true);

  form.addDateItem()
    .setTitle("DATE PENSIONABLE SERVICE COMMENCED")
    .setRequired(false);

  // 4. Link the form to the central spreadsheet
  form.setDestination(
    FormApp.DestinationType.SPREADSHEET,
    ss.getId()
  );

  // 5. Install automatic email confirmation trigger
  ScriptApp.newTrigger("sendStaffDispositionConfirmation")
    .forForm(form)
    .onFormSubmit()
    .create();

  // 6. Save the access links in the spreadsheet
  linksSheet.getRange("A1:B4").setValues([
    ["STAFF DISPOSITION DATA COLLECTION", "LINK"],
    ["STAFF FORM - SHARE THIS LINK", form.getPublishedUrl()],
    ["GOOGLE SPREADSHEET - ADMIN ACCESS", ss.getUrl()],
    ["FORM EDITING LINK - ADMIN ONLY", form.getEditUrl()]
  ]);

  linksSheet.getRange("A1:B1").setFontWeight("bold");
  linksSheet.setColumnWidth(1, 280);
  linksSheet.setColumnWidth(2, 650);
  linksSheet.getRange("A1:B4").setWrap(true);

  SpreadsheetApp.flush();

  Logger.log("FORM LINK: " + form.getPublishedUrl());
  Logger.log("SPREADSHEET LINK: " + ss.getUrl());
  Logger.log("FORM EDIT LINK: " + form.getEditUrl());
}
/**
 * Sends acknowledgement email with individual edit link,
 * expected promotion date and expected retirement date.
 * Saves the edit link in column X.
 */

function sendStaffDispositionConfirmation(e) {

  try {

    const responses = e.response.getItemResponses();
    const submittedData = {};

    responses.forEach(function(itemResponse) {
      const question = itemResponse.getItem().getTitle().trim();
      submittedData[question] = itemResponse.getResponse();
    });

    const email = String(submittedData["EMAIL ADDRESS"] || "").trim();

    if (!email) {
      throw new Error("No email address was provided.");
    }

    const oracleId = submittedData["ORACLE ID"] || "Not provided";
    const fullName =
      submittedData["FULL NAME (SURNAME FIRST)"] || "Staff Member";

    const gradeLevel = submittedData["GRADE LEVEL"];
    const gradeDate =
      submittedData["DATE OF PRESENT APPOINTMENT/GRADE LEVEL"] || "";
    Logger.log("GRADE LEVEL received: " + JSON.stringify(gradeLevel));
Logger.log("GRADE DATE received: " + JSON.stringify(gradeDate));
Logger.log("GRADE DATE type: " + typeof gradeDate);
Logger.log("ALL FORM QUESTION TITLES: " + JSON.stringify(Object.keys(submittedData)));
    const firstAppointment = submittedData["DATE OF FIRST APPOINTMENT"];
    const dateOfBirth = submittedData["DATE OF BIRTH"];

    // Generate individual edit link
    const editLink = e.response.getEditResponseUrl();

    if (!editLink) {
      throw new Error("Could not generate edit-response link.");
    }

    // Open response spreadsheet
    const ss = SpreadsheetApp.openById(
  "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU"
);

    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Form Responses 1 worksheet was not found.");
    }

    // Locate submitted response row using timestamp
    const submittedTimestamp = e.response.getTimestamp().getTime();
    const lastRow = sheet.getLastRow();

    if (lastRow < 2) {
      throw new Error("No response row was found.");
    }

    const timestamps = sheet.getRange(2, 1, lastRow - 1, 1).getValues();
    let responseRow = -1;

    for (let i = timestamps.length - 1; i >= 0; i--) {
      if (
        timestamps[i][0] instanceof Date &&
        Math.abs(timestamps[i][0].getTime() - submittedTimestamp) < 1000
      ) {
        responseRow = i + 2;
        break;
      }
    }

    if (responseRow === -1) {
      throw new Error("Could not locate the submitted response row.");
    }

    // Save edit link in column X
    // Identify columns by their headings
const headers = sheet.getRange(
  1, 1, 1, sheet.getLastColumn()
).getDisplayValues()[0];

function findColumnByHeader_(headerName) {
  const index = headers.findIndex(header =>
    String(header).trim().toUpperCase() ===
    headerName.trim().toUpperCase()
  );

  if (index === -1) {
    throw new Error(
      "Column heading not found: " + headerName
    );
  }

  return index + 1;
}

// ============================================
// ORACLE ID DUPLICATE STAFF RECORD PREVENTION
// ============================================

const duplicateLock = LockService.getScriptLock();
duplicateLock.waitLock(30000);

try {

  // Standardise Oracle ID for comparison
  const submittedOracleId = String(oracleId || "")
    .trim()
    .replace(/\s+/g, "")
    .toUpperCase();

  if (!submittedOracleId) {
    throw new Error("Oracle ID is missing.");
  }

  // Find the Oracle ID column
  const oracleColumn = findColumnByHeader_("ORACLE ID");

  // Read existing Oracle IDs
  const oracleValues = sheet.getRange(
    2,
    oracleColumn,
    lastRow - 1,
    1
  ).getDisplayValues();

  let duplicateRow = -1;

  for (let i = 0; i < oracleValues.length; i++) {

    const existingOracleId = String(oracleValues[i][0] || "")
      .trim()
      .replace(/\s+/g, "")
      .toUpperCase();

    const currentRow = i + 2;

    // Exclude the current response so staff can edit their own record
    if (
      currentRow !== responseRow &&
      existingOracleId === submittedOracleId
    ) {
      duplicateRow = currentRow;
      break;
    }
  }

  // Reject a new submission if Oracle ID already exists
  if (duplicateRow !== -1) {

    const existingEditLink = sheet.getRange(
      duplicateRow,
      findColumnByHeader_("EDIT RESPONSE LINK")
    ).getDisplayValue();

    // Delete the duplicate from Google Form
    e.source.deleteResponse(e.response.getId());

    // Remove the duplicate row from the response spreadsheet
    sheet.deleteRow(responseRow);

    // Notify the staff member
    const duplicateSubject =
      "Duplicate Staff Record - Oracle ID Already Registered";

    const duplicateBody =
      "Dear " + fullName + ",\n\n" +
      "Your Staff Disposition submission was not accepted because " +
      "Oracle ID " + submittedOracleId +
      " already exists in the staff database.\n\n" +
      "Please do not submit another registration.\n\n" +
      (
        existingEditLink
          ? "To correct your existing record, use this personal editing link:\n" +
            existingEditLink + "\n\n"
          : "Please contact your HR Officer for assistance in locating your existing record.\n\n"
      ) +
      "Thank you.\n" +
      "Lagos State Local Government Service Commission";

    MailApp.sendEmail({
      to: email,
      subject: duplicateSubject,
      body: duplicateBody,
      name: "Lagos State Local Government Service Commission"
    });

    Logger.log(
      "Duplicate Oracle ID rejected: " + submittedOracleId
    );

    return;
  }

} finally {
  duplicateLock.releaseLock();
}

// END OF ORACLE ID DUPLICATE PREVENTION

// Save edit link under the correct heading
sheet.getRange(
  responseRow,
  findColumnByHeader_("EDIT RESPONSE LINK")
).setValue(editLink);
    

    // Convert form dates safely
    function parseDate(value) {
      if (!value) return null;

      if (value instanceof Date && !isNaN(value.getTime())) {
        return new Date(
          value.getFullYear(),
          value.getMonth(),
          value.getDate()
        );
      }

      const parsed = new Date(value);

      if (isNaN(parsed.getTime())) return null;

      return new Date(
        parsed.getFullYear(),
        parsed.getMonth(),
        parsed.getDate()
      );
    }

    function addYears(date, years) {
      const result = new Date(date);
      const month = result.getMonth();
      result.setFullYear(result.getFullYear() + years);

      // Handle dates such as 29 February
      if (result.getMonth() !== month) {
        result.setDate(0);
      }

      return result;
    }

    function formatDate(date) {
      if (!date) return "Unable to calculate";

      return Utilities.formatDate(
        date,
        Session.getScriptTimeZone(),
        "dd MMMM yyyy"
      );
    }

    // Calculate expected promotion date
    const promotionPeriods = {
      7: 3,
      8: 3,
      9: 3,
      10: 3,
      12: 3,
      13: 3,
      14: 3,
      15: 4,
      16: 4
    };

    const gradeNumber = String(gradeLevel || "").match(/\d+/);
    const currentGrade = gradeNumber ? Number(gradeNumber[0]) : null;
    const promotionDateBase = parseDate(gradeDate);

    let expectedPromotion = "Unable to calculate";

    if (
      currentGrade !== null &&
      promotionDateBase &&
      promotionPeriods[currentGrade]
    ) {
      expectedPromotion = formatDate(
        addYears(promotionDateBase, promotionPeriods[currentGrade])
      );
    }

    // Calculate expected retirement date
    const birthDate = parseDate(dateOfBirth);
    const firstAppointmentDate = parseDate(firstAppointment);

    let expectedRetirement = "Unable to calculate";

    if (birthDate && firstAppointmentDate) {

      const retirementByAge = addYears(birthDate, 60);
      const retirementByService = addYears(firstAppointmentDate, 35);

      const retirementDate =
        retirementByAge <= retirementByService
          ? retirementByAge
          : retirementByService;

      expectedRetirement = formatDate(retirementDate);
    }
// Save expected service dates under their correct headings
sheet.getRange(
  responseRow,
  findColumnByHeader_("EXPECTED NEXT PROMOTION DATE")
).setValue(expectedPromotion);

sheet.getRange(
  responseRow,
  findColumnByHeader_("EXPECTED RETIREMENT DATE")
).setValue(expectedRetirement);
    // Prepare acknowledgement email
    const subject =
      "Confirmation of Staff Disposition Data Submission";

    const body =
      "Dear " + fullName + ",\n\n" +
      "Your Staff Disposition information has been successfully submitted.\n\n" +
      "SUBMISSION DETAILS\n" +
      "Oracle ID: " + oracleId + "\n" +
      "Submission Status: Successfully Collected\n" +
      "Date Submitted: " + new Date().toLocaleString() + "\n\n" +
      "EXPECTED SERVICE DATES\n" +
      "Expected Next Promotion Date: " + expectedPromotion + "\n" +
      "Expected Retirement Date: " + expectedRetirement + "\n\n" +
      "EDIT YOUR SUBMISSION:\n" + editLink + "\n\n" +
      "Please retain this email for your records.\n\n" +
      "Thank you.\n" +
      "Lagos State Local Government Service Commission";

    const htmlBody =
      "<p>Dear " + fullName + ",</p>" +
      "<p>Your Staff Disposition information has been successfully submitted.</p>" +
      "<p><b>SUBMISSION DETAILS</b><br>" +
      "Oracle ID: " + oracleId + "<br>" +
      "Submission Status: Successfully Collected<br>" +
      "Date Submitted: " + new Date().toLocaleString() + "</p>" +
      "<p><b>EXPECTED SERVICE DATES</b><br>" +
      "Expected Next Promotion Date: " + expectedPromotion + "<br>" +
      "Expected Retirement Date: " + expectedRetirement + "</p>" +
      "<p><b>EDIT YOUR SUBMISSION</b><br>" +
      '<a href="' + editLink + '">CLICK HERE TO EDIT YOUR SUBMISSION</a></p>' +
      "<p><i>Note: These dates are estimates based on the information submitted and the stated service rules. Official verification is required.</i></p>" +
      "<p>Please retain this email for your records.</p>" +
      "<p>Thank you.<br>" +
      "Lagos State Local Government Service Commission</p>";
Logger.log("Remaining email quota: " + MailApp.getRemainingDailyQuota());
    MailApp.sendEmail({
      to: email,
      subject: subject,
      body: body,
      htmlBody: htmlBody,
      name: "Lagos State Local Government Service Commission"
    });

    Logger.log("Confirmation email sent to: " + email);
    Logger.log("Edit link saved in row: " + responseRow);

  } catch (error) {

    Logger.log("Email confirmation error: " + error.message);
    throw error;

  }
}

function authorizeDriveAccess() {
  const folderName = DriveApp.getRootFolder().getName();
  Logger.log("Drive access authorised: " + folderName);
}


/****************************************************
 * STAFF DISPOSITION - ORACLE ID VERIFICATION
 * Checks the existing central response spreadsheet.
 ****************************************************/

function checkOracleIdAvailability(oracleId) {

  const submittedId = String(oracleId || "")
    .trim()
    .toUpperCase();

  if (!submittedId) {
    return {
      available: false,
      exists: false,
      message: "Please enter a valid Oracle ID."
    };
  }

  const lock = LockService.getScriptLock();

  try {

    lock.waitLock(10000);

    const ss = SpreadsheetApp.openById(
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU"
    );

    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Form Responses 1 sheet was not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      return {
        available: true,
        exists: false,
        message: "Oracle ID is available."
      };
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const oracleColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "ORACLE ID";
    });

    if (oracleColumn === -1) {
      throw new Error("ORACLE ID column was not found.");
    }

    const oracleValues = sheet.getRange(
      2,
      oracleColumn + 1,
      lastRow - 1,
      1
    ).getDisplayValues();

    const duplicateFound = oracleValues.some(function(row) {

      const existingId = String(row[0] || "")
        .trim()
        .toUpperCase();

      return existingId === submittedId;

    });

    if (duplicateFound) {
      return {
        available: false,
        exists: true,
        message: "This Oracle ID already exists in the staff records."
      };
    }

    return {
      available: true,
      exists: false,
      message: "Oracle ID is available."
    };

  } catch (error) {

    Logger.log(
      "Oracle ID verification error: " + error.message
    );

    return {
      available: false,
      exists: false,
      message: "Unable to verify Oracle ID. Please try again or contact the administrator."
    };

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }

}

/****************************************************
 * STAFF DISPOSITION - CUSTOM WEB FORM
 * Opens the new StaffForm.html page.
 ****************************************************/


/****************************************************
 * STAFF DISPOSITION - CUSTOM WEB FORM
 * Supports new submissions and individual editing.
 ****************************************************/

/****************************************************
 * CUSTOM STAFF FORM - SECURE SUBMISSION
 * Prevents duplicate Oracle IDs at the point of saving.
 ****************************************************/

function submitStaffDisposition(data) {
// TEMPORARY STAFF SUBMISSION CONTROL
const submissionPaused =
  PropertiesService.getScriptProperties()
    .getProperty("STAFF_SUBMISSIONS_PAUSED");

if (submissionPaused === "TRUE") {
  return {
    success: false,
    message: "Staff submissions are temporarily paused for system maintenance. Please try again later."
  };
}
  const lock = LockService.getScriptLock();

  try {

    lock.waitLock(30000);

    const spreadsheetId =
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU";

    const ss = SpreadsheetApp.openById(spreadsheetId);
    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("The response worksheet was not found.");
    }

    const oracleId = String(data["ORACLE ID"] || "")
      .trim()
      .toUpperCase();

    if (!oracleId) {
      return {
        success: false,
        message: "Please enter your Oracle ID."
      };
    }

    // SECOND DUPLICATE CHECK - BEFORE SAVING

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const oracleColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "ORACLE ID";
    });

    if (oracleColumn === -1) {
      throw new Error("Oracle ID column was not found.");
    }

    if (lastRow >= 2) {

      const existingIds = sheet.getRange(
        2,
        oracleColumn + 1,
        lastRow - 1,
        1
      ).getDisplayValues();

      const duplicate = existingIds.some(function(row) {
        return String(row[0] || "").trim().toUpperCase() === oracleId;
      });

      if (duplicate) {
        return {
          success: false,
          duplicate: true,
          message: "Submission rejected. This Oracle ID has already been registered."
        };
      }
    }

    
    // VALIDATE REQUIRED STAFF INFORMATION

    const requiredFields = [
      "ORACLE ID",
      "FULL NAME (SURNAME FIRST)",
      "GENDER",
      "COMMISSION FILE NUMBER",
      "DATE OF BIRTH",
      "POST OF FIRST APPOINTMENT/GRADE LEVEL",
      "DATE OF FIRST APPOINTMENT",
      "DATE OF PRESENT APPOINTMENT/GRADE LEVEL",
      "DATE DEPLOYED TO PRESENT LGA / LCDA",
      "CURRENT EMPLOYMENT STATUS",
      "PHONE NUMBER",
      "EMAIL ADDRESS",
      "POST OF PRESENT APPOINTMENT/GRADE LEVEL",
      "CADRE",
      "STATE OF ORIGIN",
      "GRADE LEVEL",
      "EDUCATIONAL QUALIFICATION",
      "PRESENT LGA / LCDA",
      "RESIDENTIAL ADDRESS",
      "LASHMA NUMBER"
    ];

    for (const field of requiredFields) {
      if (!String(data[field] || "").trim()) {
        return {
          success: false,
          message: "Please provide the required information: " + field
        };
      }
    }

    // VALIDATE EMAIL ADDRESS

    const email = String(data["EMAIL ADDRESS"] || "").trim();

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return {
        success: false,
        message: "Please provide a valid email address."
      };
    }


    // ENSURE CUSTOM EDIT TOKEN COLUMN EXISTS

    let tokenColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "CUSTOM EDIT TOKEN";
    });

    if (tokenColumn === -1) {
      tokenColumn = sheet.getLastColumn();
      sheet.getRange(1, tokenColumn + 1)
        .setValue("CUSTOM EDIT TOKEN");
      headers.push("CUSTOM EDIT TOKEN");
    }

    // PREPARE THE NEW RESPONSE ROW

    const row = new Array(headers.length).fill("");

    const timestampColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "TIMESTAMP";
    });

    if (timestampColumn !== -1) {
      row[timestampColumn] = new Date();
    }

    Object.keys(data).forEach(function(key) {

      const column = headers.findIndex(function(header) {
        return String(header).trim().toUpperCase() ===
          key.trim().toUpperCase();
      });

      if (column !== -1) {
        row[column] = data[key];
      }

    });

    // USE THE PRESENT-POST APPOINTMENT DATE FOR PROMOTION CALCULATION

    function parseDate(value) {
      if (!value) return null;

      const date = value instanceof Date
        ? new Date(value)
        : new Date(String(value));

      if (isNaN(date.getTime())) return null;

      return new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate()
      );
    }

    function addYears(date, years) {
      const result = new Date(date);
      const month = result.getMonth();

      result.setFullYear(result.getFullYear() + years);

      if (result.getMonth() !== month) {
        result.setDate(0);
      }

      return result;
    }

    function formatDate(date) {
      if (!date) return "Unable to calculate";

      return Utilities.formatDate(
        date,
        Session.getScriptTimeZone(),
        "dd MMMM yyyy"
      );
    }

    const promotionPeriods = {
      7: 3,
      8: 3,
      9: 3,
      10: 3,
      12: 3,
      13: 3,
      14: 3,
      15: 4,
      16: 4
    };

    const gradeMatch = String(data["GRADE LEVEL"] || "").match(/\d+/);
    const gradeNumber = gradeMatch ? Number(gradeMatch[0]) : null;

    const gradeDate = parseDate(
      data["DATE OF PRESENT APPOINTMENT/GRADE LEVEL"]
    );

    let expectedPromotion = "Unable to calculate";

    if (
      gradeNumber !== null &&
      gradeDate &&
      promotionPeriods[gradeNumber]
    ) {
      expectedPromotion = formatDate(
        addYears(gradeDate, promotionPeriods[gradeNumber])
      );
    }

    const dob = parseDate(data["DATE OF BIRTH"]);
    const firstAppointment = parseDate(
      data["DATE OF FIRST APPOINTMENT"]
    );

    let expectedRetirement = "Unable to calculate";

    if (dob && firstAppointment) {

      const retirementByAge = addYears(dob, 60);
      const retirementByService = addYears(firstAppointment, 35);

      expectedRetirement = formatDate(
        retirementByAge <= retirementByService
          ? retirementByAge
          : retirementByService
      );
    }

    const promotionColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "EXPECTED NEXT PROMOTION DATE";
    });

    if (promotionColumn !== -1) {
      row[promotionColumn] = expectedPromotion;
    }

    const retirementColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "EXPECTED RETIREMENT DATE";
    });

    if (retirementColumn !== -1) {
      row[retirementColumn] = expectedRetirement;
    }

    // CREATE A UNIQUE TOKEN FOR FUTURE INDIVIDUAL EDITING

    const editToken = Utilities.getUuid();
    row[tokenColumn] = editToken;

    // SAVE THE STAFF RECORD

    const newRowNumber = sheet.getLastRow() + 1;

    sheet.getRange(
      newRowNumber,
      1,
      1,
      row.length
    ).setValues([row]);

    SpreadsheetApp.flush();

    
    // SEND CONFIRMATION EMAIL

    const fullName =
      String(data["FULL NAME (SURNAME FIRST)"] || "Staff Member");

    
    const subject =
      "Staff Disposition Data Submission Confirmation";

    const webAppUrl = ScriptApp.getService().getUrl();

    const editUrl =
      webAppUrl + "?form=staff&token=" + encodeURIComponent(editToken);

    const editLinkColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "EDIT RESPONSE LINK";
    });
    if (editLinkColumn !== -1) {
      sheet.getRange(newRowNumber, editLinkColumn + 1).setValue(editUrl);
    }

    const body =
      "Dear " + fullName + ",\n\n" +
      "Your Staff Disposition information has been successfully submitted.\n\n" +
      "Oracle ID: " + oracleId + "\n" +
      "Expected Next Promotion Date: " + expectedPromotion + "\n" +
      "Expected Retirement Date: " + expectedRetirement + "\n\n" +
      "PERSONAL STAFF RECORD EDITING LINK:\n" +
      editUrl + "\n\n" +
      "You may use this personal link to review or update your information.\n" +
      "Please keep this link confidential and do not share it with others.\n\n" +
      "Lagos State Local Government Service Commission";

    const emailStatusColumn = headers.findIndex(function(header) {
  return String(header).trim().toUpperCase() === "EMAIL STATUS";
});

let emailSent = true;

// Initialise email tracking information
if (emailStatusColumn !== -1) {
  sheet.getRange(newRowNumber, emailStatusColumn + 1)
       .setValue("PENDING");
}

const retryCountColumn = headers.findIndex(function(header) {
  return String(header).trim().toUpperCase() === "EMAIL RETRY COUNT";
});

const lastAttemptColumn = headers.findIndex(function(header) {
  return String(header).trim().toUpperCase() === "EMAIL LAST ATTEMPT";
});

const lastErrorColumn = headers.findIndex(function(header) {
  return String(header).trim().toUpperCase() === "EMAIL LAST ERROR";
});

if (retryCountColumn !== -1) {
  sheet.getRange(newRowNumber, retryCountColumn + 1).setValue(0);
}

if (lastAttemptColumn !== -1) {
  sheet.getRange(newRowNumber, lastAttemptColumn + 1).setValue(new Date());
}

if (lastErrorColumn !== -1) {
  sheet.getRange(newRowNumber, lastErrorColumn + 1).clearContent();
}

try {
  // Record the actual email attempt time
  if (lastAttemptColumn !== -1) {
    sheet.getRange(newRowNumber, lastAttemptColumn + 1)
         .setValue(new Date());
  }

  MailApp.sendEmail({
    to: email,
    subject: subject,
    body: body,
    name: "Lagos State Local Government Service Commission"
  });

  // Email successfully submitted
  if (emailStatusColumn !== -1) {
    sheet.getRange(newRowNumber, emailStatusColumn + 1)
         .setValue("SENT");
  }

  if (lastErrorColumn !== -1) {
    sheet.getRange(newRowNumber, lastErrorColumn + 1)
         .clearContent();
  }

  Logger.log("Confirmation email submitted to: " + email);

} catch (emailError) {

  emailSent = false;

  // Mark email for retry
  if (emailStatusColumn !== -1) {
    sheet.getRange(newRowNumber, emailStatusColumn + 1)
         .setValue("FAILED");
  }

  if (lastErrorColumn !== -1) {
    sheet.getRange(newRowNumber, lastErrorColumn + 1)
         .setValue(String(emailError.message).substring(0, 500));
  }

  Logger.log("Confirmation email error: " + emailError.message);
}

  
    return {
      success: true,
      emailSent: emailSent,
      message: emailSent
        ? "Your information has been successfully submitted. A confirmation email has been sent."
        : "Your information has been successfully submitted, but the confirmation email could not be sent."
    };

  } catch (error) {

    Logger.log("Staff submission error: " + error.message);

    return {
      success: false,
      message: "Submission could not be completed. Please contact the administrator."
    };

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }
}

/****************************************************
 * AUTOMATIC STAFF CONFIRMATION EMAIL RETRY
 ****************************************************/

function retryFailedStaffConfirmationEmails() {

  const lock = LockService.getScriptLock();

  // Avoid overlapping with staff submissions or another retry run
  if (!lock.tryLock(1000)) {
    Logger.log("Retry skipped: another operation is running.");
    return;
  }

  try {

    const spreadsheetId =
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU";

    const ss = SpreadsheetApp.openById(spreadsheetId);
    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("The response worksheet was not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      Logger.log("No staff records found.");
      return;
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    function findColumn(name) {
      return headers.findIndex(function(header) {
        return String(header).trim().toUpperCase() === name;
      });
    }

    const statusCol = findColumn("EMAIL STATUS");
    const retryCol = findColumn("EMAIL RETRY COUNT");
    const attemptCol = findColumn("EMAIL LAST ATTEMPT");
    const errorCol = findColumn("EMAIL LAST ERROR");
    const emailCol = findColumn("EMAIL ADDRESS");
    const nameCol = findColumn("FULL NAME (SURNAME FIRST)");
    const oracleCol = findColumn("ORACLE ID");
    const promotionCol = findColumn("EXPECTED NEXT PROMOTION DATE");
    const retirementCol = findColumn("EXPECTED RETIREMENT DATE");
    const editLinkCol = findColumn("EDIT RESPONSE LINK");

    const requiredColumns = [
      statusCol, retryCol, attemptCol,
      errorCol, emailCol, nameCol,
      oracleCol, promotionCol, retirementCol,
      editLinkCol
    ];

    if (requiredColumns.some(function(col) {
      return col === -1;
    })) {
      throw new Error("One or more email tracking or staff columns are missing.");
    }

    const records = sheet.getRange(
      2, 1, lastRow - 1, lastColumn
    ).getDisplayValues();

    let sentCount = 0;
    let failedCount = 0;

    for (let i = 0; i < records.length; i++) {

      const rowNumber = i + 2;
      const record = records[i];

      const status = String(record[statusCol] || "")
        .trim().toUpperCase();

      if (status !== "PENDING" && status !== "FAILED") {
        continue;
      }

      let retryCount = Number(record[retryCol]) || 0;

      // Maximum of three retries after the initial attempt
      if (retryCount >= 3) {
        continue;
      }

      const email = String(record[emailCol] || "").trim();

      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        sheet.getRange(rowNumber, statusCol + 1).setValue("FAILED");
        sheet.getRange(rowNumber, errorCol + 1)
          .setValue("Invalid or missing email address.");
        failedCount++;
        continue;
      }

      // Avoid attempting to send when the daily quota is exhausted
      if (MailApp.getRemainingDailyQuota() <= 0) {
        Logger.log("Email quota exhausted. Remaining records will wait.");
        break;
      }

      const fullName = String(record[nameCol] || "Staff Member");
      const oracleId = String(record[oracleCol] || "");
      const expectedPromotion = String(record[promotionCol] || "");
      const expectedRetirement = String(record[retirementCol] || "");
      const editUrl = String(record[editLinkCol] || "");

      const subject =
        "Staff Disposition Data Submission Confirmation";

      const body =
        "Dear " + fullName + ",\n\n" +
        "Your Staff Disposition information has been successfully submitted.\n\n" +
        "Oracle ID: " + oracleId + "\n" +
        "Expected Next Promotion Date: " + expectedPromotion + "\n" +
        "Expected Retirement Date: " + expectedRetirement + "\n\n" +
        "PERSONAL STAFF RECORD EDITING LINK:\n" +
        editUrl + "\n\n" +
        "You may use this personal link to review or update your information.\n" +
        "Please keep this link confidential and do not share it with others.\n\n" +
        "Lagos State Local Government Service Commission";

      // Record the retry before attempting to send
      retryCount++;

      sheet.getRange(rowNumber, retryCol + 1).setValue(retryCount);
      sheet.getRange(rowNumber, attemptCol + 1).setValue(new Date());
      sheet.getRange(rowNumber, statusCol + 1).setValue("PENDING");
      sheet.getRange(rowNumber, errorCol + 1).clearContent();

      SpreadsheetApp.flush();

      try {

        MailApp.sendEmail({
          to: email,
          subject: subject,
          body: body,
          name: "Lagos State Local Government Service Commission"
        });

        sheet.getRange(rowNumber, statusCol + 1).setValue("SENT");
        sheet.getRange(rowNumber, errorCol + 1).clearContent();

        sentCount++;

        Logger.log("Retry successful for Oracle ID: " + oracleId);

      } catch (emailError) {

        sheet.getRange(rowNumber, statusCol + 1).setValue("FAILED");

        sheet.getRange(rowNumber, errorCol + 1)
          .setValue(String(emailError.message).substring(0, 500));

        failedCount++;

        Logger.log(
          "Retry failed for Oracle ID " +
          oracleId + ": " + emailError.message
        );
      }
    }

    SpreadsheetApp.flush();

    Logger.log("Email retry process completed.");
    Logger.log("Emails successfully sent: " + sentCount);
    Logger.log("Failed attempts: " + failedCount);

  } catch (error) {

    Logger.log("Email retry process error: " + error.message);
    throw error;

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }
  }
}

/****************************************************
 * SECURE STAFF RECORD RETRIEVAL FOR INDIVIDUAL EDITING
 ****************************************************/

function getStaffRecordForEditing(token) {

  const lock = LockService.getScriptLock();

  try {

    const editToken = String(token || "").trim();

    if (!editToken) {
      return {
        success: false,
        message: "Invalid editing link."
      };
    }

    lock.waitLock(30000);

    const spreadsheetId =
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU";

    const ss = SpreadsheetApp.openById(spreadsheetId);
    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Response worksheet not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      return {
        success: false,
        message: "No staff record was found."
      };
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const tokenColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "CUSTOM EDIT TOKEN";
    });

    if (tokenColumn === -1) {
      throw new Error("Editing token column not found.");
    }

    const tokens = sheet.getRange(
      2,
      tokenColumn + 1,
      lastRow - 1,
      1
    ).getDisplayValues();

    let matchingRow = -1;

    for (let i = 0; i < tokens.length; i++) {
      if (String(tokens[i][0]).trim() === editToken) {
        matchingRow = i + 2;
        break;
      }
    }

    if (matchingRow === -1) {
      return {
        success: false,
        message: "This editing link is invalid or no longer available."
      };
    }

    const values = sheet.getRange(
      matchingRow, 1, 1, lastColumn
    ).getValues()[0];

    const record = {};

    headers.forEach(function(header, index) {

      const fieldName = String(header).trim();

      if (
        !fieldName ||
        fieldName.toUpperCase() === "CUSTOM EDIT TOKEN"
      ) {
        return;
      }

      const value = values[index];

      if (value instanceof Date && !isNaN(value.getTime())) {
        record[fieldName] = Utilities.formatDate(
          value,
          Session.getScriptTimeZone(),
          "yyyy-MM-dd"
        );
      } else {
        record[fieldName] = value === null ? "" : String(value);
      }

    });

    return {
      success: true,
      data: record
    };

  } catch (error) {

    Logger.log("Record retrieval error: " + error.message);

    return {
      success: false,
      message: "Unable to retrieve this staff record."
    };

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }

}

/****************************************************
 * SECURE STAFF RECORD UPDATE
 * Updates the existing spreadsheet row.
 * Does not create a new submission.
 ****************************************************/

function updateStaffDisposition(token, data) {

  const lock = LockService.getScriptLock();

  try {

    lock.waitLock(30000);

    const editToken = String(token || "").trim();

    if (!editToken || !data || typeof data !== "object") {
      return {
        success: false,
        message: "Invalid editing request."
      };
    }

    const spreadsheetId =
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU";

    const ss = SpreadsheetApp.openById(spreadsheetId);
    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Response worksheet not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      return {
        success: false,
        message: "Staff record not found."
      };
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const tokenColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "CUSTOM EDIT TOKEN";
    });

    const oracleColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "ORACLE ID";
    });

    if (tokenColumn === -1 || oracleColumn === -1) {
      throw new Error("Required spreadsheet columns were not found.");
    }

    const tokenValues = sheet.getRange(
      2,
      tokenColumn + 1,
      lastRow - 1,
      1
    ).getDisplayValues();

    let rowNumber = -1;

    for (let i = 0; i < tokenValues.length; i++) {
      if (String(tokenValues[i][0]).trim() === editToken) {
        rowNumber = i + 2;
        break;
      }
    }

    if (rowNumber === -1) {
      return {
        success: false,
        message: "Invalid or expired editing link."
      };
    }

    const existingRow = sheet.getRange(
      rowNumber, 1, 1, lastColumn
    ).getValues()[0];

    
    const existingOracleId = String(
      existingRow[oracleColumn] || ""
    ).trim().toUpperCase();

    const submittedOracleId = String(
      data["ORACLE ID"] || ""
    ).trim().toUpperCase();

    if (!submittedOracleId) {
      return {
        success: false,
        message: "Oracle ID is required."
      };
    }

    // CHECK WHETHER THE NEW ORACLE ID BELONGS TO ANOTHER RECORD

    const allOracleIds = sheet.getRange(
      2,
      oracleColumn + 1,
      lastRow - 1,
      1
    ).getDisplayValues();

    for (let i = 0; i < allOracleIds.length; i++) {

      const checkedRow = i + 2;

      if (checkedRow === rowNumber) continue;

      const registeredId = String(
        allOracleIds[i][0] || ""
      ).trim().toUpperCase();

      if (registeredId === submittedOracleId) {
        return {
          success: false,
          duplicate: true,
          message: "This Oracle ID already belongs to another staff record."
        };
      }
    }

    const oracleIdChanged =
      submittedOracleId !== existingOracleId;

    // CHECK REQUIRED INFORMATION

    const requiredFields = [
      "ORACLE ID",
      "FULL NAME (SURNAME FIRST)",
      "GENDER",
      "COMMISSION FILE NUMBER",
      "DATE OF BIRTH",
      "POST OF FIRST APPOINTMENT/GRADE LEVEL",
      "DATE OF FIRST APPOINTMENT",
      "DATE OF PRESENT APPOINTMENT/GRADE LEVEL",
      "DATE DEPLOYED TO PRESENT LGA / LCDA",
      "CURRENT EMPLOYMENT STATUS",
      "PHONE NUMBER",
      "EMAIL ADDRESS",
      "POST OF PRESENT APPOINTMENT/GRADE LEVEL",
      "CADRE",
      "STATE OF ORIGIN",
      "GRADE LEVEL",
      "EDUCATIONAL QUALIFICATION",
      "PRESENT LGA / LCDA",
      "RESIDENTIAL ADDRESS",
      "LASHMA NUMBER"
    ];

    for (const field of requiredFields) {
      if (!String(data[field] || "").trim()) {
        return {
          success: false,
          message: "Please provide the required information: " + field
        };
      }
    }

    const email = String(data["EMAIL ADDRESS"] || "").trim();

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return {
        success: false,
        message: "Please provide a valid email address."
      };
    }

    // UPDATE ONLY THE STAFF INFORMATION FIELDS.
    // Preserve timestamp, edit links and custom token.

    const protectedColumns = [
      "TIMESTAMP",
      "EDIT RESPONSE LINK",
      "CUSTOM EDIT TOKEN",
      "EXPECTED NEXT PROMOTION DATE",
      "EXPECTED RETIREMENT DATE"
    ];

    const dateFields = [
      "DATE OF BIRTH",
      "DATE OF FIRST APPOINTMENT",
      "DATE OF CONFIRMATION",
      "DATE OF PRESENT APPOINTMENT/GRADE LEVEL",
      "DATE DEPLOYED TO PRESENT LGA / LCDA",
      "EXIT / RETIREMENT DATE (IF APPLICABLE)"
    ];

    Object.keys(data).forEach(function(key) {

      const column = headers.findIndex(function(header) {
        return String(header).trim().toUpperCase() ===
          key.trim().toUpperCase();
      });

      if (column === -1) return;

      if (protectedColumns.indexOf(
        String(headers[column]).trim().toUpperCase()
      ) !== -1) return;

      let value = data[key];

      if (dateFields.indexOf(key) !== -1 && value) {
        const dateMatch = String(value).match(
          /^(\d{4})-(\d{2})-(\d{2})$/
        );

        if (dateMatch) {
          value = new Date(
            Number(dateMatch[1]),
            Number(dateMatch[2]) - 1,
            Number(dateMatch[3])
          );
        }
      }

      existingRow[column] = value;

    });

    // RECALCULATE EXPECTED PROMOTION DATE

    function parseStaffDate(value) {

      if (!value) return null;

      if (value instanceof Date && !isNaN(value.getTime())) {
        return new Date(
          value.getFullYear(),
          value.getMonth(),
          value.getDate()
        );
      }

      const match = String(value).match(
        /^(\d{4})-(\d{2})-(\d{2})$/
      );

      if (match) {
        return new Date(
          Number(match[1]),
          Number(match[2]) - 1,
          Number(match[3])
        );
      }

      const date = new Date(value);

      return isNaN(date.getTime()) ? null :
        new Date(date.getFullYear(), date.getMonth(), date.getDate());
    }

    function addStaffYears(date, years) {

      const result = new Date(date);
      const originalMonth = result.getMonth();

      result.setFullYear(result.getFullYear() + years);

      if (result.getMonth() !== originalMonth) {
        result.setDate(0);
      }

      return result;
    }

    function formatStaffDate(date) {

      if (!date) return "Unable to calculate";

      return Utilities.formatDate(
        date,
        Session.getScriptTimeZone(),
        "dd MMMM yyyy"
      );
    }

    const promotionPeriods = {
      7: 3,
      8: 3,
      9: 3,
      10: 3,
      12: 3,
      13: 3,
      14: 3,
      15: 4,
      16: 4
    };

    const gradeMatch = String(
      data["GRADE LEVEL"] || ""
    ).match(/\d+/);

    const gradeNumber = gradeMatch
      ? Number(gradeMatch[0])
      : null;

    const gradeDate = parseStaffDate(
      data["DATE OF PRESENT APPOINTMENT/GRADE LEVEL"]
    );

    let expectedPromotion = "Unable to calculate";

    if (gradeDate && promotionPeriods[gradeNumber]) {
      expectedPromotion = formatStaffDate(
        addStaffYears(gradeDate, promotionPeriods[gradeNumber])
      );
    }

    const dob = parseStaffDate(data["DATE OF BIRTH"]);
    const firstAppointment = parseStaffDate(
      data["DATE OF FIRST APPOINTMENT"]
    );

    let expectedRetirement = "Unable to calculate";

    if (dob && firstAppointment) {

      const retirementByAge = addStaffYears(dob, 60);
      const retirementByService = addStaffYears(firstAppointment, 35);

      expectedRetirement = formatStaffDate(
        retirementByAge <= retirementByService
          ? retirementByAge
          : retirementByService
      );
    }

    const promotionColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "EXPECTED NEXT PROMOTION DATE";
    });

    if (promotionColumn !== -1) {
      existingRow[promotionColumn] = expectedPromotion;
    }

    const retirementColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() ===
        "EXPECTED RETIREMENT DATE";
    });

    if (retirementColumn !== -1) {
      existingRow[retirementColumn] = expectedRetirement;
    }

    // SAVE CHANGES TO THE SAME EXISTING ROW

    sheet.getRange(
      rowNumber, 1, 1, lastColumn
    ).setValues([existingRow]);

    SpreadsheetApp.flush();
    // RECORD ORACLE ID CORRECTION FOR ADMINISTRATIVE AUDIT

    if (oracleIdChanged) {

      let logSheet = ss.getSheetByName("Oracle ID Change Log");

      if (!logSheet) {
        logSheet = ss.insertSheet("Oracle ID Change Log");

        logSheet.appendRow([
          "DATE OF CHANGE",
          "PREVIOUS ORACLE ID",
          "NEW ORACLE ID",
          "STAFF NAME",
          "RESPONSE SHEET ROW"
        ]);
      }

      logSheet.appendRow([
        new Date(),
        existingOracleId,
        submittedOracleId,
        data["FULL NAME (SURNAME FIRST)"] || "",
        rowNumber
      ]);
    }


    // SEND CONFIRMATION EMAIL AFTER A SUCCESSFUL STAFF RECORD UPDATE
    const updatedFullName = String(
      data["FULL NAME (SURNAME FIRST)"] || "Staff Member"
    );
    const updatedEmail = String(data["EMAIL ADDRESS"] || "").trim();
    const updatedEditUrl =
      ScriptApp.getService().getUrl() + "?form=staff&token=" +
      encodeURIComponent(editToken);

    let updateEmailSent = true;

    try {
      MailApp.sendEmail({
        to: updatedEmail,
        subject: "Staff Disposition Information Update Confirmation",
        body:
          "Dear " + updatedFullName + ",\n\n" +
          "Your Staff Disposition information has been successfully updated.\n\n" +
          "Oracle ID: " + submittedOracleId + "\n" +
          "Expected Next Promotion Date: " + expectedPromotion + "\n" +
          "Expected Retirement Date: " + expectedRetirement + "\n\n" +
          "Your personal staff record editing link remains:\n" +
          updatedEditUrl + "\n\n" +
          "Please keep this link confidential and do not share it with others.\n\n" +
          "Lagos State Local Government Service Commission",
        name: "Lagos State Local Government Service Commission"
      });
    } catch (emailError) {
      updateEmailSent = false;
      Logger.log("Staff update confirmation email error: " + emailError.message);
    }

    return {
      success: true,
      emailSent: updateEmailSent,
      message: updateEmailSent
        ? "Your staff information has been updated successfully. A confirmation email has been sent."
        : "Your staff information has been updated successfully, but the confirmation email could not be sent."
    };

   } catch (error) {

    Logger.log("Staff update error: " + error.message);

    return {
      success: false,
      message: "Your information could not be updated. Please contact the administrator."
    };

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }

}

/****************************************************
 * ORACLE ID VERIFICATION FOR INDIVIDUAL EDITING
 * Allows the staff member to retain or correct their ID.
 ****************************************************/

function checkOracleIdForEditing(newOracleId, editToken) {

  const lock = LockService.getScriptLock();

  try {

    lock.waitLock(30000);

    newOracleId = String(newOracleId || "")
      .trim()
      .toUpperCase();

    editToken = String(editToken || "").trim();

    if (!newOracleId || !editToken) {
      return {
        available: false,
        message: "Oracle ID and editing token are required."
      };
    }

    const spreadsheetId =
      "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU";

    const ss = SpreadsheetApp.openById(spreadsheetId);
    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Response worksheet not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      return {
        available: false,
        message: "No staff records were found."
      };
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const oracleColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "ORACLE ID";
    });

    const tokenColumn = headers.findIndex(function(header) {
      return String(header).trim().toUpperCase() === "CUSTOM EDIT TOKEN";
    });

    if (oracleColumn === -1 || tokenColumn === -1) {
      throw new Error("Required columns were not found.");
    }

    const records = sheet.getRange(
      2, 1, lastRow - 1, lastColumn
    ).getDisplayValues();

    let ownRow = -1;

    // Identify the staff member's record using the private token.

    for (let i = 0; i < records.length; i++) {

      if (String(records[i][tokenColumn]).trim() === editToken) {
        ownRow = i;
        break;
      }

    }

    if (ownRow === -1) {
      return {
        available: false,
        message: "Invalid or expired editing link."
      };
    }

    // Check the proposed Oracle ID against every other record.

    for (let i = 0; i < records.length; i++) {

      if (i === ownRow) continue;

      const registeredId = String(
        records[i][oracleColumn] || ""
      ).trim().toUpperCase();

      if (registeredId === newOracleId) {
        return {
          available: false,
          exists: true,
          message: "This Oracle ID already belongs to another staff member."
        };
      }

    }

    return {
      available: true,
      exists: false,
      message: "Oracle ID is available for this staff record."
    };

  } catch (error) {

    Logger.log("Oracle ID editing verification error: " + error.message);

    return {
      available: false,
      message: "Oracle ID verification could not be completed. Please try again."
    };

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }

}
function testStaffConfirmationEmail() {

  const testEmail = "dam752002@gmail.com";

  Logger.log(
    "Remaining email quota: " +
    MailApp.getRemainingDailyQuota()
  );

  MailApp.sendEmail({
    to: testEmail,
    subject: "CMD/HR57 Portal - Email Delivery Test",
    body: "This is a test of the staff submission confirmation email service.",
    name: "Lagos State Local Government Service Commission"
  });

  Logger.log("Test email submitted to: " + testEmail);
}
function checkEmailQuota() {
  Logger.log(
    "Remaining email quota: " +
    MailApp.getRemainingDailyQuota()
  );
}
function checkEmailQuota() {
  const remaining = MailApp.getRemainingDailyQuota();

  Logger.log("Remaining email recipients today: " + remaining);

  return remaining;
}
function checkEmailAccountAndQuota() {
  const remaining = MailApp.getRemainingDailyQuota();
  Logger.log("Remaining email recipients today: " + remaining);
}
function testMailAppAuthorization() {
  MailApp.sendEmail({
    to: "dam752002@gmail.com",
    subject: "CMD/HR57 CONNECT PORTAL - Mail Test",
    body: "This is a test of Google Apps Script email authorization."
  });

  Logger.log("Test email sent successfully.");
}

function cleanDuplicateOracleIdsKeepLatest() {

  const lock = LockService.getScriptLock();

  try {
    lock.waitLock(30000);

    const ss = SpreadsheetApp.openById(
      HR_PORTAL_CONFIG.SPREADSHEET_ID
    );

    const sheet = ss.getSheetByName("Form Responses 1");

    if (!sheet) {
      throw new Error("Form Responses 1 sheet was not found.");
    }

    const lastRow = sheet.getLastRow();
    const lastColumn = sheet.getLastColumn();

    if (lastRow < 2) {
      Logger.log("No staff records available.");
      return;
    }

    const headers = sheet.getRange(
      1, 1, 1, lastColumn
    ).getDisplayValues()[0];

    const timestampColumn = headers.findIndex(h =>
      String(h).trim().toUpperCase() === "TIMESTAMP"
    );

    const oracleColumn = headers.findIndex(h =>
      String(h).trim().toUpperCase() === "ORACLE ID"
    );

    if (timestampColumn < 0 || oracleColumn < 0) {
      throw new Error("Timestamp or Oracle ID column not found.");
    }

    const data = sheet.getRange(
      2, 1, lastRow - 1, lastColumn
    ).getValues();

    const latestRecords = {};
    const rowsToDelete = [];

    data.forEach((row, index) => {

      const sheetRow = index + 2;

      const oracleId = String(row[oracleColumn] || "")
        .trim()
        .toUpperCase();

      // Preserve records without Oracle IDs.
      if (!oracleId) return;

      const timestamp = row[timestampColumn];
      const timeValue = timestamp instanceof Date
        ? timestamp.getTime()
        : Date.parse(String(timestamp));

      if (!Number.isFinite(timeValue)) {
        throw new Error(
          "Invalid timestamp found at row " + sheetRow +
          ". No records have been deleted."
        );
      }

      if (!latestRecords[oracleId]) {

        latestRecords[oracleId] = {
          row: sheetRow,
          time: timeValue
        };

      } else {

        const previous = latestRecords[oracleId];

        if (timeValue >= previous.time) {

          rowsToDelete.push(previous.row);

          latestRecords[oracleId] = {
            row: sheetRow,
            time: timeValue
          };

        } else {

          rowsToDelete.push(sheetRow);

        }
      }
    });

    if (rowsToDelete.length === 0) {
      Logger.log("No duplicate Oracle IDs found.");
      return;
    }

    // CREATE COMPLETE BACKUP BEFORE DELETION.

    const backup = sheet.copyTo(ss);

    const backupName =
      "STAFF BACKUP " +
      Utilities.formatDate(
        new Date(),
        ss.getSpreadsheetTimeZone(),
        "yyyyMMdd_HHmmss"
      );

    backup.setName(backupName);

    // DELETE DUPLICATE ROWS FROM BOTTOM TO TOP.

    rowsToDelete.sort((a, b) => b - a);

    let start = rowsToDelete[0];
    let count = 1;

    for (let i = 1; i < rowsToDelete.length; i++) {

      if (rowsToDelete[i] === start - 1) {

        start = rowsToDelete[i];
        count++;

      } else {

        sheet.deleteRows(start, count);

        start = rowsToDelete[i];
        count = 1;
      }
    }

    sheet.deleteRows(start, count);

    Logger.log("CLEANUP COMPLETED SUCCESSFULLY.");
    Logger.log("BACKUP WORKSHEET: " + backupName);
    Logger.log("DUPLICATE ROWS REMOVED: " + rowsToDelete.length);
    Logger.log("UNIQUE ORACLE IDs RETAINED: " +
      Object.keys(latestRecords).length);

  } finally {

    if (lock.hasLock()) {
      lock.releaseLock();
    }

  }
}
