package ConsultancyAssignment;

import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;

import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import RevalERP_HRMS.basesetup.BaseSetup;
import RevalERP_HRMS.elements.ConsultancyAssignment_Elements;
import RevalERP_HRMS.excels.Excels;
import RevalERP_HRMS.utils.CommonUtils;

public class ConsultancyAssignment_AddFunctionality extends BaseSetup {

	public Sheet sheet1;
	public ConsultancyAssignment_Elements Elements;
	public WebDriverWait wait;
	public int attempts = 0;
	public int maxAttempts = 3;
	public int i;

	@BeforeClass
	public void setUp() throws Throwable {
		// openbrowser();
		CommonUtils.ModuleName = "ConsultancyAssignment_AddFunctionality";
		driver = getDriver();
		driver.manage().window().maximize();
		driver.get(baseUrl);
		CommonUtils.Reports("ConsultancyAssignment_AddFunctionality.html", "All Modules");
		sheet1 = CommonUtils.readExcellSheet(Excels.filepath2 + "Consultancy Assignment_TestData.xls", 0);
		Elements = PageFactory.initElements(driver, ConsultancyAssignment_Elements.class);
		CommonUtils.login();
		wait = new WebDriverWait(driver, Duration.ofSeconds(20));
	}

	@Test(priority = 1)
	public void NavigateAddConsultancyPage_Tc_01() throws IOException {
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // while(attempts<maxAttempts) {
		try {

			try {
				if (Elements.HRMS.isDisplayed()) {
					CommonUtils.scrollTOElement(Elements.HRMS, driver);
					CommonUtils.Thread_Sleep(2);
					CommonUtils.JS_Click(driver, Elements.HRMS);
					CommonUtils.captureScreenshot_pass(driver, "TC_001",
							"Home page Hrms Main modules is visable and clickable also");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_001",
						"Home page Hrms Main modules is  not visable and unable clickable also");

			}
			CommonUtils.Thread_Sleep(2);
			try {
				if (Elements.Requisition.isDisplayed()) {
					CommonUtils.scroll_down(driver);
					CommonUtils.JS_Click(driver, Elements.Requisition);
					CommonUtils.captureScreenshot_pass(driver, "TC_002",
							"Inside the  HRMS -Requisition section is displayed and click able alos");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_002",
						"Inside the  HRMS -Requisition section is  not displayed and unable to click able alos");

			}
			CommonUtils.Thread_Sleep(3);
			wait.until(ExpectedConditions.visibilityOf(Elements.ConsultancyAssignment_Module));
			CommonUtils.JS_Click(driver, Elements.ConsultancyAssignment_Module);
			CommonUtils.Thread_Sleep(3);

			// break;
		} catch (Exception e2) {

			// attempts++;
			// if (attempts==maxAttempts) {
			// throw e2;
		}
		// }
	}

	@Test(priority = 2)
	public void ListpageFunctionalilty() throws Exception {
		List<WebElement> formElements = Arrays.asList(Elements.ConsultancyAssignment_Title, Elements.SearchWord,
				Elements.FromDate, Elements.ToDate, Elements.SubmitButton, Elements.JobCode_Gride,
				Elements.PositionTitle_Gride, Elements.ResumeUploaded_Gride, Elements.Created_UpdatedBY_Gride,
				Elements.Status_Gride, Elements.DownalodJD_Gride);

		// Friendly names for each field (matching order)
		List<String> elementNames = Arrays.asList("Consultancy Assignment Title", "Search Word", "From Date ",
				" To Date ", "Submit", "Job Code Gride", "Created By / Updated By ", "Position Title Gride",
				"Resumes Uploaded Gride", "Status", "Download JD Gride");

		// Loop through and verify each element
		// Check visibility for each element
		for (int i = 0; i < formElements.size(); i++) {
			WebElement element = formElements.get(i);
			String name = elementNames.get(i);

			if (element.isDisplayed()) {
				System.out.println("✅ " + name + " is displayed. TC_NAV_01,TC_CA_LIST_01,2 Pass");
			} else {
				throw new Exception("❌ " + name + " is NOT displayed.TC_NAV_01 ,TC_CA_LIST_01,2Fail");
			}
		}

		String ListPageJobCode = Elements.ListPageRecord_JobCode.getText();
		System.out.println("Job Code :- " + ListPageJobCode);

		try {
			if (Elements.SearchWord.isDisplayed()) {
				Elements.SearchWord.click();
				Elements.SearchWord.sendKeys(ListPageJobCode);

				if (Elements.SubmitButton.isDisplayed()) {
					CommonUtils.Thread_Sleep(2); // Wait for 2 seconds before clicking submit
					Elements.SubmitButton.click();

					// Wait for the page to update and fetch the Job Code after filtering
					String ListPageJobCode_AfterFetched = Elements.ListPageRecord_JobCode.getText();
					System.out.println("Job Code After Filter :- " + ListPageJobCode_AfterFetched);

					// Compare the Job Codes properly using equals() method
					if (ListPageJobCode.equals(ListPageJobCode_AfterFetched)) {
						CommonUtils.captureScreenshot_pass(driver, "TC_NVA_02",
								"On the Consultancy Assignment list page, user-filtered Job Code records are showing in tabular format.");
					} else {
						CommonUtils.captureScreenshot_fail(driver, "TC_NVA_02",
								"Filtered Job Code did not match on the Consultancy Assignment list page.");
					}
				}
			}
		} catch (Exception E) {
			// Capture a screenshot if any exception occurs
			CommonUtils.captureScreenshot_fail(driver, "TC_NVA_02",
					"An error occurred while filtering Job Code on the Consultancy Assignment list page.");
			E.printStackTrace(); // It's good practice to log the error for debugging
		}
		CommonUtils.Thread_Sleep(2);
		try {
			// Step 1: Capture partial job code (test data)
			String partialJobCode = "JD-2025";

			// Step 2: Ensure SearchWord input is visible and interactable
			if (Elements.SearchWord.isDisplayed()) {
				Elements.SearchWord.click();
				Elements.SearchWord.clear(); // Clear previous input
				Elements.SearchWord.sendKeys(partialJobCode);

				// Step 3: Click Submit
				if (Elements.SubmitButton.isDisplayed()) {
					CommonUtils.Thread_Sleep(2); // Wait for UI update
					Elements.SubmitButton.click();

					// Step 4: Locate all Job Code cells in the filtered table
					List<WebElement> jobCodeResults = driver
							.findElements(By.xpath("//*[@class='table-responsive']/table/tbody/tr/td[1]")); // Make sure
																											// this
																											// XPath
																											// points to
																											// the Job
																											// Code
																											// column

					boolean allMatch = true;

					// Step 5: Validate each job code
					if (!jobCodeResults.isEmpty()) {
						System.out.println("✅ Total Job Code Records Found: " + jobCodeResults.size());

						for (int i = 0; i < jobCodeResults.size(); i++) {
							WebElement jobCodeElement = jobCodeResults.get(i);
							String jobCodeText = jobCodeElement.getText().trim();

							System.out.println("Record " + (i + 1) + ": " + jobCodeText);

							if (!jobCodeText.contains(partialJobCode)) {
								System.out.println("❌ Mismatch found at record " + (i + 1));
								allMatch = false;
								break;
							}
						}

						// Step 6: Result reporting
						if (allMatch) {
							CommonUtils.captureScreenshot_pass(driver, "TC_TC_NAV_03",
									"✅ All filtered records contain partial Job Code: " + partialJobCode);
						} else {
							CommonUtils.captureScreenshot_fail(driver, "TC_TC_NAV_03",
									"❌ One or more filtered records do NOT contain the partial Job Code: "
											+ partialJobCode);
						}

					} else {
						// No rows found after search
						CommonUtils.captureScreenshot_fail(driver, "TC_TC_NAV_03",
								"❌ No Job Code records found on the list page after searching with: " + partialJobCode);
					}
				}
			}
		} catch (Exception e) {
			CommonUtils.captureScreenshot_fail(driver, "TC_TC_NAV_03",
					"❌ Exception occurred during partial Job Code search.");
			e.printStackTrace();
		}

		String PositionRecords = Elements.ListPageRecord_position.getText();
		System.out.println("PositionRecords :- " + PositionRecords);

		try {
			if (Elements.SearchWord.isDisplayed()) {
				Elements.SearchWord.click();
				Elements.SearchWord.sendKeys(PositionRecords);

				if (Elements.SubmitButton.isDisplayed()) {
					CommonUtils.Thread_Sleep(2); // Wait for 2 seconds before clicking submit
					Elements.SubmitButton.click();
					try {
						if (Elements.ListPageRecord_JobCode.isDisplayed()) {
							// Wait for the page to update and fetch the Job Code after filtering
							String PositionRecords_AfterFetched = Elements.ListPageRecord_position.getText();
							System.out.println("position Code After Filter :- " + PositionRecords_AfterFetched);

							// Compare the Job Codes properly using equals() method
							if (ListPageJobCode.equals(PositionRecords_AfterFetched)) {
								CommonUtils.captureScreenshot_pass(driver, "TC_NVA_04",
										"On the Consultancy Assignment list page, user-filtered Job Code records are showing in tabular format.");
							} else {
								CommonUtils.captureScreenshot_fail(driver, "TC_NVA_04",
										"Filtered Job Code did not match on the Consultancy Assignment list page.");
							}
						}
					} catch (Exception E) {
						CommonUtils.captureScreenshot_pass(driver, "TC_NVA_04",
								"Correctly Search field Functionality Postion based data was not feching");
					}
				}
			}
		} catch (Exception E) {
			// Capture a screenshot if any exception occurs
			CommonUtils.captureScreenshot_fail(driver, "TC_NVA_04",
					"An error occurred while filtering postion  Code on the Consultancy Assignment list page.");
			E.printStackTrace(); // It's good practice to log the error for debugging
		}

		try {
			Elements.SearchWord.click();
			Elements.SearchWord.sendKeys(CommonUtils.generateRandomString(9));
			Elements.SubmitButton.click();
			if (Elements.NoRecords.isDisplayed()) {
				CommonUtils.captureScreenshot_pass(driver, "TC_NVA_04", "No records text message should displayed");
			}
		} catch (Exception E) {
			CommonUtils.captureScreenshot_fail(driver, "TC_NVA_04", "No records text message shouldn't displayed");

		}
		CommonUtils.Thread_Sleep(2);
		for (int i = 1; i <= 6; i++) {

			driver.navigate().refresh();
			CommonUtils.Thread_Sleep(4);
			String testCaseID = "TC_NVA_05_" + i;
			try {
				AssertJUnit.assertTrue(Elements.SearchWord.isDisplayed());
				Elements.SearchWord.click();
				Elements.SearchWord.sendKeys(CommonUtils.getExcellData(i, 1, sheet1));
			} catch (Exception e) {
				System.out.println("search Field not Displaying");
			}
			try {
				AssertJUnit.assertTrue(Elements.SubmitButton.isDisplayed());
				Elements.SubmitButton.click();
			} catch (Exception e) {
				System.out.println("Submit not Displaying");
			}
			try {
				if (driver.findElement(By.xpath("//*[text()='" + CommonUtils.getExcellData(i, 2, sheet1) + "']"))
						.isDisplayed()) {
					CommonUtils.captureScreenshot_pass(driver, "TC_NVA_05." + testCaseID, "Validation is Working");
					System.out.println("Pass");
				}
			} catch (Exception e) {
				CommonUtils.captureScreenshot_fail(driver, "TC_NVA_05." + testCaseID, "Validation is not Working");
				System.out.println("fail");
			}
		}
			driver.navigate().refresh();
			CommonUtils.Thread_Sleep(4);
			try {
				if (Elements.SearchWord.isDisplayed()) {
					// Input 1000-character remark from Excel
					String search = CommonUtils.getExcellData(1, 7, sheet1);
					Elements.SearchWord.clear();
					Elements.SearchWord.sendKeys(search);

					// Get text length from the field to validate max limit
					String enteredText = Elements.SearchWord.getAttribute("value");
					int enteredLength = enteredText.length();

					if (enteredLength == 64) {
						CommonUtils.captureScreenshot_pass(driver, "TC_NVA_05_10",
								"search Text field correctly accepted 64 characters.");
						System.out.println("TC_NVA_05_10 - Pass: Field accepted exactly 64 characters.");
					} else {
						CommonUtils.captureScreenshot_fail(driver, "TC_NVA_05_10",
								"search Text field did not accept 64 characters. Entered: " + enteredLength);
						System.out.println("TC_NVA_05_10 - Fail: Entered characters = " + enteredLength);
					}
				} else {
					CommonUtils.captureScreenshot_fail(driver, "TC_NVA_05_10",
							"search Text field is not displayed on the page.");
					System.out.println("TC_NVA_05_10 - Fail: Field not visible.");
				}
			} catch (Exception e) {
				CommonUtils.captureScreenshot_fail(driver, "TC_117",
						"Exception occurred while validating 64-character limit in Remark field: " + e.getMessage());
				e.printStackTrace();
			}
		}
	

	@Test(priority = 3)
	public void DatePickerFunctionality() throws Exception {
		driver.navigate().refresh();
		CommonUtils.Thread_Sleep(3);
		try {
			if (Elements.FromDate.isDisplayed()) {
				Elements.FromDate.click();
				CommonUtils.Thread_Sleep(3);

				List<WebElement> allMonthss1 = driver
						.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
				System.out.println(CommonUtils.getCurrentDay());
				String day = CommonUtils.getCurrentDay();
				List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
				date.get(date.size() - 1).click();
				CommonUtils.Thread_Sleep(3);
				CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.FromDate, "StartDateField",
						"Today Date Selected, TC_NAV_06", "Today Date not Selected ");
				if (Elements.SubmitButton.isDisplayed()) {
					if (Elements.ListPageRecord_JobCode.isDisplayed()) {
						CommonUtils.captureScreenshot_pass(driver, "TC_NAV_06",
								"Consultancy Assignment page  user selected data records are getting correctly");
					}
				} else {
					CommonUtils.captureScreenshot_pass(driver, "TC_NAV_06",
						"Consultancy Assignment page  user selected data records are not  getting correctly/ user selected data range records are unavialable");

				}

			}
		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {

			Elements.FromDate.click();
			CommonUtils.Thread_Sleep(3);

			List<WebElement> allMonthss1 = driver
					.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
			System.out.println(CommonUtils.getCurrentDatePlus(2));
			String day = CommonUtils.getCurrentDatePlus(2);
			List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
			date.get(date.size() - 1).click();
			CommonUtils.Thread_Sleep(3);
			CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.FromDate, "StartDateField",
					"Future Date Selected, TC_NAV_07_01", "Future Date not Selected, TC_NAV_07_01");

		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {

			Elements.FromDate.click();
			CommonUtils.Thread_Sleep(3);

			List<WebElement> allMonthss1 = driver
					.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
			System.out.println(CommonUtils.getCurrentDateLess(2));
			String day = CommonUtils.getCurrentDateLess(2);
			List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
			date.get(date.size() - 1).click();
			CommonUtils.Thread_Sleep(3);
			CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.FromDate, "StartDateField",
					"Past Date Selected, TC_NAV_07_02", "Past Date not Selected, TC_NAV_07_02");

		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		// ----------------------------
		try {
			if (Elements.ToDate.isDisplayed()) {
				Elements.ToDate.click();
				CommonUtils.Thread_Sleep(3);

				List<WebElement> allMonthss1 = driver
						.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
				System.out.println(CommonUtils.getCurrentDay());
				String day = CommonUtils.getCurrentDay();
				List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
				date.get(date.size() - 1).click();
				CommonUtils.Thread_Sleep(3);
				CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.ToDate, "TODate Date Picker",
						"Today Date Selected,TC_NAV_07_03", "Today Date not Selected,TC_NAV_07_03");

			}
		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {

			Elements.ToDate.click();
			CommonUtils.Thread_Sleep(3);

			List<WebElement> allMonthss1 = driver
					.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
			System.out.println(CommonUtils.getCurrentDatePlus(2));
			String day = CommonUtils.getCurrentDatePlus(2);
			List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
			date.get(date.size() - 1).click();
			CommonUtils.Thread_Sleep(3);
			CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.ToDate, "StartDateField",
					"Future Date Selected,TC_NAV_07_04", "Future Date not Selected,TC_NAV_07_04");

		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {

			Elements.ToDate.click();
			CommonUtils.Thread_Sleep(3);

			List<WebElement> allMonthss1 = driver
					.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
			System.out.println(CommonUtils.getCurrentDateLess(2));
			String day = CommonUtils.getCurrentDateLess(2);
			List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
			date.get(date.size() - 1).click();
			CommonUtils.Thread_Sleep(3);
			CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.ToDate, "StartDateField",
					"Past Date Selected,TC_NAV_07_05", "Past Date not Selected,TC_NAV_07_06");

		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		driver.navigate().refresh();
		CommonUtils.Thread_Sleep(2);
		try {
			if (Elements.FromDate.isDisplayed()) {
				Elements.FromDate.click();
				CommonUtils.Thread_Sleep(3);

				List<WebElement> allMonthss1 = driver
						.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
				System.out.println(CommonUtils.getCurrentDay());
				String day = CommonUtils.getCurrentDay();
				List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
				date.get(date.size() - 1).click();
				CommonUtils.Thread_Sleep(3);
				CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.FromDate, "StartDateField",
						"Today Date Selected", "Today Date not Selected");

			}
		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {

			Elements.ToDate.click();
			CommonUtils.Thread_Sleep(3);

			List<WebElement> allMonthss1 = driver
					.findElements(By.xpath("(//*[@class='xdsoft_calendar'])[last()]/table/tbody/tr/td"));
			System.out.println(CommonUtils.getCurrentDateLess(2));
			String day = CommonUtils.getCurrentDateLess(2);
			List<WebElement> date = driver.findElements(By.xpath("(//*[text()='" + day + "'])"));
			date.get(date.size() - 1).click();
			CommonUtils.Thread_Sleep(3);
			CommonUtils.CaptureScreenshot_for_IsDisplayed(driver, Elements.ToDate, "StartDateField",
					"Past Date Selected", "Past Date not Selected");

		} catch (Exception E) {
			System.out.println("unable to selected Date picker");
		}
		try {
			if (Elements.SubmitButton.isDisplayed()) {
				Elements.SubmitButton.click();
				if (Elements.FromDateConntbeToDate_ValidationMessage.isDisplayed()) {
					CommonUtils.captureScreenshot_pass(driver, "TC_NAV_07_07",
							"From date can't be greater than to date. Validation should displayed");
				}
			}
		} catch (Exception E) {
			CommonUtils.captureScreenshot_fail(driver, "TC_NAV_07_07",
					"From date can't be greater than to date. Validation message shouldn't displayed");

		}
	}

	@Test(priority = 4)
	public void ModifyConsultancyAssignmentFunctionality() throws Exception {
		driver.navigate().refresh();
		CommonUtils.Thread_Sleep(4);
		try {
		if(Elements.ListPageRecord_JobCode.isDisplayed()) {
			CommonUtils.Thread_Sleep(2);
			Elements.ListPageRecord_JobCode.click();
			if(Elements.ModifyConsultanceAssignment_Title.isDisplayed()) {
				CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_05", "Modify Consultance Assignment page should be displayed");
			}
		}
	}catch(Exception E) {
		CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_05", "Modify Consultance Assignment page shouldn't be displayed");

	}
		List<WebElement> formElements = Arrays.asList(
	            Elements.ModifyConsultanceAssignment_Title,
	            Elements.JobCode_Field,
	            Elements.JobDescription_Field,
	            Elements.ConsultanceDropdownfield,
	            Elements.CancelButton,
	            Elements.SaveButton
	        );

	        // Friendly names for each field (matching order)
	        List<String> elementNames = Arrays.asList(
	            "Modify Consultancy Assignment Title",
	            "Job Code-Disable Mode",
	            "Job Description-Text field -Disable Mode",
	            "Consultance Dropdown field ",
	            "Cancel Button",
	            "Save "
	            
	        );

        // Loop through and verify each element
	        // Check visibility for each element
	        for (int i = 0; i < formElements.size(); i++) {
	            WebElement element = formElements.get(i);
	            String name = elementNames.get(i);


	            if (element.isDisplayed()) {
	                System.out.println("✅ " + name + " is displayed. TC_MOD_CA_05_01 Pass");
	            } else {
	                throw new Exception("❌ " + name + " is NOT displayed.TC_MOD_CA_05_01 Fail");
	            }
	        }
	                try {
	                	String testCaseID="TC_MOD_CA_7";
	                    // Step 1: Open the dropdown
	                    WebElement dropdown = wait.until(ExpectedConditions.visibilityOf(Elements.ConsultanceDropdownfield));
	                    dropdown.click();
	                    System.out.println("🔽 Dropdown opened successfully.");

	                    // Step 2: Enter consultancy name in search field
	                    WebElement searchField = wait.until(ExpectedConditions.visibilityOf(Elements.ConsultanceDropdownfield_SearchField));
	                    searchField.click();
	                    //searchField.clear();
	                    searchField.sendKeys(CommonUtils.getExcellData(3, 1, sheet1));
	                    System.out.println("🔍 Searched for consultancy: " + CommonUtils.getExcellData(3, 1, sheet1));

	                    // Step 3: Wait for matching checkbox and click if not already selected
	                    WebElement checkbox = wait.until(ExpectedConditions.visibilityOf(Elements.ConsultanceDropdownfield_SearchField_CheckBox));

	                    if (!checkbox.isSelected()) {
	                        checkbox.click();
	                        System.out.println("☑️ Consultancy checkbox selected: " + CommonUtils.getExcellData(3, 1, sheet1));
	                    } else {
	                        System.out.println("ℹ️ Consultancy already selected: " + CommonUtils.getExcellData(3, 1, sheet1));
	                    }

	                    CommonUtils.captureScreenshot_pass(driver, testCaseID,
	                        "✅ Consultancy '" + CommonUtils.getExcellData(3, 1, sheet1) + "' selected successfully.");

	                } catch (TimeoutException te) {
	                    System.err.println("⏱️ Timeout: Element not found for consultancy: " + CommonUtils.getExcellData(3, 1, sheet1));
	                    CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_7",
	                        "❌ Timeout while selecting consultancy: " + CommonUtils.getExcellData(3, 1, sheet1));
	                } catch (Exception e) {
	                    System.err.println("❌ Error while selecting consultancy: " + CommonUtils.getExcellData(3, 1, sheet1));
	                    e.printStackTrace();
	                    CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_7",
	                        "❌ Exception occurred while selecting consultancy: " + CommonUtils.getExcellData(3, 1, sheet1));
	                }

	                try {
	                	if(Elements.SaveButton.isDisplayed()    ) {
	                		Elements.SaveButton.click();
	                		CommonUtils.Thread_Sleep(1);
	                		if(Elements.SuccessMessage.isDisplayed()) {
	                			CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_7.1", "Success message should displayed ");
	                		}
	                	}
	                	}catch(Exception E) {
                			CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_7.1", "Success message shouldn't displayed ");

	                	}
	        		List<WebElement> formElements1 = Arrays.asList(
	        	            Elements.ResumeUpload_History_Title,
	        	            Elements.ResumeUpload_History_SharedOn_Gride,
	        	            Elements.ResumeUpload_History_Consultant_Gride,
	        	            Elements.ResumeUpload_History_CreatedUpdatedBy_Gride,
	        	            Elements.ResumeUpload_History_SharingMethaod_Gride,
	        	            Elements.ResumeUploaded_Gride
	        	        );

	        	        // Friendly names for each field (matching order)
	        	        List<String> elementNames1 = Arrays.asList(
	        	            "Resume Upload History Title",
	        	            "Shared On",
	        	            "Consultant",
	        	            "Sharing Method",
	        	            "Resumes Uploaded",
	        	            "Created By / Updated By "
	        	            
	        	        );

	                // Loop through and verify each element
	        	        // Check visibility for each element
	        	        for (int i = 0; i < formElements1.size(); i++) {
	        	            WebElement element = formElements1.get(i);
	        	            String name = elementNames1.get(i);


	        	            if (element.isDisplayed()) {
	        	                System.out.println("✅ " + name + " is displayed. TC_MOD_CA_08,9 Pass");
	        	            } else {
	        	                throw new Exception("❌ " + name + " is NOT displayed.TC_MOD_CA_08,9 Fail");
	        	            }
	        	        }
	        	        String Consultanceinput = Elements.ResumeUpload_History_Consultance_InputRecords.getText();
	        	        System.out.println("📋 History Input: " + Consultanceinput);

	        	        try {
	        	            if (Consultanceinput != null && !Consultanceinput.trim().isEmpty()) {
	        	                CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_10", "✅ History data is populated correctly: " + Consultanceinput);
	        	            } else {
	        	                CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_10", "❌ History data is empty or null.");
	        	            }
	        	        } catch (Exception e) {
	        	            CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_10", "❌ Exception occurred while validating history data.");
	        	            e.printStackTrace();
	        	        }
	        	        CommonUtils.Thread_Sleep(4);
	        	        try {
	        	            // Step 1: Wait for and click the dropdown field
	        	            if (Elements.ConsultanceDropdownfield.isDisplayed()) {
	        	                Elements.ConsultanceDropdownfield.click();

	        	                // Step 2: Check if the checkbox container is visible
	        	                if (Elements.SelectAll_CheckBox.isDisplayed()) {

	        	                    // Step 3: Check and click the 'Select All' checkbox if not already selected
	        	                    if (!Elements.SelectAll_CheckBox.isSelected()) {
	        	                        Elements.SelectAll_CheckBox.click();
	        	                        Elements.SelectAll_CheckBox.click();

	        	                        CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_05_02",
	        	                            "✅ 'Select All' checkbox clicked - all consultancies un-selected successfully on Modify Consultancy Assignment page.");
	        	                    } else {
	        	                        CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_05_02",
	        	                            "ℹ️ 'Select All' checkbox was already selected  and Agin un selected");
	        	                    }
	        	                } else {
	        	                    CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_05_02",
	        	                        "❌ Consultancy checkboxes not visible inside dropdown.");
	        	                }
	        	            } else {
	        	                CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_05_02",
	        	                    "❌ Consultancy dropdown is not visible.");
	        	            }

	        	        } catch (Exception e) {
	        	            CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_05_02",
	        	                "❌ Exception occurred while trying to select all consultancies.");
	        	            e.printStackTrace();
	        	        }
	        	        try {
		                	if(Elements.SaveButton.isDisplayed()    ) {
		                		Elements.SaveButton.click();
		                		CommonUtils.Thread_Sleep(1);
		                		if(Elements.SuccessMessage.isDisplayed()) {
		                			CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_7.1", "Success message should displayed ");
		                		}
		                	}
		                	}catch(Exception E) {
	                			CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_7.1", "Success message shouldn't displayed ");

		                	}
	        	        CommonUtils.Thread_Sleep(4);
	        	        try {
	        	        	if(Elements.CancelButton.isDisplayed()) {
	        	        		Elements.CancelButton.click();
	        	        		CommonUtils.Thread_Sleep(2);
	        	        		if(Elements.CancelButton_ContionueButton.isDisplayed())
	        	        			CommonUtils.Thread_Sleep(2);
	        	        		Elements.CancelButton_ContionueButton.click();
	        	        		
	        	        		CommonUtils.Thread_Sleep(3);
	        	        		if(Elements.ConsultancyAssignment_Title.isDisplayed()) {
	        	        			CommonUtils.captureScreenshot_pass(driver, "TC_MOD_CA_11", "ConsultancyAssignment_Title should displayed successfully");
	        	        		}
	        	        	}
	        	        }catch(Exception E) {
	        	        	CommonUtils.captureScreenshot_fail(driver, "TC_MOD_CA_11", "Cancel button is not working correctly ");
	        	        }
}
}

