
/****************************************************
 * LAGOS STATE LOCAL GOVERNMENT SERVICE COMMISSION
 * STAFF DISPOSITION DATA COLLECTION SYSTEM
 * HUMAN RESOURCE MANAGEMENT PORTAL
 *
 * FIREBASE AUTHENTICATION AND ACCESS MANAGEMENT
 ****************************************************/

const HR_PORTAL_CONFIG = {
  SPREADSHEET_ID: "1APFoMW8HdxNW_qQcQCJpKZ6t1NqJlXiqxRvFl7CJMaU",
  STAFF_SHEET: "Form Responses 1",
  ACCESS_SHEET: "HR USER ACCESS",
  DASHBOARD_SHEET: "MANAGEMENT DASHBOARD",
  PORTAL_SHEET: "HR OFFICERS PORTAL",
  AUDIT_SHEET: "HR AUDIT LOG"
};


/****************************************************
 * FIREBASE USER VERIFICATION
 ****************************************************/

function verifyFirebaseUser_(idToken) {

  if (!idToken) {
    throw new Error("Please sign in to continue.");
  }

  const apiKey = PropertiesService
    .getScriptProperties()
    .getProperty("FIREBASE_WEB_API_KEY");

  if (!apiKey) {
    throw new Error("Firebase API key is not configured.");
  }

  const url =
    "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=" +
    encodeURIComponent(apiKey);

  let response;

  try {
    response = UrlFetchApp.fetch(url, {
      method: "post",
      contentType: "application/json",
      payload: JSON.stringify({
        idToken: idToken
      }),
      muteHttpExceptions: true
    });

  } catch (error) {
    console.error("Firebase connection error: " + error.message);
    throw new Error("Unable to connect to Firebase. Check the execution log.");
  }

  const statusCode = response.getResponseCode();
  const responseText = response.getContentText();

  let responseData;

  try {
    responseData = JSON.parse(responseText);
  } catch (error) {
    console.error(
      "Firebase returned an invalid response. HTTP status: " +
      statusCode + ". Response: " + responseText
    );
    throw new Error("Firebase returned an invalid response.");
  }

  if (statusCode !== 200) {
    console.error(
      "Firebase verification HTTP " + statusCode +
      ": " + responseText
    );

    throw new Error(
      "Firebase verification failed. HTTP status: " + statusCode
    );
  }

  if (!responseData.users || responseData.users.length === 0) {
    throw new Error(
      "Your Firebase session is invalid or has expired. Please sign in again."
    );
  }

  const firebaseUser = responseData.users[0];

  if (firebaseUser.disabled === true) {
    throw new Error("Your Firebase account has been disabled.");
  }

  if (firebaseUser.emailVerified !== true) {
    throw new Error("Please verify your email address before accessing the portal.");
  }

  const userEmail = String(firebaseUser.email || "")
    .trim()
    .toLowerCase();

  if (!userEmail) {
    throw new Error("Your Firebase account has no registered email address.");
  }

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

  const accessSheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.ACCESS_SHEET
  );

  if (!accessSheet) {
    throw new Error("HR USER ACCESS sheet was not found.");
  }

  const records = accessSheet.getDataRange().getValues();

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

    const registeredEmail = String(records[i][1] || "")
      .trim()
      .toLowerCase();

    const accessLevel = String(records[i][2] || "")
      .trim()
      .toUpperCase();

    const accountStatus = String(records[i][4] || "")
      .trim()
      .toUpperCase();

    if (registeredEmail === userEmail) {

      if (accountStatus !== "ACTIVE") {
        throw new Error(
          "Your portal account is not active. Please contact the ICT Administrator."
        );
      }

      const permittedRoles = [
  "MANAGEMENT",
  "HR OFFICER",
  "ICT ADMINISTRATOR",
  "CMD STAFF"
];

      if (!permittedRoles.includes(accessLevel)) {
        throw new Error("Your portal access role is not recognised.");
      }

      return {
        authorised: true,
        email: userEmail,
        name: records[i][0],
        accessLevel: accessLevel,
        assignedDepartment: records[i][3]
      };
    }
  }

  throw new Error(
    "Your Firebase email is not registered in the HR USER ACCESS sheet."
  );
}

/****************************************************
 * GET AUTHORISED PORTAL USER INFORMATION
 ****************************************************/

function getPortalUserInfo(idToken) {

  // Reuse existing Firebase and portal access verification.
  const user = verifyFirebaseUser_(idToken);

  // Return only the information required by the frontend.
  return {
    authorised: true,
    email: user.email,
    name: user.name,
    accessLevel: user.accessLevel
  };
}


/****************************************************
 * CHECK USER ACCESS PERMISSIONS
 ****************************************************/

function checkHRPermission_(requiredRole, idToken) {

  const user = verifyFirebaseUser_(idToken);

  const permissions = {
    MANAGEMENT: [
      "VIEW_DASHBOARD"
    ],

    "HR OFFICER": [
      "VIEW_STAFF_RECORDS"
    ],

    "ICT ADMINISTRATOR": [
      "MANAGE_USERS",
      "VIEW_AUDIT_LOGS",
      "SYSTEM_ADMINISTRATION"
    ]
  };

  const allowedPermissions =
    permissions[user.accessLevel] || [];

  if (!allowedPermissions.includes(requiredRole)) {
    throw new Error(
      "Access denied. You do not have permission to perform this action."
    );
  }

  return true;
}


/****************************************************
 * RECORD HR PORTAL ACTIVITIES
 ****************************************************/

function recordHRAudit_(action, oracleID, details, result, idToken) {

  const user = verifyFirebaseUser_(idToken);

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

  const auditSheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.AUDIT_SHEET
  );

  if (!auditSheet) {
    throw new Error("HR AUDIT LOG sheet was not found.");
  }

  auditSheet.appendRow([
    new Date(),
    user.email,
    user.accessLevel,
    action,
    oracleID || "",
    details || "",
    result || ""
  ]);

}

/****************************************************
 * EXPECTED PROMOTION DATE CALCULATION
 ****************************************************/

function calculateExpectedPromotionDate_(gradeValue, presentGradeDate) {

  const grade = parseInt(
    String(gradeValue || "").replace(/\D/g, ""),
    10
  );

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

  if (grade === 17) {
    return "Maximum Grade Level Attained";
  }

  if (!Object.prototype.hasOwnProperty.call(promotionYears, grade)) {
    return null;
  }

  if (!presentGradeDate) {
    return null;
  }

  const timeZone = Session.getScriptTimeZone();

  const dateParts = Utilities.formatDate(
    new Date(presentGradeDate),
    timeZone,
    "yyyy-MM-dd"
  ).split("-").map(Number);

  const year = dateParts[0];
  const month = dateParts[1];
  const day = dateParts[2];

  if (!year || !month || !day) {
    return null;
  }

  const eligibilityYear = year + promotionYears[grade];

  
  // January 1: January promotion cycle
  if (month === 1 && day === 1) {
    return new Date(eligibilityYear, 0, 1);
  }

  // January 2 to June 30: July promotion cycle
  if (
    (month === 1 && day >= 2) ||
    (month >= 2 && month <= 6)
  ) {
    return new Date(eligibilityYear, 6, 1);
  }

  // July 1: July promotion cycle
  if (month === 7 && day === 1) {
    return new Date(eligibilityYear, 6, 1);
  }

  // July 2 to December 31: January promotion cycle
  return new Date(eligibilityYear + 1, 0, 1);
  }

/****************************************************
 * VALIDATE PRESENT GRADE APPOINTMENT DATE
 ****************************************************/

function validatePresentGradeAppointment_(
  firstAppointmentDate,
  presentGradeDate
) {

  if (!firstAppointmentDate || !presentGradeDate) {
    return {
      status: "HR VERIFICATION REQUIRED",
      message: "Appointment date information is incomplete."
    };
  }

  const timeZone = Session.getScriptTimeZone();

  function getDateParts(value) {
    return Utilities.formatDate(
      new Date(value),
      timeZone,
      "yyyy-MM-dd"
    ).split("-").map(Number);
  }

  const firstDate = getDateParts(firstAppointmentDate);
  const presentDate = getDateParts(presentGradeDate);

  const firstMonth = firstDate[1];
  const firstDay = firstDate[2];

  let expectedCycleMonth;
  let expectedCycleDay;

  if (firstMonth === 1 && firstDay === 1) {
    expectedCycleMonth = 1;
    expectedCycleDay = 1;
  } else if (
    (firstMonth === 1 && firstDay >= 2) ||
    (firstMonth >= 2 && firstMonth <= 6) ||
    (firstMonth === 7 && firstDay === 1)
  ) {
    expectedCycleMonth = 7;
    expectedCycleDay = 1;
  } else {
    expectedCycleMonth = 1;
    expectedCycleDay = 1;
  }

  const matchesCycle =
    presentDate[1] === expectedCycleMonth &&
    presentDate[2] === expectedCycleDay;

  return {
    status: matchesCycle
      ? "VERIFIED"
      : "HR VERIFICATION REQUIRED",

    message: matchesCycle
      ? "Present grade appointment date matches the promotion cycle."
      : "Please verify the present grade appointment date against the staff promotion history."
  };
}


/****************************************************
 * STAFF SEARCH BY ORACLE ID
 * Returns approved personnel fields only.
 ****************************************************/

function searchStaffByOracleID(oracleID, idToken) {

  const user = verifyFirebaseUser_(idToken);

  if (
  user.accessLevel !== "MANAGEMENT" &&
  user.accessLevel !== "HR OFFICER" &&
  user.accessLevel !== "ICT ADMINISTRATOR" &&
  user.accessLevel !== "CMD STAFF"
) {
  throw new Error("Access denied.");
}

  const searchID = String(oracleID || "").trim();

  if (!searchID) {
    throw new Error("Please enter an Oracle ID.");
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!sheet) {
    throw new Error("Staff database not found.");
  }

  const records = sheet.getDataRange().getValues();

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

  const headers = records[0];

  const findColumn = name => headers.findIndex(header =>
    String(header)
      .trim()
      .replace(/\s+/g, " ")
      .toUpperCase() ===
    name.trim().replace(/\s+/g, " ").toUpperCase()
  );

  const columns = {
    oracleID: findColumn("ORACLE ID"),
    fullName: findColumn("FULL NAME (SURNAME FIRST)"),
    staffNumber: findColumn("COMMISSION FILE NUMBER"),
    dob: findColumn("DATE OF BIRTH"),

    firstPost: findColumn("POST OF FIRST APPOINTMENT/GRADE LEVEL"),
    firstAppointment: findColumn("DATE OF FIRST APPOINTMENT"),
    confirmationDate: findColumn("DATE OF CONFIRMATION"),
    presentGradeDate: findColumn(
  "DATE OF PRESENT APPOINTMENT/GRADE LEVEL"
),

    deploymentDate: findColumn(
      "DATE DEPLOYED TO PRESENT LGA / LCDA"
    ),
    professionalQualification: findColumn(
      "PROFESSIONAL QUALIFICATION"
    ),

    phoneNumber: findColumn("PHONE NUMBER"),

    // Column O: staff-provided email address.
    staffEmail: 14,

    designation: findColumn("POST OF PRESENT APPOINTMENT"),
    cadre: findColumn("CADRE"),
    stateOrigin: findColumn("STATE OF ORIGIN"),
    grade: findColumn("GRADE LEVEL"),
    lga: findColumn("PRESENT LGA / LCDA"),
    gender: findColumn("GENDER"),
    qualification: findColumn("EDUCATIONAL QUALIFICATION"),

    employmentStatus: headers.findIndex(header => {
      const title = String(header)
        .trim()
        .replace(/\s+/g, " ")
        .toUpperCase();

      return [
        "CURRENT EMPLOYMENT STATUS",
        "EMPLOYMENT STATUS"
      ].includes(title);
    }),

    nextPromotion: findColumn("EXPECTED NEXT PROMOTION DATE"),
expectedRetirement: findColumn("EXPECTED RETIREMENT DATE"),

hrVerifiedPresentGradeDate: findColumn(
  "HR VERIFIED PRESENT GRADE DATE"
),

hrVerificationRemarks: findColumn(
  "HR VERIFICATION REMARKS"
)
};
  for (const [field, index] of Object.entries(columns)) {

    if (index === -1 && !["gender", "qualification"].includes(field)) {
      throw new Error(
        "Required staff database column not found: " + field
      );
    }
  }

  const timeZone = ss.getSpreadsheetTimeZone();

  const formatDate = value => {

    if (!value) return "";

    if (value instanceof Date) {
      return Utilities.formatDate(
        value,
        timeZone,
        "dd MMMM yyyy"
      );
    }

    return value;
  };

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

    if (
      String(records[i][columns.oracleID]).trim() === searchID
    ) {

      const normalizeLocation = value =>
        String(value || "")
          .replace(/[\u00A0\u200B\uFEFF]/g, " ")
          .replace(/\s+/g, " ")
          .trim()
          .toUpperCase()
          .replace(/\s+(LGA|LCDA)$/i, "");

      const staffLGA = normalizeLocation(
        records[i][columns.lga]
      );

      const assignedLGA = normalizeLocation(
        user.assignedDepartment
      );

      console.log("LOCATION CHECK: " + JSON.stringify({
        oracleID: searchID,
        staffLocation: staffLGA,
        officerLocation: assignedLGA,
        match: staffLGA === assignedLGA
      }));

      if (
  user.accessLevel === "HR OFFICER" &&
  (
    !staffLGA ||
    !assignedLGA ||
    staffLGA !== assignedLGA
  )
) {

  recordHRAudit_(
    "STAFF RECORD SEARCH",
    searchID,
    "Record outside assigned LGA/LCDA scope or location information is missing.",
    "ACCESS DENIED",
    idToken
  );

  throw new Error(
    "You are not authorised to view this staff record."
  );
}

      const staff = records[i];
      const hrVerifiedDate =
  staff[columns.hrVerifiedPresentGradeDate];

const promotionCalculationDate =
  hrVerifiedDate || staff[columns.presentGradeDate];
      const appointmentValidation =
  validatePresentGradeAppointment_(
    staff[columns.firstAppointment],
    staff[columns.presentGradeDate]
  );

      const result = {

        oracleID: staff[columns.oracleID],
        fullName: staff[columns.fullName],
        staffNumber: staff[columns.staffNumber],
        dateOfBirth: formatDate(staff[columns.dob]),

        firstPost: staff[columns.firstPost],
        firstAppointment: formatDate(
          staff[columns.firstAppointment]
        ),
        confirmationDate: formatDate(
          staff[columns.confirmationDate]
        ),
        presentGradeDate: formatDate(
          staff[columns.presentGradeDate]
        ),
        hrVerifiedPresentGradeDate: formatDate(
  staff[columns.hrVerifiedPresentGradeDate]
),

hrVerificationRemarks:
  staff[columns.hrVerificationRemarks] || "",
        appointmentVerificationStatus:
  appointmentValidation.status,

appointmentVerificationMessage:
  appointmentValidation.message,

        deploymentDate: formatDate(
          staff[columns.deploymentDate]
        ),

        professionalQualification:
          staff[columns.professionalQualification],

        phoneNumber: staff[columns.phoneNumber],
        emailAddress: staff[columns.staffEmail],

        designation: staff[columns.designation],
        cadre: staff[columns.cadre],
        stateOrigin: staff[columns.stateOrigin],
        gradeLevel: staff[columns.grade],

        gender: columns.gender >= 0
          ? staff[columns.gender]
          : "",

        qualification: columns.qualification >= 0
          ? staff[columns.qualification]
          : "",

        presentLGA: staff[columns.lga],
        employmentStatus: staff[columns.employmentStatus],

        nextPromotion: (function() {

  const calculatedDate = calculateExpectedPromotionDate_(
  staff[columns.grade],
  promotionCalculationDate
);
  if (calculatedDate !== null) {
    return typeof calculatedDate === "string"
      ? calculatedDate
      : formatDate(calculatedDate);
  }

  return formatDate(staff[columns.nextPromotion]);

})(),

        expectedRetirement: formatDate(
          staff[columns.expectedRetirement]
        )
      };

      recordHRAudit_(
        "STAFF RECORD SEARCH",
        searchID,
        "Approved personnel fields retrieved.",
        "SUCCESS",
        idToken
      );

      return {
        found: true,
        staffRecord: result
      };
    }
  }

  recordHRAudit_(
    "STAFF RECORD SEARCH",
    searchID,
    "No matching record found.",
    "NOT FOUND",
    idToken
  );

  return {
    found: false,
    message: "No matching staff record found."
  };
}

/****************************************************
 * HR VERIFICATION OF PRESENT GRADE APPOINTMENT DATE
 ****************************************************/

function saveHRVerifiedAppointmentDate(
  oracleID,
  verifiedDate,
  remarks,
  idToken
) {

  const user = verifyFirebaseUser_(idToken);

 if (
  user.accessLevel !== "HR OFFICER" &&
  user.accessLevel !== "MANAGEMENT"
) {
  throw new Error(
    "Access denied. Only authorised Management and HR Officers can verify appointment dates."
  );
}
  const searchID = String(oracleID || "").trim();

  if (!searchID || !verifiedDate) {
    throw new Error("Oracle ID and verified appointment date are required.");
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!sheet) {
    throw new Error("Staff database not found.");
  }

  const records = sheet.getDataRange().getValues();
  const headers = records[0];

  const findColumn = name => headers.findIndex(header =>
    String(header).trim().replace(/\s+/g, " ").toUpperCase() ===
    name.toUpperCase()
  );

  const oracleCol = findColumn("ORACLE ID");
  const locationCol = findColumn("PRESENT LGA / LCDA");
  const verifiedDateCol = findColumn("HR VERIFIED PRESENT GRADE DATE");
  const remarksCol = findColumn("HR VERIFICATION REMARKS");

  if (
    oracleCol === -1 ||
    locationCol === -1 ||
    verifiedDateCol === -1 ||
    remarksCol === -1
  ) {
    throw new Error("One or more required HR verification columns are missing.");
  }

  const normalizeLocation = value =>
    String(value || "")
      .replace(/[\u00A0\u200B\uFEFF]/g, " ")
      .replace(/\s+/g, " ")
      .trim()
      .toUpperCase()
      .replace(/\s+(LGA|LCDA)$/i, "");

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

    if (String(records[i][oracleCol]).trim() === searchID) {

      const staffLocation = normalizeLocation(
        records[i][locationCol]
      );

      const assignedLocation = normalizeLocation(
        user.assignedDepartment
      );

      if (
  user.accessLevel === "HR OFFICER" &&
  (
    !staffLocation ||
    !assignedLocation ||
    staffLocation !== assignedLocation
  )
) {
        throw new Error(
          "You are not authorised to verify this staff record."
        );
      }

      const dateText = String(verifiedDate || "").trim();

if (!/^\d{4}-\d{2}-\d{2}$/.test(dateText)) {
  throw new Error("Invalid verified appointment date.");
}

const spreadsheetTimeZone = ss.getSpreadsheetTimeZone();
const date = Utilities.parseDate(
  dateText,
  spreadsheetTimeZone,
  "yyyy-MM-dd"
);

if (
  Utilities.formatDate(date, spreadsheetTimeZone, "yyyy-MM-dd") !== dateText
) {
  throw new Error("Invalid verified appointment date.");
}

      if (isNaN(date.getTime())) {
        throw new Error("Invalid verified appointment date.");
      }

      sheet.getRange(i + 1, verifiedDateCol + 1)
        .setValue(date);

      sheet.getRange(i + 1, remarksCol + 1)
        .setValue(String(remarks || "").trim());

      recordHRAudit_(
        "HR APPOINTMENT DATE VERIFICATION",
        searchID,
        "Verified date: " +
          Utilities.formatDate(
            date,
            ss.getSpreadsheetTimeZone(),
            "dd MMMM yyyy"
          ) +
          "; Remarks: " + String(remarks || "").trim(),
        "SUCCESS",
        idToken
      );

      return {
        success: true,
        message: "HR verification saved successfully."
      };
    }
  }

  throw new Error("Staff record not found.");
}

/****************************************************
 * WEB APP ENTRY POINT
 ****************************************************/



function doGet(e) {

  const params = e && e.parameter ? e.parameter : {};

  // OPEN STAFF DISPOSITION FORM
  if (params.form === "staff") {

    const staffTemplate =
      HtmlService.createTemplateFromFile("StaffForm");

    staffTemplate.editToken = params.token || "";

    return staffTemplate.evaluate()
      .setTitle("Lagos State Staff Disposition Data Collection")
      .setXFrameOptionsMode(
        HtmlService.XFrameOptionsMode.ALLOWALL
      );
  }

  // OPEN EXISTING HR OFFICERS' PORTAL
  const portalTemplate =
    HtmlService.createTemplateFromFile("Index");

  portalTemplate.invitationToken = params.token || "";

  return portalTemplate.evaluate()
    .setTitle("LGSCHR57 CONNECT PORTAL | Staff Disposition System")
    .setXFrameOptionsMode(
      HtmlService.XFrameOptionsMode.DEFAULT
    );

}


/****************************************************
 * INVITATION-BASED PORTAL REGISTRATION
 ****************************************************/

const HR_INVITATION_CONFIG = {
  SHEET_NAME: "HR PORTAL INVITATIONS",
  VALID_HOURS: 48,
  HEADERS: [
    "Token Hash", "Full Name", "Email Address", "Access Level",
    "Assigned Department", "Created At", "Expires At", "Status",
    "Created By", "Completed At"
  ]
};

function getInvitationSheet_() {
  const ss = SpreadsheetApp.openById(HR_PORTAL_CONFIG.SPREADSHEET_ID);
  let sheet = ss.getSheetByName(HR_INVITATION_CONFIG.SHEET_NAME);

  if (!sheet) {
    sheet = ss.insertSheet(HR_INVITATION_CONFIG.SHEET_NAME);
    sheet.getRange(1, 1, 1, HR_INVITATION_CONFIG.HEADERS.length)
      .setValues([HR_INVITATION_CONFIG.HEADERS]);
    sheet.setFrozenRows(1);
  } else if (sheet.getLastRow() === 0) {
    sheet.getRange(1, 1, 1, HR_INVITATION_CONFIG.HEADERS.length)
      .setValues([HR_INVITATION_CONFIG.HEADERS]);
    sheet.setFrozenRows(1);
  }

  return sheet;
}

function hashInvitationToken_(token) {
  const digest = Utilities.computeDigest(
    Utilities.DigestAlgorithm.SHA_256,
    String(token),
    Utilities.Charset.UTF_8
  );

  return digest.map(function(byte) {
    return ("0" + ((byte + 256) % 256).toString(16)).slice(-2);
  }).join("");
}

function findApprovedPortalUser_(email) {
  const ss = SpreadsheetApp.openById(HR_PORTAL_CONFIG.SPREADSHEET_ID);
  const sheet = ss.getSheetByName(HR_PORTAL_CONFIG.ACCESS_SHEET);

  if (!sheet) throw new Error("HR USER ACCESS sheet was not found.");

  const rows = sheet.getDataRange().getValues();
  const normalizedEmail = String(email).trim().toLowerCase();

  for (let r = 1; r < rows.length; r++) {
    if (String(rows[r][1] || "").trim().toLowerCase() === normalizedEmail) {
      return {
        row: r + 1,
        name: String(rows[r][0] || "").trim(),
        email: normalizedEmail,
        role: String(rows[r][2] || "").trim().toUpperCase(),
        department: String(rows[r][3] || "").trim(),
        status: String(rows[r][4] || "").trim().toUpperCase()
      };
    }
  }

  return null;
}


function getInvitationDetails(invitationToken) {
  const token = String(invitationToken || "").trim();

  console.log("INVITATION CHECK - Token received: " + (token ? "YES" : "NO"));
  console.log("INVITATION CHECK - Token length: " + token.length);

  if (!token || token.length < 30 || token.length > 300) {
    console.log("INVITATION CHECK - Invalid token length");
    return { valid: false };
  }

  const sheet = getInvitationSheet_();
  const rows = sheet.getDataRange().getValues();

  console.log("INVITATION CHECK - Spreadsheet rows: " + rows.length);

  const tokenHash = hashInvitationToken_(token);
    console.log("WEB APP HASH PREFIX: " + tokenHash.substring(0, 8));
    
    console.log("LATEST STORED HASH PREFIX: " +
  String(rows[rows.length - 1][0] || "").trim().substring(0, 8));

console.log("LATEST STORED HASH LENGTH: " +
  String(rows[rows.length - 1][0] || "").trim().length);

let matchingHashFound = false;

for (let i = 1; i < rows.length; i++) {
  if (String(rows[i][0] || "").trim() === tokenHash) {
    matchingHashFound = true;
    console.log("MATCHING HASH ROW: " + (i + 1));
    break;
  }
}

console.log("HASH MATCH FOUND: " + matchingHashFound);
  const now = new Date();

  for (let r = 1; r < rows.length; r++) {
    if (
  String(rows[r][0] || "").trim().toLowerCase() !==
  tokenHash.trim().toLowerCase()
) continue;
    console.log("INVITATION CHECK - MATCH FOUND");

    const expiresAt = rows[r][6] instanceof Date
      ? rows[r][6]
      : new Date(rows[r][6]);

    const status = String(rows[r][7] || "").trim().toUpperCase();

    console.log("INVITATION CHECK - Status: " + status);
    console.log("INVITATION CHECK - Expiry valid: " +
      (!isNaN(expiresAt.getTime()) && now <= expiresAt));

    if (status !== "PENDING" || isNaN(expiresAt.getTime()) || now > expiresAt) {
      return { valid: false };
    }

    return {
      valid: true,
      email: String(rows[r][2] || "").trim().toLowerCase()
    };
  }

  console.log("INVITATION CHECK - NO MATCH FOUND");
  return { valid: false };
}
function createPortalInvitation(name, email, role, department, idToken) {
  const admin = verifyFirebaseUser_(idToken);

  if (admin.accessLevel !== "ICT ADMINISTRATOR") {
    throw new Error("Only the ICT Administrator can issue portal invitations.");
  }

  const fullName = String(name || "").trim();
  const normalizedEmail = String(email || "").trim().toLowerCase();
  const selectedRole = String(role || "").trim().toUpperCase();
  const assignedDepartment = String(department || "").trim();

  if (!fullName) throw new Error("Enter the approved user's full name.");
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) {
    throw new Error("Enter a valid email address.");
  }

  
const permittedRoles = [
  "MANAGEMENT",
  "HR OFFICER",
  "ICT ADMINISTRATOR",
  "CMD STAFF"
];

if (!permittedRoles.includes(selectedRole)) {
  throw new Error("Select a valid portal access level.");
}

if (selectedRole === "HR OFFICER" && !assignedDepartment) {
  throw new Error("An HR Officer must have an assigned LGA or LCDA.");
}

// The access row must be approved and active before an invitation is issued.
const approvedUser = findApprovedPortalUser_(normalizedEmail);

if (!approvedUser) {
  throw new Error("This email is not yet listed in HR USER ACCESS. Add and approve the user there first.");
}

if (approvedUser.status !== "ACTIVE") {
  throw new Error("The user's HR USER ACCESS account must be ACTIVE before an invitation is issued.");
}

// Confirm that the approved role matches the selected role.
if (approvedUser.role !== selectedRole) {
  throw new Error(
    "The selected access role does not match the approved HR USER ACCESS record."
  );
}

// Department validation applies only to HR Officers.
if (
  selectedRole === "HR OFFICER" &&
  String(approvedUser.department || "").trim().toLowerCase() !==
    assignedDepartment.toLowerCase()
) {
  throw new Error(
    "The assigned LGA/LCDA does not match the approved HR USER ACCESS record."
  );
}

// Confirm that the name matches the approved record.
if (String(approvedUser.name || "").trim().toLowerCase() !== fullName.toLowerCase()) {
  throw new Error("The name does not match the approved HR USER ACCESS record.");
}

  const deploymentUrl = "https://script.google.com/macros/s/AKfycbwhHB3JX_eQdMui0-XNmBtxyuHlMHlthd7mulI1o6Rhe8gL_rQ__vpQF0r16lWySp56gg/exec";

  const token = Utilities.getUuid().replace(/-/g, "") +
    Utilities.getUuid().replace(/-/g, "") +
    Utilities.getUuid().replace(/-/g, "");
  const tokenHash = hashInvitationToken_(token);
  const now = new Date();
  const expiry = new Date(now.getTime() + HR_INVITATION_CONFIG.VALID_HOURS * 60 * 60 * 1000);
  const invitationUrl = deploymentUrl + "?token=" + encodeURIComponent(token);
  const sheet = getInvitationSheet_();

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

  try {
    const rows = sheet.getDataRange().getValues();

    // Revoke earlier unused invitations for the same email.
    for (let r = 1; r < rows.length; r++) {
      if (
        String(rows[r][2] || "").trim().toLowerCase() === normalizedEmail &&
        String(rows[r][7] || "").trim().toUpperCase() === "PENDING"
      ) {
        sheet.getRange(r + 1, 8).setValue("REVOKED");
      }
    }

    sheet.appendRow([
      tokenHash, fullName, normalizedEmail, selectedRole,
      selectedRole === "HR OFFICER" ? assignedDepartment : "",
      now, expiry, "PENDING", admin.email, ""
    ]);
  } finally {
    lock.releaseLock();
  }

  const subject = "Invitation to register for CMD/HR57 CONNECT PORTAL";
  const body =
    "Dear " + fullName + ",\n\n" +
    "You have been invited to create an account on the CMD/HR57 CONNECT PORTAL.\n\n" +
    "Please open the link below to create your password and complete registration:\n" +
    invitationUrl + "\n\n" +
    "This invitation expires in 48 hours and can be used only once. " +
    "After creating your account, verify your email address before signing in.\n\n" +
    "If you were not expecting this invitation, please contact the ICT Administrator.\n\n" +
    "Regards,\nCMD/HR57 CONNECT PORTAL";

  try {
    MailApp.sendEmail({
      to: normalizedEmail,
      subject: subject,
      body: body,
      name: "CMD/HR57 CONNECT PORTAL"
    });
  
  
  } catch (mailError) {
    console.error(
  "MAILAPP SEND ERROR:",
  mailError && mailError.message,
  mailError
);

    const rows = sheet.getDataRange().getValues();

    for (let r = rows.length - 1; r >= 1; r--) {

      if (
        String(rows[r][0] || "").trim().toLowerCase() !==
        tokenHash.trim().toLowerCase()
      ) {
        continue;
      }

      sheet.getRange(r + 1, 8).setValue("EMAIL_FAILED");
      break;
    }

    throw new Error(
      "The invitation record was created, but the email could not be sent. Check MailApp authorization and try again."
    );
  }

  return {
    success: true,
    message: "Invitation email sent successfully."
  };
}



function completePortalInvitation(invitationToken, idToken) {
  const token = String(invitationToken || "").trim();
  if (!token) throw new Error("The invitation token is missing.");

  // This also confirms that the Firebase account exists, is enabled,
  // has a verified email, and is present in the active access register.
  const user = verifyFirebaseUser_(idToken);
  const tokenHash = hashInvitationToken_(token);
  const sheet = getInvitationSheet_();
  const lock = LockService.getScriptLock();

  lock.waitLock(30000);
  try {
    const rows = sheet.getDataRange().getValues();
    const now = new Date();

    for (let r = 1; r < rows.length; r++) {
      if (String(rows[r][0] || "") !== tokenHash) continue;

      const inviteEmail = String(rows[r][2] || "").trim().toLowerCase();
      const status = String(rows[r][7] || "").trim().toUpperCase();
      const expiry = rows[r][6] instanceof Date ? rows[r][6] : new Date(rows[r][6]);

      if (status !== "PENDING") {
        throw new Error("This invitation has already been used or is no longer valid.");
      }
      if (isNaN(expiry.getTime()) || now > expiry) {
        sheet.getRange(r + 1, 8).setValue("EXPIRED");
        throw new Error("This invitation has expired. Please request a new invitation.");
      }
      if (user.email !== inviteEmail) {
        throw new Error("The signed-in email does not match the email address this invitation was issued to.");
      }

      const approvedUser = findApprovedPortalUser_(inviteEmail);
      if (
        !approvedUser ||
        approvedUser.status !== "ACTIVE" ||
        approvedUser.role !== String(rows[r][3] || "").trim().toUpperCase()
      ) {
        throw new Error("Your approved HR USER ACCESS record is no longer active or does not match this invitation.");
      }

      sheet.getRange(r + 1, 8).setValue("COMPLETED");
      sheet.getRange(r + 1, 10).setValue(now);
      return { success: true, message: "Your portal registration has been completed." };
    }

    throw new Error("The invitation link is invalid or cannot be found.");
  } finally {
    lock.releaseLock();
  }
}

/****************************************************
 * MANAGEMENT DASHBOARD
 ****************************************************/



/****************************************************
 * MANAGEMENT DASHBOARD - CORRECTED VERSION
 ****************************************************/

function getManagementDashboard(idToken) {

  const user = verifyFirebaseUser_(idToken);

  if (
    user.accessLevel !== "MANAGEMENT" &&
    user.accessLevel !== "ICT ADMINISTRATOR"
  ) {
    throw new Error(
      "Access denied. Management permission is required."
    );
  }

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

  const dashboard = ss.getSheetByName(
    HR_PORTAL_CONFIG.DASHBOARD_SHEET
  );

  if (!dashboard) {
    throw new Error("Management Dashboard sheet was not found.");
  }

  const staffSheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!staffSheet) {
    throw new Error("Staff database not found.");
  }

  const staffData = staffSheet.getDataRange().getValues();

  if (!staffData.length) {
    throw new Error("Staff database has no headings.");
  }

  const headers = staffData[0];

  const findColumn = name => headers.findIndex(header =>
    String(header).trim().replace(/\s+/g, " ").toUpperCase()
      === name.toUpperCase()
  );
const col = {
  timestamp: findColumn("TIMESTAMP"),
  oracle: findColumn("ORACLE ID"),
  name: findColumn("FULL NAME (SURNAME FIRST)"),
  gender: findColumn("GENDER"),
  grade: findColumn("GRADE LEVEL"),
  designation: findColumn("POST OF PRESENT APPOINTMENT/GRADE LEVEL"),
  lga: findColumn("PRESENT LGA / LCDA"),
  status: findColumn("CURRENT EMPLOYMENT STATUS"),
  promotion: findColumn("EXPECTED NEXT PROMOTION DATE"),
  retirement: findColumn("EXPECTED RETIREMENT DATE")
};

const requiredColumns = [
  "oracle", "gender", "grade", "lga",
  "promotion", "retirement"
];
  requiredColumns.forEach(key => {
    if (col[key] < 0) {
      throw new Error(
        "Required staff database heading is missing: " + key
      );
    }
  });

  // ---------------------------------------
  // OFFICIAL 57 COUNCILS
  // ---------------------------------------

  const councils = [
    "Agege", "Ajeromi-Ifelodun", "Alimosho",
    "Amuwo-Odofin", "Apapa", "Badagry", "Epe",
    "Eti-Osa", "Ibeju-Lekki", "Ifako-Ijaiye",
    "Ikeja", "Ikorodu", "Kosofe", "Lagos Island",
    "Lagos Mainland", "Mushin", "Ojo",
    "Oshodi-Isolo", "Shomolu", "Surulere",

    "Agbado-Oke Odo", "Agboyi-Ketu", "Apapa-Iganmu",
    "Ayobo-Ipaja", "Badagry West", "Bariga",
    "Coker-Aguda", "Egbe-Idimu", "Ejigbo",
    "Eredo", "Eti-Osa East", "Iba", "Ifelodun",
    "Igando-Ikotun", "Igbogbo-Baiyeku", "Ijede",
    "Ikorodu North", "Ikorodu West", "Ikosi-Ejinrin",
    "Ikosi-Isheri", "Ikoyi-Obalende", "Imota",
    "Iru-Victoria Island", "Isolo", "Itire-Ikate",
    "Lagos Island West", "Lekki", "Mosan-Okunola",
    "Odi-Olowo/Ojuwoye", "Ojodu", "Ojokoro",
    "Olorunda", "Onigbongbo", "Oriade",
    "Orile-Agege", "Oto-Awori", "Yaba"
  ];

  function normalizeCouncil(value) {
    return String(value || "")
      .trim()
      .toUpperCase()
      .replace(/\b(LGA|LCDA)\b/g, "")
      .replace(/[^A-Z0-9]/g, "");
  }

  const councilLookup = {};

  councils.forEach(name => {
    councilLookup[normalizeCouncil(name)] = name;
  });

  // ---------------------------------------
  // DATE READING
  // ---------------------------------------

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

    if (typeof value === "string" && value.trim()) {
      const parsed = new Date(value.trim());

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

    return null;
  }

  function dateKey(date) {
    return (
      date.getFullYear() * 10000 +
      (date.getMonth() + 1) * 100 +
      date.getDate()
    );
  }

  // ---------------------------------------
  // UNIQUE STAFF RECORDS
  // ---------------------------------------

  const uniqueStaff = [];
  const seenOracleIds = {};
  const duplicateOracleIds = [];

  let blankOracleRecords = 0;

  staffData.slice(1).forEach((row, index) => {

    const oracle = String(row[col.oracle] || "")
      .trim()
      .toUpperCase();

    if (!oracle) {
      if (row.some(v => v !== "" && v !== null)) {
        blankOracleRecords++;
      }
      return;
    }

    if (seenOracleIds[oracle]) {
      seenOracleIds[oracle].count++;

      duplicateOracleIds.push({
        oracleID: oracle,
        spreadsheetRow: index + 2
      });

      return;
    }

    seenOracleIds[oracle] = {
      count: 1,
      row: index + 2
    };

    uniqueStaff.push(row);
  });

  // ---------------------------------------
  // GENERAL STATISTICS
  // ---------------------------------------

  const totalStaff = uniqueStaff.length;

  const gradeCounts = {};
  const genderCounts = {
    MALE: 0,
    FEMALE: 0,
    "NOT RECORDED": 0
  };

  const employmentCounts = {};
  const councilCounts = {};

  councils.forEach(name => {
    councilCounts[name] = 0;
  });

  let gradeLevelNotRecorded = 0;
  let staffWithLGA = 0;
  let invalidCouncilRecords = 0;
  let incompleteRecords = 0;

  uniqueStaff.forEach(row => {

    const grade = String(row[col.grade] || "").trim();

    if (grade) {
      gradeCounts[grade] = (gradeCounts[grade] || 0) + 1;
    } else {
      gradeLevelNotRecorded++;
    }

    const gender = String(row[col.gender] || "")
      .trim().toUpperCase();

    if (gender === "MALE") {
      genderCounts.MALE++;
    } else if (gender === "FEMALE") {
      genderCounts.FEMALE++;
    } else {
      genderCounts["NOT RECORDED"]++;
    }

    if (col.status >= 0) {
      const status = String(row[col.status] || "").trim();

      if (status) {
        employmentCounts[status] =
          (employmentCounts[status] || 0) + 1;
      }
    }

    const rawCouncil = String(row[col.lga] || "").trim();

    if (rawCouncil) {
      const canonical = councilLookup[
        normalizeCouncil(rawCouncil)
      ];

      if (canonical) {
        councilCounts[canonical]++;
        staffWithLGA++;
      } else {
        invalidCouncilRecords++;
      }
    }

    if (
      !String(row[col.name] || "").trim() ||
      !grade ||
      !rawCouncil ||
      !gender
    ) {
      incompleteRecords++;
    }
  });
const totalGradeCount = Object.values(gradeCounts)
  .reduce((sum, count) => sum + count, 0);

console.log("DASHBOARD COUNT CHECK: " + JSON.stringify({
  totalStaff: totalStaff,
  duplicateOracleRecords: duplicateOracleIds.length,
  blankOracleRecords: blankOracleRecords,
  totalGradeCount: totalGradeCount,
  gradeLevelNotRecorded: gradeLevelNotRecorded,
  combinedGradeCount: totalGradeCount + gradeLevelNotRecorded
}));  const gradeLevelBreakdown = Object.keys(gradeCounts)
    .map(grade => ({
      gradeLevel: grade,
      staffCount: gradeCounts[grade]
    }))
    .sort((a, b) =>
      a.gradeLevel.localeCompare(
        b.gradeLevel,
        undefined,
        { numeric: true, sensitivity: "base" }
      )
    );

  const lgaDistribution = councils.map(name => ({
    council: name,
    staffCount: councilCounts[name]
  }));

  // ---------------------------------------
  // PROMOTION FORECAST - 2027
  // ---------------------------------------

  const januaryPromotions = [];
  const julyPromotions = [];
  const outstandingPromotions = [];

  uniqueStaff.forEach(row => {

    const date = readDate(row[col.promotion]);

    if (!date) return;

    const year = date.getFullYear();
    const month = date.getMonth();

    const officer = {
      oracleID: String(row[col.oracle] || "").trim(),
      fullName: col.name >= 0 ? row[col.name] : "",
      gradeLevel: row[col.grade],
       designation: col.designation >= 0 ? row[col.designation] : "",
      lga: row[col.lga],
      promotionDate: Utilities.formatDate(
        date,
        ss.getSpreadsheetTimeZone(),
        "dd MMMM yyyy"
      )
    };

    if (year === 2027 && month === 0) {
      januaryPromotions.push(officer);
    }

    if (year === 2027 && month === 6) {
      julyPromotions.push(officer);
    }

    if (year < 2027) {
      outstandingPromotions.push(officer);
    }
  });

  // ---------------------------------------
  // RETIREMENT FORECAST
  // 20 NOVEMBER 2026 - 31 DECEMBER 2027
  // ---------------------------------------

  const retirementStart = new Date(2026, 10, 20);
  const retirementEnd = new Date(2027, 11, 31);

  const retirementStartKey = dateKey(retirementStart);
  const retirementEndKey = dateKey(retirementEnd);

  const retirementMonths = [];

  for (let year = 2026; year <= 2027; year++) {

    const firstMonth = year === 2026 ? 10 : 0;
    const lastMonth = year === 2027 ? 11 : 11;

    for (let month = firstMonth; month <= lastMonth; month++) {

      retirementMonths.push({
        year: year,
        month: month,
        monthName: Utilities.formatDate(
          new Date(year, month, 1),
          ss.getSpreadsheetTimeZone(),
          "MMMM yyyy"
        ),
        count: 0,
        officers: []
      });
    }
  }

  uniqueStaff.forEach(row => {

    const date = readDate(row[col.retirement]);

    if (!date) return;

    const key = dateKey(date);

    if (
      key < retirementStartKey ||
      key > retirementEndKey
    ) {
      return;
    }

    const monthEntry = retirementMonths.find(item =>
      item.year === date.getFullYear() &&
      item.month === date.getMonth()
    );

    if (!monthEntry) return;

    monthEntry.count++;

    monthEntry.officers.push({
      oracleID: String(row[col.oracle] || "").trim(),
      fullName: col.name >= 0 ? row[col.name] : "",
      gradeLevel: row[col.grade],
      lga: row[col.lga],
      retirementDate: Utilities.formatDate(
        date,
        ss.getSpreadsheetTimeZone(),
        "dd MMMM yyyy"
      )
    });
  });

  const expectedRetirements = retirementMonths.reduce(
    (sum, item) => sum + item.count,
    0
  );

  // ---------------------------------------
  // AUDIT LOG
  // ---------------------------------------

  recordHRAudit_(
    "VIEW MANAGEMENT DASHBOARD",
    "",
    "Management dashboard statistics accessed.",
    "SUCCESS",
    idToken
  );

  // ---------------------------------------
  // RETURN DASHBOARD DATA
  // ---------------------------------------

  return JSON.parse(JSON.stringify({

    totalStaff: totalStaff,
    totalLGAs: councils.length,
    gradeLevels: gradeLevelBreakdown.length,
    staffWithLGA: staffWithLGA,

    expectedPromotions:
      januaryPromotions.length + julyPromotions.length,

    expectedRetirements: expectedRetirements,

    gradeLevelBreakdown: gradeLevelBreakdown,
    gradeLevelNotRecorded: gradeLevelNotRecorded,

    maleStaff: genderCounts.MALE,
    femaleStaff: genderCounts.FEMALE,
    unrecordedGender: genderCounts["NOT RECORDED"],

    malePercentage: totalStaff
      ? Math.round(genderCounts.MALE / totalStaff * 1000) / 10
      : 0,

    femalePercentage: totalStaff
      ? Math.round(genderCounts.FEMALE / totalStaff * 1000) / 10
      : 0,

    lgaDistribution: lgaDistribution,
    employmentStatusBreakdown: employmentCounts,

    january2027Promotions: januaryPromotions,
    july2027Promotions: julyPromotions,

    combinedJanuaryExamination:
      januaryPromotions.length + julyPromotions.length,

    outstandingPromotions: outstandingPromotions,

    retirementMonths: retirementMonths,

    duplicateOracleIds: duplicateOracleIds,
    duplicateOracleCount: duplicateOracleIds.length,

    blankOracleRecords: blankOracleRecords,
    incompleteRecords: incompleteRecords,
    invalidCouncilRecords: invalidCouncilRecords
  }));
}
/****************************************************
 * LGSC/HR57 CONNECT PORTAL - REPORT GENERATION
 * Management and ICT Administrator: system-wide reports.
 * HR Officer: reports restricted to assigned LGA/LCDA.
 ****************************************************/

function normalizeReportLocation_(value) {

  return String(value || "")
    .replace(/[\u00A0\u200B\uFEFF]/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .toUpperCase()
    .replace(/\s+(LGA|LCDA)$/i, "");

}


function formatPortalReportValue_(value, timeZone) {

  if (
    value === null ||
    value === undefined ||
    value === ""
  ) {
    return "";
  }

  if (value instanceof Date && !isNaN(value.getTime())) {

    return Utilities.formatDate(
      value,
      timeZone,
      "dd MMMM yyyy"
    );

  }

  return String(value).trim();

}


/****************************************************
 * GENERATE PORTAL REPORT
 ****************************************************/

function getPortalReport(reportType, idToken) {

  const user = verifyFirebaseUser_(idToken);

  const permittedRoles = [
    "MANAGEMENT",
    "HR OFFICER",
    "ICT ADMINISTRATOR"
  ];

  if (!permittedRoles.includes(user.accessLevel)) {
    throw new Error(
      "You are not authorised to generate reports."
    );
  }

  const allowedTypes = [
    "STAFF_MASTER",
    "LGA_DISTRIBUTION",
    "GRADE_LEVEL",
    "PROMOTION",
    "RETIREMENT",
    "EMPLOYMENT_STATUS",
    "GENDER_DISTRIBUTION"
  ];

  const selectedType = String(reportType || "")
    .trim()
    .toUpperCase();

  if (!allowedTypes.includes(selectedType)) {
    throw new Error("Please select a valid report type.");
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!sheet) {
    throw new Error("Staff database not found.");
  }

  const data = sheet.getDataRange().getValues();

  if (data.length < 2) {

    return {
      title: "LGSC/HR57 CONNECT - Staff Report",
      headers: ["Information"],
      rows: [["No staff records are currently available."]],
      total: 0,

      generatedAt: Utilities.formatDate(
        new Date(),
        ss.getSpreadsheetTimeZone(),
        "dd MMM yyyy HH:mm"
      ),

      fileName: "LGSC_HR57_Empty_Report.csv"
    };

  }

  const headers = data[0];

  const findCol = function(names) {

    const accepted = names.map(function(name) {

      return String(name)
        .trim()
        .replace(/\s+/g, " ")
        .toUpperCase();

    });

    return headers.findIndex(function(header) {

      return accepted.includes(
        String(header)
          .trim()
          .replace(/\s+/g, " ")
          .toUpperCase()
      );

    });

  };

  const col = {
timestamp: findCol(["TIMESTAMP"]),
    oracle: findCol(["ORACLE ID"]),

    name: findCol([
      "FULL NAME (SURNAME FIRST)",
      "FULL NAME"
    ]),

    fileNo: findCol([
      "COMMISSION FILE NUMBER"
    ]),

    designation: findCol([
  "POST OF PRESENT APPOINTMENT",
  "POST OF PRESENT APPOINTMENT/GRADE LEVEL"
]),

    cadre: findCol(["CADRE"]),
    grade: findCol(["GRADE LEVEL"]),

    lga: findCol([
      "PRESENT LGA / LCDA",
      "PRESENT LGA/LCDA"
    ]),

    status: findCol([
      "CURRENT EMPLOYMENT STATUS",
      "EMPLOYMENT STATUS"
    ]),

    promotion: findCol([
      "EXPECTED NEXT PROMOTION DATE"
    ]),

    retirement: findCol([
      "EXPECTED RETIREMENT DATE"
    ]),

    gender: findCol(["GENDER"])

  };


  /****************************************************
   * REQUIRED COLUMNS FOR EACH REPORT
   ****************************************************/

  const requiredByType = {

    STAFF_MASTER: [
      "oracle",
      "name",
      "fileNo",
      "designation",
      "cadre",
      "grade",
      "lga",
      "status",
      "promotion",
      "retirement"
    ],

    LGA_DISTRIBUTION: [
      "lga"
    ],

    GRADE_LEVEL: [
      "grade"
    ],

    PROMOTION: [
      "oracle",
      "name",
      "grade",
      "lga",
      "promotion"
    ],

    RETIREMENT: [
      "oracle",
      "name",
      "grade",
      "lga",
      "retirement"
    ],

    EMPLOYMENT_STATUS: [
      "status"
    ],

    GENDER_DISTRIBUTION: [
      "gender"
    ]

  };

  requiredByType[selectedType].forEach(function(key) {

    if (col[key] < 0) {

      throw new Error(
        "Required staff database heading is missing: " + key
      );

    }

  });


  /****************************************************
   * FILTER STAFF RECORDS
   ****************************************************/

  let records = data.slice(1).filter(function(row) {

    return row.some(function(value) {
      return value !== "" && value !== null;
    });

  });


  // Restrict HR Officers to their assigned LGA/LCDA.
  if (user.accessLevel === "HR OFFICER") {

    if (
      col.lga < 0 ||
      !String(user.assignedDepartment || "").trim()
    ) {

      throw new Error(
        "Your account has no valid assigned LGA/LCDA. Contact the ICT Administrator."
      );

    }

    const assigned = normalizeReportLocation_(
      user.assignedDepartment
    );

    records = records.filter(function(row) {

      return normalizeReportLocation_(
        row[col.lga]
      ) === assigned;

    });

  }


  /****************************************************
   * REPORT FORMATTING
   ****************************************************/

  const timeZone = ss.getSpreadsheetTimeZone();

  const val = function(row, key) {

    return col[key] < 0
      ? ""
      : formatPortalReportValue_(
          row[col[key]],
          timeZone
        );

  };

  let title = "";
  let reportHeaders = [];
  let reportRows = [];


  /****************************************************
   * STAFF MASTER REPORT
   ****************************************************/

  if (selectedType === "STAFF_MASTER") {

    title = "STAFF MASTER REPORT";

    reportHeaders = [
      "Oracle ID",
      "Full Name",
      "Commission File Number",
      "POST OF PRESENT APPOINTMENT/GRADE LEVEL",
      "Cadre",
      "Grade Level",
      "Present LGA / LCDA",
      "Employment Status",
      "Expected Next Promotion Date",
      "Expected Retirement Date"
    ];

    reportRows = records.map(function(row) {

  return [
    "oracle",
    "name",
    "fileNo",
    "designation",
    "cadre",
    "grade",
    "lga",
    "status",
    "promotion",
    "retirement"
  ].map(function(key) {

    var value = val(row, key);

    // STANDARDISE ADMIN & HR CADRE
    if (key === "cadre") {

      var cadre = String(value || "")
        .trim()
        .toUpperCase()
        .replace(/[^A-Z0-9]/g, "");

      if (
        cadre.includes("ADVANCE") &&
        cadre.includes("SPECIALGRADE")
      ) {
        return "Admin & HR Officer II";
      }

      if (cadre === "ADMINHROFFICERII") {
        return "Admin & HR Officer II";
      }
    }

    return value;

  });

});
// SORT BY CADRE A-Z, THEN GRADE LEVEL DESCENDING.
// Blank and numeric-only Cadres go to the bottom.

reportRows.sort(function(a, b) {

  var cadreA = String(a[4] || "").trim().toUpperCase();
  var cadreB = String(b[4] || "").trim().toUpperCase();

  var invalidA = !cadreA || /^\d+$/.test(cadreA);
  var invalidB = !cadreB || /^\d+$/.test(cadreB);

  if (invalidA && !invalidB) return 1;
  if (!invalidA && invalidB) return -1;

  var cadreCompare = cadreA.localeCompare(cadreB);

  if (cadreCompare !== 0) return cadreCompare;

  var gradeA = parseInt(
    String(a[5] || "").replace(/\D/g, ""), 10
  ) || 0;

  var gradeB = parseInt(
    String(b[5] || "").replace(/\D/g, ""), 10
  ) || 0;

  return gradeB - gradeA;

});
    // SORT BY CADRE (A-Z), THEN GRADE LEVEL (HIGHEST TO LOWEST).
// Blank and numeric-only Cadre values are placed at the bottom.

reportRows.sort(function(a, b) {

  var cadreA = String(a[4] || "").trim().toUpperCase();
  var cadreB = String(b[4] || "").trim().toUpperCase();

  // Identify blank or numeric-only Cadre values.
  var invalidA = !cadreA || /^\d+$/.test(cadreA);
  var invalidB = !cadreB || /^\d+$/.test(cadreB);

  if (invalidA && !invalidB) return 1;
  if (!invalidA && invalidB) return -1;

  // Sort recognised Cadres alphabetically.
  var cadreCompare = cadreA.localeCompare(cadreB);

  if (cadreCompare !== 0) {
    return cadreCompare;
  }

  // Sort Grade Level from highest to lowest.
  var gradeA = parseInt(
    String(a[5] || "").replace(/\D/g, ""), 10
  ) || 0;

  var gradeB = parseInt(
    String(b[5] || "").replace(/\D/g, ""), 10
  ) || 0;

  return gradeB - gradeA;

});

  /****************************************************
   * LGA / LCDA DISTRIBUTION REPORT
   ****************************************************/

  } else if (selectedType === "LGA_DISTRIBUTION") {

    title = "LGA / LCDA STAFF DISTRIBUTION REPORT";

    reportHeaders = [
      "LGA / LCDA",
      "Number of Staff"
    ];

    const counts = {};
    const labels = {};

    records.forEach(function(row) {

      const raw = String(row[col.lga] || "").trim();

      if (!raw) return;

      const key = normalizeReportLocation_(raw);

      counts[key] = (counts[key] || 0) + 1;
      labels[key] = labels[key] || raw;

    });

    reportRows = Object.keys(counts)
      .sort()
      .map(function(key) {

        return [
          labels[key],
          String(counts[key])
        ];

      });


  /****************************************************
   * GRADE LEVEL DISTRIBUTION REPORT
   ****************************************************/

  } else if (selectedType === "GRADE_LEVEL") {

    title = "GRADE LEVEL DISTRIBUTION REPORT";

    reportHeaders = [
      "Grade Level",
      "Number of Staff"
    ];

    const counts = {};

    records.forEach(function(row) {

      const grade = String(
        row[col.grade] || ""
      ).trim();

      if (grade) {

        counts[grade] = (counts[grade] || 0) + 1;

      }

    });

    reportRows = Object.keys(counts)
      .sort(function(a, b) {

        return a.localeCompare(
          b,
          undefined,
          {
            numeric: true,
            sensitivity: "base"
          }
        );

      })
      .map(function(grade) {

        return [
          grade,
          String(counts[grade])
        ];

      });

  /****************************************************
   * EXPECTED PROMOTION REPORT
   ****************************************************/

  } else if (selectedType === "PROMOTION") {

    title = "EXPECTED PROMOTION REPORT";

    reportHeaders = [
      "Oracle ID",
      "Full Name",
      "Grade Level",
      "LGA / LCDA",
      "Expected Next Promotion Date"
    ];

    
reportRows = records
  .map(function(row) {

    const calculatedPromotion = calculateExpectedPromotionDate_(
  val(row, "grade"),
  row[col.presentGradeDate]
);

    const promotionDate = calculatedPromotion !== null
      ? calculatedPromotion
      : val(row, "promotion");

    if (
      !promotionDate ||
      String(promotionDate).trim().toUpperCase() ===
        "UNABLE TO CALCULATE"
    ) {
      return null;
    }

    return [
      val(row, "oracle"),
      val(row, "name"),
      val(row, "grade"),
      val(row, "lga"),
      promotionDate instanceof Date
        ? Utilities.formatDate(
            promotionDate,
            Session.getScriptTimeZone(),
            "dd MMMM yyyy"
          )
        : promotionDate
    ];

  })
  .filter(function(row) {
    return row !== null;
  });

  /****************************************************
   * EXPECTED RETIREMENT REPORT
   ****************************************************/

  } else if (selectedType === "RETIREMENT") {

    title = "EXPECTED RETIREMENT REPORT";

    reportHeaders = [
      "Oracle ID",
      "Full Name",
      "Grade Level",
      "LGA / LCDA",
      "Expected Retirement Date"
    ];

    reportRows = records
      .filter(function(row) {

        const value = String(
          row[col.retirement] || ""
        ).trim();

        return (
          value !== "" &&
          value.toUpperCase() !== "UNABLE TO CALCULATE"
        );
      })
      .map(function(row) {

        return [
          "oracle",
          "name",
          "grade",
          "lga",
          "retirement"
        ].map(function(key) {
          return val(row, key);
        });
      });

  /****************************************************
   * STAFF DISTRIBUTION BY GENDER
   ****************************************************/

  } else if (selectedType === "GENDER_DISTRIBUTION") {

    title = "STAFF DISTRIBUTION BY GENDER";

    reportHeaders = [
      "Gender",
      "Number of Staff"
    ];

    const counts = {
      "Male": 0,
      "Female": 0,
      "Not Recorded": 0
    };

    records.forEach(function(row) {

      const gender = String(
        row[col.gender] || ""
      ).trim().toLowerCase();

      if (gender === "male") {
        counts.Male++;
      } else if (gender === "female") {
        counts.Female++;
      } else {
        counts["Not Recorded"]++;
      }
    });

    reportRows = Object.keys(counts).map(function(key) {

      return [
        key,
        String(counts[key])
      ];
    });

  /****************************************************
   * EMPLOYMENT STATUS REPORT
   ****************************************************/

  } else if (selectedType === "EMPLOYMENT_STATUS") {

    title = "EMPLOYMENT STATUS REPORT";

    reportHeaders = [
      "Employment Status",
      "Number of Staff"
    ];

    const counts = {};

    records.forEach(function(row) {

      const status = String(
        row[col.status] || ""
      ).trim();

      if (status) {
        counts[status] = (counts[status] || 0) + 1;
      }
    });

    reportRows = Object.keys(counts)
      .sort()
      .map(function(key) {

        return [
          key,
          String(counts[key])
        ];
      });
  }


  /****************************************************
   * RECORD REPORT GENERATION IN AUDIT LOG
   ****************************************************/

  recordHRAudit_(
    "GENERATE REPORT",
    "",
    title + " | Records included: " + records.length,
    "SUCCESS",
    idToken
  );

  const generatedAt = Utilities.formatDate(
    new Date(),
    timeZone,
    "dd MMM yyyy HH:mm"
  );

  return {
    title: title,
    headers: reportHeaders,
    rows: reportRows,
    total: reportRows.length,
    generatedAt: generatedAt,
    fileName: "LGSC_HR57_" + selectedType + "_Report.csv"
  };
}

/****************************************************
 * LGSC/HR57 CONNECT - SECURE NOMINAL ROLL DOWNLOAD
  * HR Officer: assigned LGA/LCDA only.
 * ICT Administrator: system-wide.
 * Management: system-wide.
 ****************************************************/

function generateNominalRollFiles(idToken) {

  const user = verifyFirebaseUser_(idToken);

  
  if (
    user.accessLevel !== "MANAGEMENT" &&
    user.accessLevel !== "HR OFFICER" &&
    user.accessLevel !== "ICT ADMINISTRATOR"
  ) {
    throw new Error(
      "Access denied. Nominal Roll download is not available for your role."
    );
  }

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

  const source = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!source) {
    throw new Error("Staff database not found.");
  }

  const data = source.getDataRange().getValues();

  if (data.length < 2) {
    throw new Error("There are no staff records to include.");
  }

  const headers = data[0];

  const findCol = function(names) {

    const accepted = names.map(function(n) {
      return String(n)
        .trim()
        .replace(/\s+/g, " ")
        .toUpperCase();
    });

    return headers.findIndex(function(h) {
      return accepted.includes(
        String(h)
          .trim()
          .replace(/\s+/g, " ")
          .toUpperCase()
      );
    });
  };

  const col = {

    oracle: findCol(["ORACLE ID"]),

    name: findCol([
      "FULL NAME (SURNAME FIRST)",
      "FULL NAME"
    ]),

    fileNo: findCol([
      "COMMISSION FILE NUMBER"
    ]),
	lashma: findCol([
  	"LASHMA NUMBER"
    ]),

    designation: findCol([
  "POST OF PRESENT APPOINTMENT",
  "POST OF PRESENT APPOINTMENT/GRADE LEVEL"
    ]),

    cadre: findCol(["CADRE"]),
    grade: findCol(["GRADE LEVEL"]),
    gender: findCol(["GENDER"]),

    firstAppointment: findCol([
      "DATE OF FIRST APPOINTMENT"
    ]),
presentGradeDate: findCol([
  "DATE OF PRESENT APPOINTMENT/GRADE LEVEL"
]),
    lga: findCol([
      "PRESENT LGA / LCDA",
      "PRESENT LGA/LCDA"
    ]),

    status: findCol([
      "CURRENT EMPLOYMENT STATUS",
      "EMPLOYMENT STATUS"
    ]),

    promotion: findCol([
      "EXPECTED NEXT PROMOTION DATE"
    ]),

    retirement: findCol([
      "EXPECTED RETIREMENT DATE"
    ]),

    professionalQualification: findCol([
      "PROFESSIONAL QUALIFICATION"
    ]),

    educationalQualification: findCol([
      "EDUCATIONAL QUALIFICATION"
    ])
  };

  const required = [
  "timestamp",
  "oracle",
  "name",
  "fileNo",
  "designation",
  "cadre",
  "grade",
  "gender",
  "firstAppointment",
  "presentGradeDate",
  "lga",
  "status",
  "promotion",
  "retirement"
];
  required.forEach(function(key) {

    if (col[key] < 0) {
      throw new Error(
        "Required staff database heading is missing: " + key
      );
    }
  });

  let records = data.slice(1).filter(function(row) {

    return row.some(function(v) {
      return v !== "" && v !== null;
    });
  });

  if (user.accessLevel === "HR OFFICER") {

    if (!String(user.assignedDepartment || "").trim()) {
      throw new Error(
        "Your account has no assigned LGA/LCDA. Contact the ICT Administrator."
      );
    }

    const assigned = normalizeReportLocation_(
      user.assignedDepartment
    );

    records = records.filter(function(row) {

      return normalizeReportLocation_(
        row[col.lga]
      ) === assigned;
    });
  }

  const tz = ss.getSpreadsheetTimeZone();
  const today = new Date();

  const headersOut = [
    "Oracle ID",
    "Full Name",
    "Commission File Number",
    "LASHMA Number",
    "POST OF PRESENT APPOINTMENT/GRADE LEVEL",
    "Cadre",
    "Grade Level",
    "Educational Qualification",
    "Professional Qualification",
    "Gender",
    "Date of First Appointment",
    "Present LGA / LCDA",
    "Employment Status",
    "Expected Next Promotion Date",
    "Expected Retirement Date",
    "Years and Months Remaining to Retirement"
  ];

  const dateText = function(v) {

    if (!v) return "";

    if (
      v instanceof Date &&
      !isNaN(v.getTime())
    ) {
      return Utilities.formatDate(
        v,
        tz,
        "dd MMMM yyyy"
      );
    }

    return String(v).trim();
  };

  const yearsAndMonthsLeft = function(v) {

    if (
      !(v instanceof Date) ||
      isNaN(v.getTime())
    ) {
      return "";
    }

    // Compare calendar dates, ignoring the time of day.
    const retirementDate = new Date(
      v.getFullYear(),
      v.getMonth(),
      v.getDate()
    );

    const currentDate = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate()
    );

    const days = (
      retirementDate.getTime() -
      currentDate.getTime()
    ) / 86400000;

    if (days < 0) {
      return "Retirement date passed";
    }

    // Convert remaining time to the nearest whole calendar month.
    const totalMonths = Math.round(
      days / 30.436875
    );

    const years = Math.floor(totalMonths / 12);
    const months = totalMonths % 12;

    return years +
      (years === 1 ? " Year, " : " Years, ") +
      months +
      (months === 1 ? " Month" : " Months");
  };
const normalizeCadre = function(value) {
  const cadre = String(value || "")
    .trim()
    .toUpperCase()
    .replace(/[^A-Z0-9]/g, "");

  // Group all Advancement on Special Grade variations
  // under Admin HR (A&HR).
  if (
  cadre.includes("ADVANCE") &&
  cadre.includes("SPECIALGRADE")
) {
  return "Admin & HR Officer II";
}

if (cadre === "ADMINHROFFICERII") {
  return "Admin & HR Officer II";
}

  return String(value || "").trim();
};  
const outputRows = records.map(function(row) {
  console.log(
  "CADRE CHECK:",
  row[col.cadre],
  "| NORMALISED:",
  normalizeCadre(row[col.cadre])
);

  return [
    row[col.oracle],
    row[col.name],
    row[col.fileNo],

    // LASHMA Number
    col.lashma >= 0 ? row[col.lashma] : "",

    row[col.designation],
    normalizeCadre(row[col.cadre]),
    row[col.grade],

    col.educationalQualification >= 0
      ? row[col.educationalQualification]
      : "",

    col.professionalQualification >= 0
      ? row[col.professionalQualification]
      : "",

    row[col.gender],
    dateText(row[col.firstAppointment]),
    row[col.lga],
    row[col.status],
    dateText(row[col.promotion]),
    dateText(row[col.retirement]),
    yearsAndMonthsLeft(row[col.retirement])
  ];
});
  // SORT BY CADRE (A-Z), THEN GRADE LEVEL (HIGHEST TO LOWEST).
// Blank or unrecognised Cadre values are placed at the bottom.

outputRows.sort(function(a, b) {

  var cadreA = String(a[5] || "").trim().toUpperCase();
  var cadreB = String(b[5] || "").trim().toUpperCase();

  // Treat numeric-only Cadre values such as "7" as unrecognised.
  var invalidA = !cadreA || /^\d+$/.test(cadreA);
  var invalidB = !cadreB || /^\d+$/.test(cadreB);

  if (invalidA && !invalidB) return 1;
  if (!invalidA && invalidB) return -1;

  // Sort recognised Cadres alphabetically.
  var cadreCompare = cadreA.localeCompare(cadreB);

  if (cadreCompare !== 0) {
    return cadreCompare;
  }

  // Sort Grade Level in descending numerical order.
  var gradeA = parseInt(
    String(a[6] || "").replace(/\D/g, ""), 10
  ) || 0;

  var gradeB = parseInt(
    String(b[6] || "").replace(/\D/g, ""), 10
  ) || 0;

  return gradeB - gradeA;

});
  const stamp = Utilities.formatDate(
    new Date(),
    tz,
    "yyyyMMdd_HHmmss"
  );

  const baseName = "LGSC_HR57_Nominal_Roll_" +
    (
      user.accessLevel === "HR OFFICER"
        ? String(user.assignedDepartment)
            .replace(/[^A-Za-z0-9_-]/g, "_")
        : "All_Areas"
    ) + "_" + stamp;

  // Create a temporary spreadsheet.
  const temp = SpreadsheetApp.create(baseName);

  const tab = temp.getSheets()[0];

tab.setName("Nominal Roll");

// Ensure the temporary sheet has enough rows and columns.
const requiredRows = Math.max(outputRows.length + 10, 100);
const requiredColumns = headersOut.length;

if (tab.getMaxRows() < requiredRows) {
  tab.insertRowsAfter(
    tab.getMaxRows(),
    requiredRows - tab.getMaxRows()
  );
}

if (tab.getMaxColumns() < requiredColumns) {
  tab.insertColumnsAfter(
    tab.getMaxColumns(),
    requiredColumns - tab.getMaxColumns()
  );
}
  const coverage = user.accessLevel === "HR OFFICER"
    ? String(user.assignedDepartment).trim()
    : "All LGAs / LCDAs";

  const generatedLabel = Utilities.formatDate(
    new Date(),
    tz,
    "dd MMMM yyyy, hh:mm a"
  );

  // Official report headings.
  tab.getRange(1, 1, 1, headersOut.length).merge();

  tab.getRange(1, 1).setValue(
    "LAGOS STATE LOCAL GOVERNMENT SERVICE COMMISSION"
  );

  tab.getRange(2, 1, 1, headersOut.length).merge();

  tab.getRange(2, 1).setValue(
    "STAFF NOMINAL ROLL"
  );

  tab.getRange(3, 1, 1, headersOut.length).merge();

  tab.getRange(3, 1).setValue(
    "Coverage: " + coverage +
    "    |    Generated: " + generatedLabel
  );

  // Table headings.
  tab.getRange(4, 1, 1, headersOut.length)
    .setValues([headersOut]);

  // Staff records.
  if (outputRows.length) {

    tab.getRange(
      5,
      1,
      outputRows.length,
      headersOut.length
    ).setValues(outputRows);
  }

  // Format official report headings.
  tab.getRange(1, 1, 1, headersOut.length)
    .setFontFamily("Arial")
    .setFontWeight("bold")
    .setFontSize(15)
    .setFontColor("#17365D")
    .setHorizontalAlignment("center")
    .setVerticalAlignment("middle");

  tab.getRange(2, 1, 1, headersOut.length)
    .setFontFamily("Arial")
    .setFontWeight("bold")
    .setFontSize(13)
    .setFontColor("#17365D")
    .setHorizontalAlignment("center")
    .setVerticalAlignment("middle");

  tab.getRange(3, 1, 1, headersOut.length)
    .setFontFamily("Arial")
    .setFontSize(9)
    .setFontColor("#444444")
    .setHorizontalAlignment("center")
    .setVerticalAlignment("middle");

  // Format table headings.
  tab.getRange(4, 1, 1, headersOut.length)
    .setFontWeight("bold")
    .setFontSize(9)
    .setBackground("#17365D")
    .setFontColor("#FFFFFF")
    .setHorizontalAlignment("center")
    .setVerticalAlignment("middle")
    .setWrap(true);

  tab.setFrozenRows(4);

  tab.getDataRange()
    .setFontFamily("Arial")
    .setFontSize(9)
    .setVerticalAlignment("middle")
    .setWrap(true);

  // Column widths: 16 columns, including LASHMA Number.
  const columnWidths = [
    85, 170, 145, 120,
    155, 140, 80, 185,
    185, 85, 130, 125,
    135, 145, 145, 165
  ];

  columnWidths.forEach(function(width, index) {

    tab.setColumnWidth(index + 1, width);
  });

  tab.setRowHeight(1, 30);
  tab.setRowHeight(2, 26);
  tab.setRowHeight(3, 22);
  tab.setRowHeight(4, 48);

  if (outputRows.length) {

    tab.autoResizeRows(5, outputRows.length);

    tab.getRange(
      5,
      1,
      outputRows.length,
      headersOut.length
    ).setHorizontalAlignment("left");
  }

  tab.getDataRange().setBorder(
    true,
    true,
    true,
    true,
    true,
    true,
    "#D9E1F2",
    SpreadsheetApp.BorderStyle.SOLID
  );

  // Official approval section.
  const approvalStartRow = 5 + outputRows.length + 2;

  const approvalSections = [
    { startCol: 1, title: "PREPARED BY" },
    { startCol: 6, title: "CHECKED BY" },
    { startCol: 11, title: "APPROVED BY" }
  ];

  approvalSections.forEach(function(section) {

    tab.getRange(
      approvalStartRow,
      section.startCol,
      1,
      5
    ).merge();

    tab.getRange(
      approvalStartRow,
      section.startCol
    )
      .setValue(section.title)
      .setFontFamily("Arial")
      .setFontWeight("bold")
      .setFontSize(9)
      .setFontColor("#17365D")
      .setHorizontalAlignment("center")
      .setVerticalAlignment("middle");

    tab.getRange(
      approvalStartRow + 1,
      section.startCol,
      1,
      5
    ).merge();

    tab.getRange(
      approvalStartRow + 1,
      section.startCol
    )
      .setValue(
        "Name: ____________________   Signature: ____________________   Date: __________"
      )
      .setFontFamily("Arial")
      .setFontSize(8)
      .setHorizontalAlignment("left")
      .setVerticalAlignment("middle")
      .setWrap(true);
  });

  tab.setRowHeight(approvalStartRow, 24);
  tab.setRowHeight(approvalStartRow + 1, 42);

  tab.getRange(
    approvalStartRow,
    1,
    2,
    headersOut.length
  ).setBorder(
    true,
    true,
    true,
    true,
    true,
    true,
    "#D9E1F2",
    SpreadsheetApp.BorderStyle.SOLID
  );

  SpreadsheetApp.flush();

  const token = ScriptApp.getOAuthToken();

  const exportFile = function(format, mimeType, extension) {

    const url =
      "https://docs.google.com/spreadsheets/d/" +
      temp.getId() +
      "/export?format=" + format;

    const response = UrlFetchApp.fetch(url, {

      headers: {
        Authorization: "Bearer " + token
      },

      muteHttpExceptions: true
    });

    if (response.getResponseCode() !== 200) {

      throw new Error(
        "Unable to create " +
        extension.toUpperCase() +
        " file. Check Google Drive export permissions."
      );
    }

    const file = DriveApp.createFile(
      response.getBlob()
        .setName(baseName + "." + extension)
        .setContentType(mimeType)
    );

    file.addViewer(user.email);

    return "https://drive.google.com/uc?export=download&id=" +
      file.getId();
  };

  try {

    const excelUrl = exportFile(
      "xlsx",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "xlsx"
    );

    const pdfUrl = exportFile(
      "pdf&portrait=false&fitw=true&sheetnames=false&printtitle=false&pagenumbers=true&gridlines=false&fzr=true",
      "application/pdf",
      "pdf"
    );

    recordHRAudit_(
      "DOWNLOAD NOMINAL ROLL",
      "",
      "Records included: " + records.length,
      "SUCCESS",
      idToken
    );

    return {
      total: records.length,
      excelUrl: excelUrl,
      pdfUrl: pdfUrl
    };

  } finally {

    DriveApp.getFileById(temp.getId()).setTrashed(true);
  }
}
/**
 * ONE-TIME FIRST ICT ADMINISTRATOR INVITATION SETUP
 * Run manually from the Apps Script editor.
 * Delete this function after successful use.
 */

function runFirstAdminInvitationSetup() {

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

  const accessSheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.ACCESS_SHEET
  );

  if (!accessSheet) {
    throw new Error("HR USER ACCESS sheet was not found.");
  }

  const rows = accessSheet.getDataRange().getValues();
  const approvedAdmins = [];

  for (let r = 1; r < rows.length; r++) {

    const role = String(rows[r][2] || "")
      .trim().toUpperCase();

    const status = String(rows[r][4] || "")
      .trim().toUpperCase();

    if (
      role === "ICT ADMINISTRATOR" &&
      status === "ACTIVE"
    ) {
      approvedAdmins.push({
        name: String(rows[r][0] || "").trim(),
        email: String(rows[r][1] || "").trim().toLowerCase(),
        role: role,
        department: String(rows[r][3] || "").trim(),
        status: status
      });
    }
  }

  if (approvedAdmins.length !== 1) {
    throw new Error(
      "Setup requires exactly one ACTIVE ICT ADMINISTRATOR record."
    );
  }

  const approvedUser = approvedAdmins[0];

  if (!approvedUser.name || !approvedUser.email) {
    throw new Error(
      "Administrator name or email is missing."
    );
  }

  if (approvedUser.department !== "") {
    throw new Error(
      "The ICT Administrator assigned department must be blank."
    );
  }

  const deploymentUrl = "https://script.google.com/macros/s/AKfycbyvzCDPvjeiTqsiPjw1fFbsASBWHXAmVfon8kgL1efc-LiWrp59qakop81dX3Lg1Ebc2w/exec";
  const token =
    Utilities.getUuid().replace(/-/g, "") +
    Utilities.getUuid().replace(/-/g, "") +
    Utilities.getUuid().replace(/-/g, "");

  const tokenHash = hashInvitationToken_(token);
  const now = new Date();

  const expiry = new Date(
    now.getTime() +
    HR_INVITATION_CONFIG.VALID_HOURS * 60 * 60 * 1000
  );

  const invitationUrl =
    deploymentUrl + "?token=" + encodeURIComponent(token);

  const sheet = getInvitationSheet_();

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

  try {

    const invitationRows = sheet.getDataRange().getValues();

    for (let r = 1; r < invitationRows.length; r++) {

      if (
        String(invitationRows[r][2] || "")
          .trim().toLowerCase() === approvedUser.email &&
        String(invitationRows[r][7] || "")
          .trim().toUpperCase() === "PENDING"
      ) {
        sheet.getRange(r + 1, 8).setValue("REVOKED");
      }
    }

    sheet.appendRow([
      tokenHash,
      approvedUser.name,
      approvedUser.email,
      approvedUser.role,
      "",
      now,
      expiry,
      "PENDING",
      approvedUser.email,
      ""
    ]);

  } finally {
    lock.releaseLock();
  }

  try {

    MailApp.sendEmail({
      to: approvedUser.email,
      subject: "First Administrator Invitation - CMD/HR57 CONNECT PORTAL",
      name: "CMD/HR57 CONNECT PORTAL",
      body:
        "Dear " + approvedUser.name + ",\n\n" +
        "You have been approved as the first ICT Administrator " +
        "of the CMD/HR57 CONNECT PORTAL.\n\n" +
        "Use the secure link below to create your portal password:\n\n" +
        invitationUrl + "\n\n" +
        "This invitation expires in 48 hours and can only be used once.\n\n" +
        "Please verify your email address before signing in.\n\n" +
        "Regards,\nCMD/HR57 CONNECT PORTAL"
    });

    console.log(
      "First administrator invitation successfully sent to " +
      approvedUser.email
    );

  } catch (error) {

    const invitationRows = sheet.getDataRange().getValues();

    for (let r = invitationRows.length - 1; r >= 1; r--) {

      if (String(invitationRows[r][0] || "") === tokenHash) {
        sheet.getRange(r + 1, 8).setValue("EMAIL_FAILED");
        break;
      }
    }

    throw new Error(
      "Invitation record created, but email delivery failed: " +
      error.message
    );
  }
}
function authorizeMailPermission() {
  const remaining = MailApp.getRemainingDailyQuota();
  console.log("Mail permission authorised. Remaining quota: " + remaining);
}


function testLatestInvitationToken() {
  const sheet = getInvitationSheet_();
  const rows = sheet.getDataRange().getValues();

  const latest = rows[rows.length - 1];

  console.log("LATEST INVITATION EMAIL: " + latest[2]);
  console.log("LATEST INVITATION STATUS: " + latest[7]);
  console.log("STORED HASH LENGTH: " + String(latest[0] || "").length);
  console.log("STORED HASH PREFIX: " +
    String(latest[0] || "").substring(0, 8));
}

function testInvitationSheetConnection() {
  const ss = SpreadsheetApp.openById(
    HR_PORTAL_CONFIG.SPREADSHEET_ID
  );

  const sheet = ss.getSheetByName(
    HR_INVITATION_CONFIG.SHEET_NAME
  );

  if (!sheet) {
    console.log("INVITATION SHEET: NOT FOUND");
    return;
  }

  const rows = sheet.getDataRange().getValues();
  const latest = rows[rows.length - 1];

  console.log("SPREADSHEET NAME: " + ss.getName());
  console.log("INVITATION SHEET: FOUND");
  console.log("LAST ROW: " + sheet.getLastRow());
  console.log("LATEST EMAIL: " + latest[2]);
  console.log("LATEST STATUS: " + latest[7]);
}

function checkFirebaseUserStatus() {
  const email = "ivtsystemtech@gmail.com";

  try {
    const user = FirebaseAuth.getUserByEmail(email);

    const result = {
      email: user.email,
      emailVerified: user.emailVerified,
      uid: user.uid,
      creationTime: user.metadata.creationTime,
      lastSignInTime: user.metadata.lastSignInTime
    };

    Logger.log(JSON.stringify(result, null, 2));
    return result;

  } catch (error) {
    Logger.log("Firebase diagnostic error: " + error.message);
    throw error;
  }
}

function checkYahooVerificationStatus() {

  const email = "dam752002@yahoo.com";

  const apiKey = PropertiesService
    .getScriptProperties()
    .getProperty("FIREBASE_WEB_API_KEY");

  if (!apiKey) {
    throw new Error("Firebase API key is missing.");
  }

  const url =
    "https://identitytoolkit.googleapis.com/v1/accounts:createAuthUri?key=" +
    encodeURIComponent(apiKey);

  const response = UrlFetchApp.fetch(url, {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({
      identifier: email,
      continueUri: "https://example.com"
    }),
    muteHttpExceptions: true
  });

  Logger.log(response.getContentText());
}
function testPromotionDateCalculation() {

  const tests = [
    ["GL14", "2024-07-01"],
    ["GL08", "2024-01-01"],
    ["GL15", "2022-08-10"],
    ["GL07", "2024-02-15"],
    ["GL17", "2024-01-01"]
  ];

  tests.forEach(test => {

    const date = new Date(test[1] + "T12:00:00");

    const result = calculateExpectedPromotionDate_(
      test[0],
      date
    );

    Logger.log(
      test[0] + " | " +
      test[1] + " | " +
      (result instanceof Date
        ? Utilities.formatDate(
            result,
            Session.getScriptTimeZone(),
            "dd MMMM yyyy"
          )
        : result)
    );

  });
}

function testAppointmentValidation() {

  const tests = [
    {
      name: "January appointment with incorrect present-grade cycle",
      firstAppointment: "2018-01-08",
      presentGradeDate: "2024-01-01"
    },
    {
      name: "January appointment with correct July cycle",
      firstAppointment: "2018-01-08",
      presentGradeDate: "2024-07-01"
    },
    {
      name: "January 1 appointment with January cycle",
      firstAppointment: "2018-01-01",
      presentGradeDate: "2024-01-01"
    }
  ];

  tests.forEach(function(test) {

    const result = validatePresentGradeAppointment_(
      new Date(test.firstAppointment + "T12:00:00"),
      new Date(test.presentGradeDate + "T12:00:00")
    );

    Logger.log(
      test.name +
      " | Result: " + result.status +
      " | Remarks: " + result.message
    );

  });
}

function generateDuplicateOracleReport() {

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

  const source = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!source) {
    throw new Error("Staff database not found.");
  }

  const data = source.getDataRange().getValues();
  const headers = data[0];

  function findColumn(name) {
    return headers.findIndex(h =>
      String(h).trim().replace(/\s+/g, " ").toUpperCase()
      === name.toUpperCase()
    );
  }

  const col = {
    oracle: findColumn("ORACLE ID"),
    name: findColumn("FULL NAME (SURNAME FIRST)"),
    grade: findColumn("GRADE LEVEL"),
    lga: findColumn("PRESENT LGA / LCDA"),
    status: findColumn("CURRENT EMPLOYMENT STATUS")
  };

  if (col.oracle < 0) {
    throw new Error("ORACLE ID column not found.");
  }

  const seen = Object.create(null);
  const report = [[
    "ISSUE TYPE",
    "ORACLE ID",
    "FULL NAME",
    "GRADE LEVEL",
    "PRESENT LGA / LCDA",
    "EMPLOYMENT STATUS",
    "FIRST OCCURRENCE ROW",
    "DUPLICATE / MISSING RECORD ROW"
  ]];

  let duplicateCount = 0;
  let blankCount = 0;

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

    const sheetRow = index + 2;

    const oracle = String(row[col.oracle] || "")
      .trim().toUpperCase();

    const hasData = row.some(v => v !== "" && v !== null);

    if (!oracle) {
      if (hasData) {
        blankCount++;

        report.push([
          "MISSING ORACLE ID",
          "",
          col.name >= 0 ? row[col.name] : "",
          col.grade >= 0 ? row[col.grade] : "",
          col.lga >= 0 ? row[col.lga] : "",
          col.status >= 0 ? row[col.status] : "",
          "",
          sheetRow
        ]);
      }
      return;
    }

    if (seen[oracle]) {
      duplicateCount++;

      report.push([
        "DUPLICATE ORACLE ID",
        oracle,
        col.name >= 0 ? row[col.name] : "",
        col.grade >= 0 ? row[col.grade] : "",
        col.lga >= 0 ? row[col.lga] : "",
        col.status >= 0 ? row[col.status] : "",
        seen[oracle],
        sheetRow
      ]);

    } else {
      seen[oracle] = sheetRow;
    }

  });

  const timestamp = Utilities.formatDate(
    new Date(),
    ss.getSpreadsheetTimeZone(),
    "yyyyMMdd_HHmmss"
  );

  const reportName = "ORACLE ID REVIEW " + timestamp;
  const output = ss.insertSheet(reportName);

  output.getRange(
    1, 1, report.length, report[0].length
  ).setValues(report);

  output.setFrozenRows(1);
  output.autoResizeColumns(1, 8);


  Logger.log("REPORT SHEET: " + reportName);
  Logger.log("DUPLICATE RECORDS: " + duplicateCount);
  Logger.log("MISSING ORACLE IDs: " + blankCount);

}

/****************************************************
 * ICT ADMINISTRATOR – STAFF EDITING LINK
 * Retrieves an existing link or creates one if absent.
 * Does not replace an existing editing token.
 ****************************************************/

function getOrCreateStaffEditingLink(oracleID, idToken) {

  const user = verifyFirebaseUser_(idToken);

  if (user.accessLevel !== "ICT ADMINISTRATOR") {
  throw new Error(
    "Only ICT Administrator can generate staff editing links."
  );
}

  const searchID = String(oracleID || "").trim();

  if (!searchID) {
    throw new Error("Please enter a Staff Oracle ID.");
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!sheet) {
    throw new Error("Staff database not found.");
  }

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

  if (lastRow < 2) {
    throw new Error("No staff records are available.");
  }

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

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

  const oracleColumn = findColumn("ORACLE ID");
  const nameColumn = findColumn("FULL NAME (SURNAME FIRST)");
  const tokenColumn = findColumn("CUSTOM EDIT TOKEN");
  const linkColumn = findColumn("EDIT RESPONSE LINK");

  if (
    oracleColumn === -1 ||
    nameColumn === -1 ||
    tokenColumn === -1
  ) {
    throw new Error("Required staff database columns are missing.");
  }

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

  let rowNumber = -1;
  let staffName = "";

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

    if (
      String(records[i][oracleColumn]).trim() === searchID
    ) {
      rowNumber = i + 2;
      staffName = String(records[i][nameColumn] || "");
      break;
    }
  }

  if (rowNumber === -1) {
    throw new Error("No staff record found for this Oracle ID.");
  }

  let editToken = String(
    sheet.getRange(rowNumber, tokenColumn + 1)
      .getDisplayValue()
  ).trim();

  let generated = false;

  if (!editToken) {
    editToken = Utilities.getUuid();

    sheet.getRange(
      rowNumber, tokenColumn + 1
    ).setValue(editToken);

    generated = true;
  }

  const editUrl =
    ScriptApp.getService().getUrl() +
    "?form=staff&token=" +
    encodeURIComponent(editToken);

  if (linkColumn !== -1) {
    sheet.getRange(
      rowNumber, linkColumn + 1
    ).setValue(editUrl);
  }

  SpreadsheetApp.flush();

  recordHRAudit_(
    generated
      ? "STAFF EDITING LINK GENERATED"
      : "STAFF EDITING LINK RETRIEVED",
    searchID,
    "Personal staff editing link processed by ICT Administrator.",
    "SUCCESS",
    idToken
  );

  return {
    success: true,
    oracleID: searchID,
    fullName: staffName,
    editUrl: editUrl,
    generated: generated
  };
}

/****************************************************
 * CMD STAFF - DUAL ACCOUNT APPROVAL
 ****************************************************/

const CMD_STAFF_APPROVAL_CONFIG = {
  SHEET_NAME: "CMD STAFF APPROVALS",
  HEADERS: [
    "CMD STAFF EMAIL",
    "MANAGEMENT APPROVAL",
    "MANAGEMENT APPROVED BY",
    "MANAGEMENT APPROVAL DATE",
    "ICT APPROVAL",
    "ICT APPROVED BY",
    "ICT APPROVAL DATE"
  ]
};
const CMD_STAFF_EDIT_GRANT_CONFIG = {
  SHEET_NAME: "CMD STAFF EDIT GRANTS",
  HEADERS: [
    "CMD STAFF EMAIL",
    "GRANT STATUS",
    "GRANTED BY",
    "GRANT DATE",
    "EXPIRY DATE",
    "USED DATE",
    "REVOKED DATE"
  ]
};


function getCmdStaffEditGrantSheet_() {
  const ss = SpreadsheetApp.openById(
    HR_PORTAL_CONFIG.SPREADSHEET_ID
  );

  let sheet = ss.getSheetByName(
    CMD_STAFF_EDIT_GRANT_CONFIG.SHEET_NAME
  );

  if (!sheet) {
    sheet = ss.insertSheet(
      CMD_STAFF_EDIT_GRANT_CONFIG.SHEET_NAME
    );

    sheet.getRange(
      1,
      1,
      1,
      CMD_STAFF_EDIT_GRANT_CONFIG.HEADERS.length
    ).setValues([
      CMD_STAFF_EDIT_GRANT_CONFIG.HEADERS
    ]);

    sheet.setFrozenRows(1);
  }

  return sheet;
}

function grantCmdStaffEditAccess(targetEmail, idToken) {
  const user = verifyFirebaseUser_(idToken);

  if (
    user.accessLevel !== "MANAGEMENT" &&
    user.accessLevel !== "ICT ADMINISTRATOR"
  ) {
    throw new Error(
      "Only Management or ICT Administrator can grant temporary access."
    );
  }

  const target = String(targetEmail || "")
    .trim()
    .toLowerCase();

  const account = findCmdStaffAccessRecord_(target);

  if (
    !account ||
    account.role !== "CMD STAFF" ||
    account.status !== "ACTIVE"
  ) {
    throw new Error("Target must be an active CMD STAFF account.");
  }

  const sheet = getCmdStaffEditGrantSheet_();
  const lock = LockService.getScriptLock();

  lock.waitLock(10000);

  try {
    const rows = sheet.getDataRange().getValues();
    let rowNumber = -1;

    for (let i = 1; i < rows.length; i++) {
      if (
        String(rows[i][0] || "")
          .trim()
          .toLowerCase() === target
      ) {
        rowNumber = i + 1;
        break;
      }
    }

    if (rowNumber === -1) {
      rowNumber = sheet.getLastRow() + 1;
    }

    const now = new Date();
    const expiry = new Date(now.getTime() + 30 * 60 * 1000);

    sheet.getRange(rowNumber, 1, 1, 7).setValues([[
      target,
      "ACTIVE",
      user.email,
      now,
      expiry,
      "",
      ""
    ]]);

    recordHRAudit_(
      "CMD STAFF TEMPORARY EDIT ACCESS GRANTED",
      "",
      "Target: " + target,
      "SUCCESS",
      idToken
    );

    return {
      success: true,
      message: "Temporary editing access granted for 30 minutes."
    };

  } finally {
    lock.releaseLock();
  }
}


function revokeCmdStaffEditAccessOnLogout(idToken) {
  const user = verifyFirebaseUser_(idToken);

  if (user.accessLevel !== "CMD STAFF") {
    return { success: true };
  }

  const sheet = getCmdStaffEditGrantSheet_();
  const lock = LockService.getScriptLock();

  lock.waitLock(10000);

  try {
    const rows = sheet.getDataRange().getValues();

    for (let i = 1; i < rows.length; i++) {
      const email = String(rows[i][0] || "")
        .trim()
        .toLowerCase();

      const status = String(rows[i][1] || "")
        .trim()
        .toUpperCase();

      if (email === user.email && status === "ACTIVE") {
        sheet.getRange(i + 1, 2).setValue("REVOKED");
        sheet.getRange(i + 1, 7).setValue(new Date());
      }
    }

    return { success: true };

  } finally {
    lock.releaseLock();
  }
}

function getCmdStaffApprovalSheet_() {
  const ss = SpreadsheetApp.openById(
    HR_PORTAL_CONFIG.SPREADSHEET_ID
  );

  const sheetName =
    CMD_STAFF_APPROVAL_CONFIG.SHEET_NAME;

  const sheet = ss.getSheetByName(sheetName);

  // Do not create a blank approval sheet during validation.
  if (!sheet) {
    throw new Error(
      "Approval sheet not found: " + sheetName
    );
  }

  return sheet;
}

function findCmdStaffAccessRecord_(email) {
  const ss = SpreadsheetApp.openById(
    HR_PORTAL_CONFIG.SPREADSHEET_ID
  );

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.ACCESS_SHEET
  );

  if (!sheet) {
    throw new Error(
      "HR USER ACCESS sheet was not found."
    );
  }

  const rows = sheet.getDataRange().getDisplayValues();

  const targetEmail = String(email || "")
    .trim()
    .toLowerCase();

  for (let i = 1; i < rows.length; i++) {
    const rowEmail = String(rows[i][1] || "")
      .trim()
      .toLowerCase();

    const role = String(rows[i][2] || "")
      .trim()
      .toUpperCase();

    const status = String(rows[i][4] || "")
      .trim()
      .toUpperCase();

    if (rowEmail === targetEmail) {
      return {
        email: rowEmail,
        role: role,
        status: status
      };
    }
  }

  return null;
}
function assertCmdStaffFullyApproved_(email) {
  const target = String(email || "")
    .trim()
    .toLowerCase();

  if (!target) {
    throw new Error("CMD STAFF email is missing.");
  }

  // Confirm that the account exists and is active.
  const account = findCmdStaffAccessRecord_(target);

  if (
    !account ||
    account.role !== "CMD STAFF" ||
    account.status !== "ACTIVE"
  ) {
    throw new Error(
      "CMD STAFF account is not active or does not exist."
    );
  }

  const sheet = getCmdStaffApprovalSheet_();
  const rows = sheet.getDataRange().getDisplayValues();

  if (rows.length < 2) {
    throw new Error(
      "No CMD STAFF approval records were found."
    );
  }

  // Locate approval columns by their header names.
  const headers = rows[0].map(value =>
    String(value || "")
      .trim()
      .toUpperCase()
      .replace(/\s+/g, " ")
  );

  const emailColumn = headers.indexOf("CMD STAFF EMAIL");
  const managementColumn =
    headers.indexOf("MANAGEMENT APPROVAL");
  const ictColumn =
    headers.indexOf("ICT APPROVAL");

  if (
    emailColumn < 0 ||
    managementColumn < 0 ||
    ictColumn < 0
  ) {
    throw new Error(
      "Approval sheet is missing required columns. " +
      "Expected CMD STAFF EMAIL, MANAGEMENT APPROVAL, " +
      "and ICT APPROVAL."
    );
  }

  // Find the exact CMD STAFF email.
  for (let i = 1; i < rows.length; i++) {
    const approvalEmail = String(
      rows[i][emailColumn] || ""
    )
      .trim()
      .toLowerCase();

    if (approvalEmail !== target) {
      continue;
    }

    const managementApproval = String(
      rows[i][managementColumn] || ""
    )
      .trim()
      .toUpperCase();

    const ictApproval = String(
      rows[i][ictColumn] || ""
    )
      .trim()
      .toUpperCase();

    // Management OR ICT approval is sufficient.
    if (
      managementApproval === "APPROVED" ||
      ictApproval === "APPROVED"
    ) {
      return true;
    }

    throw new Error(
      "CMD STAFF editing requires Management or " +
      "ICT Administrator approval. " +
      "Management: " + managementApproval +
      "; ICT: " + ictApproval
    );
  }

  throw new Error(
    "No approval record found for CMD STAFF email: " +
    target
  );
}


function getCmdStaffApprovalStatus(targetEmail, idToken) {
  const user = verifyFirebaseUser_(idToken);

  const target = String(targetEmail || "")
    .trim()
    .toLowerCase();

  if (!target) {
    throw new Error("CMD STAFF email is required.");
  }

  const allowedViewer =
    user.accessLevel === "MANAGEMENT" ||
    user.accessLevel === "ICT ADMINISTRATOR" ||
    (
      user.accessLevel === "CMD STAFF" &&
      user.email === target
    );

  if (!allowedViewer) {
    throw new Error("Access denied.");
  }

  const account = findCmdStaffAccessRecord_(target);

  if (!account || account.role !== "CMD STAFF") {
    throw new Error("The account is not a CMD STAFF account.");
  }

  const sheet = getCmdStaffApprovalSheet_();
  const rows = sheet.getDataRange().getValues();

  for (let i = 1; i < rows.length; i++) {
    if (
      String(rows[i][0] || "").trim().toLowerCase() === target
    ) {
      const managementApproval = String(rows[i][1] || "PENDING")
        .trim()
        .toUpperCase();

      const ictApproval = String(rows[i][4] || "PENDING")
        .trim()
        .toUpperCase();

      return {
        managementApproval: managementApproval,
        managementApprover: String(rows[i][2] || ""),
        managementDate: rows[i][3] || "",
        ictApproval: ictApproval,
        ictApprover: String(rows[i][5] || ""),
        ictDate: rows[i][6] || "",

        // Either approval is sufficient.
        fullyApproved:
          managementApproval === "APPROVED" ||
          ictApproval === "APPROVED"
      };
    }
  }

  return {
    managementApproval: "PENDING",
    managementApprover: "",
    managementDate: "",
    ictApproval: "PENDING",
    ictApprover: "",
    ictDate: "",
    fullyApproved: false
  };
}


function setCmdStaffApproval(
  targetEmail,
  approve,
  approvalType,
  idToken
) {
  const user = verifyFirebaseUser_(idToken);

  const type = String(approvalType || "")
    .trim()
    .toUpperCase();

  if (
    type === "MANAGEMENT" &&
    user.accessLevel !== "MANAGEMENT"
  ) {
    throw new Error(
      "Only Management can change Management approval."
    );
  }

  if (
    type === "ICT" &&
    user.accessLevel !== "ICT ADMINISTRATOR"
  ) {
    throw new Error(
      "Only ICT Administrator can change ICT approval."
    );
  }

  if (type !== "MANAGEMENT" && type !== "ICT") {
    throw new Error("Invalid approval type.");
  }

  const target = String(targetEmail || "")
    .trim()
    .toLowerCase();

  const account = findCmdStaffAccessRecord_(target);

  if (
    !account ||
    account.role !== "CMD STAFF" ||
    account.status !== "ACTIVE"
  ) {
    throw new Error(
      "Target must be an active CMD STAFF account."
    );
  }

  const sheet = getCmdStaffApprovalSheet_();
  const lock = LockService.getScriptLock();

  lock.waitLock(10000);

  try {
    const rows = sheet.getDataRange().getValues();
    let rowNumber = -1;

    for (let i = 1; i < rows.length; i++) {
      if (
        String(rows[i][0] || "").trim().toLowerCase() === target
      ) {
        rowNumber = i + 1;
        break;
      }
    }

    if (rowNumber === -1) {
      rowNumber = sheet.getLastRow() + 1;
      sheet.getRange(rowNumber, 1).setValue(target);
    }

    const approved = approve === true;
    const status = approved ? "APPROVED" : "REVOKED";
    const now = new Date();

    if (type === "MANAGEMENT") {
      // Ensure Management and ICT approvals are from different accounts.
      const ictApprover = String(
        sheet.getRange(rowNumber, 6).getValue() || ""
      )
        .trim()
        .toLowerCase();

      if (
        approved &&
        ictApprover &&
        ictApprover === user.email
      ) {
        throw new Error(
          "Management and ICT approvals must be granted by different accounts."
        );
      }

      sheet.getRange(rowNumber, 2, 1, 3).setValues([[
        status,
        user.email,
        now
      ]]);

    } else {
      const managementApprover = String(
        sheet.getRange(rowNumber, 3).getValue() || ""
      )
        .trim()
        .toLowerCase();

      if (
        approved &&
        managementApprover &&
        managementApprover === user.email
      ) {
        throw new Error(
          "Management and ICT approvals must be granted by different accounts."
        );
      }

      sheet.getRange(rowNumber, 5, 1, 3).setValues([[
        status,
        user.email,
        now
      ]]);
    }

    recordHRAudit_(
      approved
        ? "CMD STAFF APPROVAL GRANTED"
        : "CMD STAFF APPROVAL REVOKED",
      "",
      "Target: " + target + "; Approval type: " + type,
      "SUCCESS",
      idToken
    );

    return {
      success: true,
      approval: status,
      approvalType: type
    };

  } finally {
    lock.releaseLock();
  }
}


function getCmdStaffApprovalCandidates(idToken) {
  const user = verifyFirebaseUser_(idToken);

  if (
    !["MANAGEMENT", "ICT ADMINISTRATOR"].includes(
      user.accessLevel
    )
  ) {
    throw new Error(
      "You are not authorised to manage CMD STAFF approvals."
    );
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.ACCESS_SHEET
  );

  if (!sheet) {
    throw new Error(
      "HR USER ACCESS sheet was not found."
    );
  }

  const records = sheet.getDataRange().getValues();
  const candidates = [];

  for (let i = 1; i < records.length; i++) {
    const name = String(records[i][0] || "").trim();
    const email = String(records[i][1] || "")
      .trim()
      .toLowerCase();
    const role = String(records[i][2] || "")
      .trim()
      .toUpperCase();
    const department = String(records[i][3] || "").trim();
    const status = String(records[i][4] || "")
      .trim()
      .toUpperCase();

    if (
      role === "CMD STAFF" &&
      status === "ACTIVE" &&
      email
    ) {
      candidates.push({
        name: name,
        email: email,
        department: department
      });
    }
  }

  return candidates;
}


function setupCmdStaffApprovalSheet() {
  getCmdStaffApprovalSheet_();
}

function updateStaffRecordByCMD(oracleID, data, idToken) {
  const user = verifyFirebaseUser_(idToken);

  if (user.accessLevel !== "CMD STAFF") {
    throw new Error(
      "Only CMD STAFF can use this function."
    );
  }

  // Approval is checked before and immediately before updating.
  assertCmdStaffFullyApproved_(user.email);

  const searchID = String(oracleID || "").trim();

  if (!searchID) {
    throw new Error("Oracle ID is required.");
  }

  if (
    !data ||
    typeof data !== "object" ||
    Array.isArray(data)
  ) {
    throw new Error("Invalid staff data submitted.");
  }

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

  const sheet = ss.getSheetByName(
    HR_PORTAL_CONFIG.STAFF_SHEET
  );

  if (!sheet) {
    throw new Error("Staff database not found.");
  }

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

  try {
    // Recheck approval immediately before modifying the record.
    assertCmdStaffFullyApproved_(user.email);
    // Require an active temporary editing grant.
    const grantSheet = getCmdStaffEditGrantSheet_();
    const grantRows = grantSheet.getDataRange().getValues();

    let grantRowNumber = -1;

    for (let i = 1; i < grantRows.length; i++) {
      const grantEmail = String(grantRows[i][0] || "")
        .trim()
        .toLowerCase();

      const grantStatus = String(grantRows[i][1] || "")
        .trim()
        .toUpperCase();

      const expiryDate = grantRows[i][4];

      if (
        grantEmail === user.email &&
        grantStatus === "ACTIVE" &&
        expiryDate instanceof Date &&
        expiryDate.getTime() > new Date().getTime()
      ) {
        grantRowNumber = i + 1;
        break;
      }
    }

    if (grantRowNumber < 0) {
      throw new Error(
        "Temporary editing access is not active, has expired, or has already been used. Please request access."
      );
    }
    const records = sheet.getDataRange().getValues();

    if (records.length < 2) {
      throw new Error(
        "No staff records are available."
      );
    }

    const headers = records[0];

    const normalize = value =>
      String(value || "")
        .trim()
        .replace(/\s+/g, " ")
        .toUpperCase();

    const findColumn = header =>
      headers.findIndex(
        h => normalize(h) === normalize(header)
      );

    const oracleColumn = findColumn("ORACLE ID");

    if (oracleColumn < 0) {
      throw new Error(
        "ORACLE ID column was not found."
      );
    }

    let targetRow = -1;

    for (let i = 1; i < records.length; i++) {
      if (
        String(records[i][oracleColumn]).trim() === searchID
      ) {
        targetRow = i + 1;
        break;
      }
    }

    if (targetRow < 0) {
      throw new Error("Staff record not found.");
    }

    // Only these fields can be changed by CMD STAFF.
    const allowedFields = {
      fullName: "FULL NAME (SURNAME FIRST)",
      staffNumber: "COMMISSION FILE NUMBER",
      dob: "DATE OF BIRTH",
      firstPost: "POST OF FIRST APPOINTMENT/GRADE LEVEL",
      firstAppointment: "DATE OF FIRST APPOINTMENT",
      confirmationDate: "DATE OF CONFIRMATION",
      presentGradeDate: "DATE OF PRESENT APPOINTMENT/GRADE LEVEL",
      deploymentDate: "DATE DEPLOYED TO PRESENT LGA / LCDA",
      professionalQualification: "PROFESSIONAL QUALIFICATION",
      phoneNumber: "PHONE NUMBER",
      emailAddress: "EMAIL ADDRESS",
      designation: "POST OF PRESENT APPOINTMENT",
      cadre: "CADRE",
      stateOrigin: "STATE OF ORIGIN",
      gradeLevel: "GRADE LEVEL",
      presentLGA: "PRESENT LGA / LCDA",
      employmentStatus: "CURRENT EMPLOYMENT STATUS",
      gender: "GENDER",
      qualification: "EDUCATIONAL QUALIFICATION",
      lashmaNumber: "LASHMA NUMBER",
      residentialAddress: "RESIDENTIAL ADDRESS",
      exitRetirementDate: "EXIT / RETIREMENT DATE (IF APPLICABLE)",
      oldEmploymentStatus: "OLD EMPLOYMENT STATUS",
      postWithGradeLevel: "POST WITH GRADE LEVEL",
      presentAppointmentGrade: "POST OF PRESENT APPOINTMENT/GRADE LEVEL"
    };

    const updates = [];

    Object.keys(allowedFields).forEach(key => {
      if (
        !Object.prototype.hasOwnProperty.call(data, key)
      ) {
        return;
      }

      // Update both present appointment columns together.
      if (key === "designation") {
        const column1 = findColumn(
          "POST OF PRESENT APPOINTMENT"
        );

        const column2 = findColumn(
          "POST OF PRESENT APPOINTMENT/GRADE LEVEL"
        );

        if (column1 < 0 || column2 < 0) {
          throw new Error(
            "Present appointment columns were not found."
          );
        }

        updates.push({
          column: column1 + 1,
          value: data[key]
        });

        updates.push({
          column: column2 + 1,
          value: data[key]
        });

        return;
      }

      const column = findColumn(allowedFields[key]);

      if (column < 0) {
        if (key === "emailAddress") {
          updates.push({
            column: 15,
            value: data[key]
          });

          return;
        }

        throw new Error(
          "Staff database column not found: " +
          allowedFields[key]
        );
      }

      updates.push({
        column: column + 1,
        value: data[key]
      });
    });

    if (updates.length === 0) {
      throw new Error(
        "No editable staff fields were submitted."
      );
    }

    updates.forEach(item => {
      sheet
        .getRange(targetRow, item.column)
        .setValue(item.value);
    });
    // Consume the temporary grant after the record is saved.
grantSheet.getRange(grantRowNumber, 2).setValue("USED");
grantSheet.getRange(grantRowNumber, 6).setValue(new Date());

    recordHRAudit_(
      "CMD STAFF RECORD UPDATE",
      searchID,
      "Updated " + updates.length + " staff field(s).",
      "SUCCESS",
      idToken
    );

    return {
      success: true,
      message: "Staff record updated successfully.",
      oracleID: searchID
    };

  } finally {
    lock.releaseLock();
  }
}