You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1524 lines
56 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. <!DOCTYPE html>
  2. <html lang="en" dir="ltr" xmlns:th="http://www.thymeleaf.org">
  3. <head th:replace="~{fragments/modules/base/head :: head}">
  4. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  5. <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/css/select2.min.css" rel="stylesheet" />
  6. </head>
  7. <style>
  8. .select2-container--default .select2-selection--multiple {
  9. padding-right: 30px;
  10. min-height: 38px;
  11. display: flex;
  12. flex-wrap: wrap;
  13. align-items: center;
  14. position: relative;
  15. background-image: none;
  16. }
  17. .select2-container--default .select2-selection--multiple::after {
  18. content: "";
  19. position: absolute;
  20. top: 50%;
  21. right: 8px;
  22. width: 14px;
  23. height: 14px;
  24. transform: translateY(-50%);
  25. background-image: url("data:image/svg+xml;utf8,<svg fill='gray' height='20' viewBox='0 0 24 24' width='20' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");
  26. background-repeat: no-repeat;
  27. background-size: contain;
  28. pointer-events: none;
  29. }
  30. /* Override for larger screens (desktops) */
  31. /* @media (min-width: 992px) {
  32. #drinkingWaterTableContainer {
  33. padding: 236px;
  34. margin-top: -233px;
  35. }
  36. }*/
  37. </style>
  38. <body>
  39. <div class="container mt-4">
  40. <header th:replace="~{fragments/modules/base/header :: header}"></header>
  41. <div th:replace="~{fragments/modules/base/menu :: menu}"></div>
  42. <div class="card p-3">
  43. <div class="card-header">
  44. <b>Drinking Water</b>
  45. </div>
  46. <!-- Table Container for Displaying Saved Data -->
  47. <div id="drinkingWaterTableContainer" style="display: none; padding: 15px;">
  48. <table class="table table-bordered">
  49. <tbody>
  50. <tr>
  51. <th>Water Sources</th>
  52. <td id="view_water_sources"></td>
  53. <th>Water Supply Types</th>
  54. <td id="view_water_supply_types"></td>
  55. </tr>
  56. <tr>
  57. <th>Purifier Available</th>
  58. <td id="view_purifier"></td>
  59. <th>Purifier Capacity</th>
  60. <td id="view_purifier_capacity"></td>
  61. </tr>
  62. <tr>
  63. <th>Borewell Available</th>
  64. <td id="view_borewell"></td>
  65. <th>No. of Borewells</th>
  66. <td id="view_borewell_count"></td>
  67. </tr>
  68. <tr>
  69. <th>Storage Available</th>
  70. <td id="view_storage"></td>
  71. <th>Storage Types & Capacities</th>
  72. <td id="view_storage_details"></td>
  73. </tr>
  74. </tbody>
  75. </table>
  76. <div class="text-center">
  77. <button class="btn btn-primary" id="editDrinkingBtn">Update</button>
  78. </div>
  79. </div>
  80. <!-- your existing form rows -->
  81. <div class="form-section">
  82. <!-- your existing form rows -->
  83. <div class="row" style="padding: 5px;">
  84. <div class="col-md-8 form-group">
  85. <label for="water_sources" class="form-label fw-bold">Source of Water <span
  86. class="text-danger">*</span></label>
  87. <div id="water_sources_container" class="row gx-4 gy-2"></div>
  88. </div>
  89. </div>
  90. <br>
  91. <div id="waterSupplyContainer" class="row" style="gap: 10px;"></div>
  92. <div class="row" style="padding: 5px;">
  93. <div class="col-md-4 form-group">
  94. <label>Water Purifying Facility Available <span
  95. class="text-danger">*</span></label>
  96. <div class="radio-group">
  97. <input type="radio" name="water_purifier_available" id="purifier_yes"
  98. value="1"> Yes
  99. <input type="radio" name="water_purifier_available" id="purifier_no"
  100. value="0"> No
  101. </div>
  102. </div>
  103. <div class="col-md-4 form-group" id="purifier_capacity_container"
  104. style="display: none;">
  105. <label for="purifier_capacity">Capacity Of Purifier (Liters) <span
  106. class="text-danger">*</span></label>
  107. <input type="text" id="purifier_capacity" name="purifier_capacity"
  108. class="form-control" placeholder="Enter Capacity Of Purifier" />
  109. </div>
  110. </div>
  111. <div class="row" style="padding: 5px;">
  112. <!-- <div class="col-md-4 form-group">
  113. <label>Borwell Status <span class="text-danger">*</span></label>
  114. <div class="radio-group">
  115. <input type="radio" name="borwell_status_available"
  116. id="borwell_status_yes" value="1"> Yes
  117. <input type="radio" name="borwell_status_available"
  118. id="borwell_status_no" value="0"> No
  119. </div>
  120. </div> -->
  121. <div class="col-md-4 form-group" id="borwell_status_container"
  122. style="display: none;">
  123. <label for="no_of_borwells">No.of Borewells <span
  124. class="text-danger">*</span></label>
  125. <input type="number" id="no_of_borwells" name="no_of_borwells"
  126. class="form-control" placeholder="Enter no Of Borwells" />
  127. </div>
  128. </div>
  129. <div class="row" style="padding: 5px;">
  130. <div class="col-md-4 form-group">
  131. <label>Storage Status <span class="text-danger">*</span></label>
  132. <div class="radio-group">
  133. <input type="radio" name="storage_status" id="storage_yes" value="1">
  134. Yes
  135. <input type="radio" name="storage_status" id="storage_no" value="0"> No
  136. </div>
  137. </div>
  138. </div>
  139. <div class="row" id="storage_type_container" style="display: none; padding: 5px;">
  140. <div class="col-md-4 form-group">
  141. <label for="storage_types" class="form-label fw-bold">Type of Storage for
  142. Drinking Water <span class="text-danger">*</span></label>
  143. <select id="storage_types" class="form-control" multiple="multiple"
  144. style="width: 100%;"></select>
  145. </div>
  146. </div>
  147. <div class="row" id="storage_capacity_container" style="padding: 5px;"></div>
  148. <div class="row" style="padding: 5px;">
  149. <div class="col-md-12 form-group">
  150. <div class="card-footer text-center">
  151. <button type="submit" class="btn btn-primary"
  152. id="drinkingWaterSubmitBtn"><i
  153. class="ik ik-save"></i>Submit</button>
  154. <button type="reset" class="btn btn-secondary mr-2" id="resetButton"><i
  155. class="ik ik-refresh-cw"></i>Reset</button>
  156. </div>
  157. </div>
  158. </div>
  159. <!-- Wrap ends here -->
  160. </div>
  161. </div>
  162. <!-- Modal (Editable Form) -->
  163. <div class="modal fade" id="drinkingWaterModal" tabindex="-1" aria-labelledby="drinkingWaterModalLabel"
  164. aria-hidden="true">
  165. <div class="modal-dialog modal-lg">
  166. <div class="modal-content">
  167. <div class="modal-header">
  168. <h5 class="modal-title">Update Drinking Water Details</h5>
  169. <button type="button" class="close" data-bs-dismiss="modal"
  170. aria-label="Close"><span aria-hidden="true">&times;</span></button>
  171. </div>
  172. <div class="modal-body">
  173. <form id="editDrinkingWaterForm">
  174. </form>
  175. </div>
  176. <div class="modal-footer">
  177. <button class="btn btn-primary" id="saveDrinkingwaterModalUpdate">Save Changes</button>
  178. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
  179. </div>
  180. </div>
  181. </div>
  182. </div>
  183. <script th:replace="~{fragments/modules/base/script :: script}"></script>
  184. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
  185. <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0/dist/js/select2.min.js"></script>
  186. <script>
  187. $(document).ready(function () {
  188. const urlParams = new URLSearchParams(window.location.search);
  189. const schoolId = urlParams.get("schoolId");
  190. document.getElementById('no_of_borwells').addEventListener('input', function () {
  191. this.value = this.value.replace(/[^0-9]/g, '');
  192. if (parseInt(this.value) < 0) {
  193. this.value = '';
  194. }
  195. });
  196. $('#storage_types').select2({
  197. placeholder: "Select Storage Type",
  198. minimumResultsForSearch: Infinity,
  199. closeOnSelect: false
  200. });
  201. $('#storage_types').on('select2:opening', function () {
  202. setTimeout(() => {
  203. $('.select2-search__field').prop('readonly', true);
  204. }, 0);
  205. });
  206. $(document).on('input', '#purifier_capacity', function () {
  207. let value = $(this).val();
  208. // Allow only digits and at most one decimal point
  209. let cleaned = value.replace(/[^0-9.]/g, ''); // Remove anything that's not digit or dot
  210. cleaned = cleaned.replace(/(\..*?)\..*/g, '$1'); // Allow only one dot
  211. $(this).val(cleaned);
  212. });
  213. loadWaterSources();
  214. function loadWaterSources() {
  215. $.ajax({
  216. url: '/gcc/api/gccschool/dropdown/getWaterSource',
  217. method: 'GET',
  218. success: function (response) {
  219. console.log(response.data);
  220. $('#water_sources_container').empty();
  221. if (response.status === "OK") {
  222. window.allWaterSources = response.data;
  223. response.data.forEach(item => {
  224. $('#water_sources_container').append(`
  225. <div class="col-auto">
  226. <div class="form-check form-check-inline me-3">
  227. <input class="form-check-input water-source-checkbox me-2 " type="checkbox" value="${item.source_water_id}" data-label="${item.water_type}" id="water_source_${item.source_water_id}">
  228. <label class="form-check-label" for="water_source_${item.source_water_id}" style="margin-bottom: 0;">${item.water_type}</label>
  229. </div>
  230. </div>
  231. `);
  232. });
  233. }
  234. }
  235. });
  236. }
  237. loadDrinkingWaterTable();
  238. function loadDrinkingWaterTable() {
  239. $.ajax({
  240. url: "/gcc/api/gccschool/schoolproperty/checkWaterDetails",
  241. method: "GET",
  242. cache: false,
  243. data: {school_id: schoolId},
  244. success: function (res) {
  245. console.log("Drinking Water API Response:", res);
  246. const d = res?.DrinkingWater || res[0]?.DrinkingWater;
  247. const sources = res?.WaterSource || res[0]?.WaterSource || [];
  248. const storage = res?.WaterStorage || res[0]?.WaterStorage || [];
  249. window.modalDrinkingData = {
  250. drinking_water_id: d.drinking_water_id, // ✅ Add this line
  251. purifier: d.is_purifier == 1 ? 'Yes' : 'No',
  252. purifier_capacity: d.purifier_capacity || '',
  253. borewell: d.is_borewell == 1 ? 'Yes' : 'No',
  254. borewell_count: d.borewell_count || '',
  255. storage: d.is_storage == 1 ? 'Yes' : 'No',
  256. storageDetails: storage.map(s => `${s.storage_type}: ${s.capacity} L`).join('<br>')
  257. };
  258. window.modalDrinkingRawResponse = res;
  259. if (d && Object.keys(d).length > 0) {
  260. $('#view_purifier').text(d.is_purifier == 1 ? 'Yes' : 'No');
  261. $('#view_purifier_capacity').text(d.purifier_capacity || '-');
  262. $('#view_borewell').text(d.is_borewell == 1 ? 'Yes' : 'No');
  263. $('#view_borewell_count').text(d.borewell_count || '-');
  264. $('#view_storage').text(d.is_storage == 1 ? 'Yes' : 'No');
  265. const sourceNames = sources.map(w => w.water_type).join(', ');
  266. const sourceTypes = sources.map(w => `${w.water_type}: ${w.supply_type}`).join('<br>');
  267. $('#view_water_sources').text(sourceNames || '-');
  268. $('#view_water_supply_types').html(sourceTypes || '-');
  269. if (d.is_storage == 1 && storage && storage.length > 0) {
  270. const storageText = storage.map(s => `${s.storage_type}: ${s.capacity} L`).join('<br>');
  271. $('#view_storage_details').html(storageText);
  272. } else {
  273. $('#view_storage_details').text('-');
  274. }
  275. $('#drinkingWaterTableContainer').show();
  276. $('.form-section').hide(); // ✅ Hides the entire form
  277. } else {
  278. $('#drinkingWaterTableContainer').hide();
  279. $('.form-section').show(); // ✅ Shows the form if no data
  280. }
  281. },
  282. error: function () {
  283. console.warn("No Drinking Water data found for school_id", schoolId);
  284. $('#drinkingWaterTableContainer').hide();
  285. $('#drinkingWaterSubmitBtn').closest('.row').show();
  286. }
  287. });
  288. }
  289. $(document).on('change', '#editDrinkingWaterForm input[name="water_purifier_available"]', function () {
  290. if ($('#editDrinkingWaterForm #purifier_yes').is(':checked')) {
  291. $('#editDrinkingWaterForm #purifier_capacity_container').show();
  292. } else {
  293. $('#editDrinkingWaterForm #purifier_capacity_container').hide();
  294. // $('#editDrinkingWaterForm #purifier_capacity').val('');
  295. }
  296. });
  297. $(document).on('change', '#editDrinkingWaterForm input[name="borwell_status_available"]', function () {
  298. if ($('#editDrinkingWaterForm #borwell_status_yes').is(':checked')) {
  299. $('#editDrinkingWaterForm #borwell_status_container').show();
  300. } else {
  301. $('#editDrinkingWaterForm #borwell_status_container').hide();
  302. // $('#editDrinkingWaterForm #no_of_borwells').val('');
  303. }
  304. });
  305. $('#editDrinkingBtn').click(function () {
  306. const d = window.modalDrinkingData;
  307. const res = window.modalDrinkingRawResponse;
  308. const allSources = window.allWaterSources || []; // cache this globally after loading dropdown
  309. const selectedSources = res?.WaterSource || res[0]?.WaterSource || [];
  310. if ($('#storage_types').hasClass('select2-hidden-accessible')) {
  311. $('#storage_types').select2('destroy');
  312. }
  313. // Clone and inject form
  314. const formHtml = $('.form-section').html();
  315. $('#editDrinkingWaterForm').html(formHtml);
  316. $('#editDrinkingWaterForm').find('.card-footer').remove();
  317. $('#editDrinkingWaterForm #storage_types').select2({
  318. placeholder: "Select Storage Types",
  319. allowClear: false,
  320. minimumResultsForSearch: Infinity,
  321. closeOnSelect: false
  322. }).on('select2:opening', function () {
  323. setTimeout(() => {
  324. $('.select2-search__field').prop('readonly', true);
  325. }, 0);
  326. });
  327. const waterSourceContainer = $('#editDrinkingWaterForm #water_sources_container');
  328. const waterSupplyContainer = $('#editDrinkingWaterForm #waterSupplyContainer');
  329. waterSourceContainer.empty();
  330. waterSupplyContainer.empty();
  331. // Build all checkboxes and pre-select only saved ones
  332. allSources.forEach(source => {
  333. const { source_water_id, water_type } = source;
  334. const isChecked = selectedSources.some(s => s.source_water_id == source_water_id);
  335. const selected = selectedSources.find(s => s.source_water_id == source_water_id);
  336. const supply_type = selected?.supply_type || "";
  337. // Add checkbox
  338. waterSourceContainer.append(`
  339. <div class="col-auto">
  340. <div class="form-check form-check-inline me-3">
  341. <input class="form-check-input water-source-checkbox me-2"
  342. type="checkbox"
  343. value="${source_water_id}"
  344. data-label="${water_type}"
  345. id="edit_water_source_${source_water_id}"
  346. ${isChecked ? 'checked' : ''}>
  347. <label class="form-check-label" for="edit_water_source_${source_water_id}" style="margin-bottom: 0;">${water_type}</label>
  348. </div>
  349. </div>
  350. `);
  351. // If it's selected, show the supply type radios
  352. if (isChecked) {
  353. waterSupplyContainer.append(`
  354. <div class="col-md-3 mb-3" id="edit-water-supply-${source_water_id}">
  355. <label class="fw-bold d-block mb-2">${water_type} Type Of Water Supply <span class="text-danger">*</span></label>
  356. <div class="d-flex gap-4">
  357. <div class="form-check form-check-inline">
  358. <input class="form-check-input" type="radio" name="water_supply_${source_water_id}" value="Continious" ${supply_type === 'Continious' ? 'checked' : ''}>
  359. <label class="form-check-label">Continious</label>
  360. </div>
  361. <div class="form-check form-check-inline">
  362. <input class="form-check-input" type="radio" name="water_supply_${source_water_id}" value="Intermittent" ${supply_type === 'Intermittent' ? 'checked' : ''}>
  363. <label class="form-check-label">Intermittent</label>
  364. </div>
  365. </div>
  366. </div>
  367. `);
  368. }
  369. });
  370. // Prefill purifier
  371. if (d.purifier === 'Yes') {
  372. $('#editDrinkingWaterForm #purifier_yes').prop('checked', true);
  373. $('#editDrinkingWaterForm #purifier_capacity_container').show();
  374. $('#editDrinkingWaterForm #purifier_capacity').val(d.purifier_capacity);
  375. } else {
  376. $('#editDrinkingWaterForm #purifier_no').prop('checked', true);
  377. $('#editDrinkingWaterForm #purifier_capacity_container').hide();
  378. }
  379. // Borewell
  380. if (d.borewell === 'Yes') {
  381. $('#editDrinkingWaterForm #borwell_status_yes').prop('checked', true);
  382. $('#editDrinkingWaterForm #borwell_status_container').show();
  383. $('#editDrinkingWaterForm #no_of_borwells').val(d.borewell_count);
  384. } else {
  385. $('#editDrinkingWaterForm #borwell_status_no').prop('checked', true);
  386. $('#editDrinkingWaterForm #borwell_status_container').hide();
  387. }
  388. // Storage
  389. if (d.storage === 'Yes') {
  390. $('#editDrinkingWaterForm #storage_yes').prop('checked', true);
  391. $('#editDrinkingWaterForm #storage_type_container').show();
  392. fetchStorageTypes(() => {
  393. const storage = res?.WaterStorage || res[0]?.WaterStorage || [];
  394. const selectedIds = [];
  395. storage.forEach(s => {
  396. const storageType = s.storage_type?.trim();
  397. $('#editDrinkingWaterForm #storage_types option').each(function () {
  398. if ($(this).text().trim() === storageType) {
  399. selectedIds.push($(this).val());
  400. }
  401. });
  402. });
  403. $('#editDrinkingWaterForm #storage_types').val(selectedIds).trigger('change');
  404. setTimeout(() => {
  405. storage.forEach(s => {
  406. const storageType = s.storage_type?.trim();
  407. const capacity = s.capacity;
  408. $('#editDrinkingWaterForm #storage_types option').each(function () {
  409. if ($(this).text().trim() === storageType) {
  410. const id = $(this).val();
  411. $(`#editDrinkingWaterForm #capacity_${id}`).val(capacity);
  412. }
  413. });
  414. });
  415. }, 500);
  416. }, '#editDrinkingWaterForm #storage_types');
  417. } else {
  418. $('#editDrinkingWaterForm #storage_no').prop('checked', true);
  419. $('#editDrinkingWaterForm #storage_type_container').hide();
  420. $('#editDrinkingWaterForm #storage_capacity_container').empty();
  421. }
  422. new bootstrap.Modal(document.getElementById('drinkingWaterModal')).show();
  423. });
  424. $('#saveDrinkingwaterModalUpdate').click(function () {
  425. const drinkingWaterId = window.modalDrinkingData?.drinking_water_id;
  426. const form = $('#editDrinkingWaterForm');
  427. const schoolId = new URLSearchParams(window.location.search).get("schoolId");
  428. // 👉 You MUST set this somewhere when loading the edit modal
  429. //const drinkingWaterId = window.modalDrinkingData?.drinking_water_id; // ✅ corrected
  430. let water = [], waterError = false;
  431. form.find('.water-source-checkbox:checked').each(function () {
  432. const id = $(this).val();
  433. const supplyType = form.find(`input[name="water_supply_${id}"]:checked`).val();
  434. if (!supplyType) waterError = true;
  435. water.push({
  436. water_supply_id: 0, // placeholder, handled in backend
  437. source_water_id: parseInt(id),
  438. supply_type: supplyType
  439. });
  440. });
  441. if (waterError || water.length === 0) {
  442. return Swal.fire("Info", "Select supply type for all selected water sources.", "info");
  443. }
  444. const purifierValue = form.find('input[name="water_purifier_available"]:checked').val();
  445. if (!purifierValue) return Swal.fire("Info", "Select purifier availability.", "info");
  446. const purifierCapacity = purifierValue === '1' ? form.find('#purifier_capacity').val() : null;
  447. /*if (purifierValue === '1' && !purifierCapacity) {
  448. return Swal.fire("Info", "Enter purifier capacity.", "info");
  449. }*/
  450. if (purifierValue === '1') {
  451. if (!purifierCapacity || purifierCapacity <= 0) {
  452. return Swal.fire("Info", !purifierCapacity ? "Enter purifier capacity." : "Purifier capacity must be greater than 0.", "info");
  453. }
  454. }
  455. const isBorewell = form.find('.water-source-checkbox[data-label="Borewell"]').is(':checked') ? '1' : '0';
  456. const borewellCount = isBorewell === '1' ? form.find('#no_of_borwells').val() : null;
  457. if (isBorewell === '1') {
  458. if (!borewellCount || borewellCount <= 0) {
  459. return Swal.fire("Info", !borewellCount ? "Enter number of borewells." : "Number of borewells must be greater than 0.", "info");
  460. }
  461. }
  462. const storageValue = form.find('input[name="storage_status"]:checked').val();
  463. let storage = [], storageError = false;
  464. if (!storageValue) return Swal.fire("Info", "Select storage status.", "info");
  465. if (storageValue === '1') {
  466. const selected = form.find('#storage_types').val() || [];
  467. if (selected.length === 0) {
  468. return Swal.fire("Info", "Select type of storage.", "info");
  469. }
  470. selected.forEach(id => {
  471. const cap = form.find(`#capacity_${id}`).val();
  472. if (!cap || isNaN(cap) || parseFloat(cap) <= 0) {
  473. storageError = true;
  474. } else {
  475. storage.push({
  476. water_storage_id: 0, // placeholder
  477. storage_water_id: parseInt(id),
  478. capacity: parseFloat(cap)
  479. });
  480. }
  481. });
  482. }
  483. if (storageError) {
  484. return Swal.fire("Info", "Enter valid capacity for all selected storage types.", "info");
  485. }
  486. const updatePayload = {
  487. is_purifier: purifierValue === '1',
  488. purifier_capacity: purifierCapacity ? parseFloat(purifierCapacity) : null,
  489. is_borewell: isBorewell === '1',
  490. borewell_count: borewellCount ? parseInt(borewellCount) : 0,
  491. is_storage: storageValue === '1',
  492. drinking_water_id: parseInt(drinkingWaterId), // ✅ will no longer be NaN or undefined
  493. school_id: parseInt(schoolId),
  494. supply: water,
  495. storage: storage
  496. };
  497. console.log("Update payload:", updatePayload);
  498. $.ajax({
  499. url: '/gcc/api/gccschool/schoolproperty/updateDrinkingWater',
  500. type: 'POST',
  501. contentType: 'application/json',
  502. data: JSON.stringify(updatePayload),
  503. success: function (response) {
  504. let result = response;
  505. // If response is a string like "Success", convert it to an object manually
  506. if (typeof response === "string" && response.toLowerCase().includes("success")) {
  507. result = { status: "OK" };
  508. }
  509. if (result.status === "OK") {
  510. Swal.fire({
  511. icon: "success",
  512. title: "Success",
  513. text: "Drinking water details updated successfully!",
  514. allowOutsideClick: false,
  515. allowEscapeKey: false,
  516. allowEnterKey: false,
  517. showConfirmButton: true
  518. }).then(() => {
  519. $('#drinkingWaterModal').modal('hide');
  520. location.reload();
  521. });
  522. } else {
  523. Swal.fire({
  524. icon: "error",
  525. title: "Submission Failed",
  526. text: result.message || "Please try again.",
  527. allowOutsideClick: false,
  528. allowEscapeKey: false,
  529. allowEnterKey: false,
  530. showConfirmButton: true
  531. });
  532. }
  533. },
  534. error: function (xhr) {
  535. let errorMessage = "Something went wrong";
  536. try {
  537. // Try parsing as JSON
  538. const json = JSON.parse(xhr.responseText);
  539. if (json.message) {
  540. errorMessage = json.message;
  541. } else {
  542. errorMessage = JSON.stringify(json); // fallback if no message
  543. }
  544. } catch (e) {
  545. // If it's HTML or plain text
  546. if (typeof xhr.responseText === 'string') {
  547. // Detect if it's HTML and avoid showing it
  548. if (xhr.responseText.trim().startsWith('<!DOCTYPE')) {
  549. errorMessage = "Internal server error. Please contact support.";
  550. } else {
  551. errorMessage = xhr.responseText;
  552. }
  553. }
  554. }
  555. Swal.fire({
  556. icon: "error",
  557. title: "Error",
  558. text: errorMessage
  559. });
  560. }
  561. });
  562. });
  563. $(document).on('change', '.water-source-checkbox', function () {
  564. const id = $(this).val();
  565. const label = $(this).data('label');
  566. const container = $('#waterSupplyContainer');
  567. if ($(this).is(':checked')) {
  568. // Add supply type section if not already added
  569. if ($(`#water-supply-${id}`).length === 0) {
  570. container.append(`
  571. <div class="col-md-3 mb-3" id="water-supply-${id}">
  572. <label class="fw-bold d-block mb-2">${label} Type Of Water Supply <span class="text-danger">*</span></label>
  573. <div class="d-flex gap-4">
  574. <div class="form-check form-check-inline">
  575. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Continious" id="supply_${id}_1">
  576. <label class="form-check-label" for="supply_${id}_1">Continious</label>
  577. </div>
  578. <div class="form-check form-check-inline">
  579. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Intermittent" id="supply_${id}_2">
  580. <label class="form-check-label" for="supply_${id}_2">Intermittent</label>
  581. </div>
  582. </div>
  583. </div>
  584. `);
  585. }
  586. // ✅ Show borewell input if Borewell is selected
  587. if (label.toLowerCase().trim() === "borewell") {
  588. $('#borwell_status_container').show();
  589. }
  590. } else {
  591. // Remove corresponding water supply section
  592. $(`#water-supply-${id}`).remove();
  593. // ✅ Hide and clear borewell field if Borewell is deselected
  594. if (label.toLowerCase().trim() === "borewell") {
  595. $('#borwell_status_container').hide();
  596. $('#no_of_borwells').val('');
  597. }
  598. }
  599. });
  600. const previousSupplySelections = {};
  601. $(document).on('change', '#editDrinkingWaterForm .water-source-checkbox', function () {
  602. const id = $(this).val();
  603. const label = $(this).data('label');
  604. const container = $('#editDrinkingWaterForm #waterSupplyContainer');
  605. if ($(this).is(':checked')) {
  606. // Restore previous supply type from memory (if any)
  607. const selectedValue = previousSupplySelections[id] || '';
  608. if ($(`#edit-water-supply-${id}`).length === 0) {
  609. container.append(`
  610. <div class="col-md-3 mb-3" id="edit-water-supply-${id}">
  611. <label class="fw-bold d-block mb-2">${label} Type Of Water Supply <span class="text-danger">*</span></label>
  612. <div class="d-flex gap-4">
  613. <div class="form-check form-check-inline">
  614. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Continious" id="edit_supply_${id}_1">
  615. <label class="form-check-label" for="edit_supply_${id}_1">Continious</label>
  616. </div>
  617. <div class="form-check form-check-inline">
  618. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Intermittent" id="edit_supply_${id}_2">
  619. <label class="form-check-label" for="edit_supply_${id}_2">Intermittent</label>
  620. </div>
  621. </div>
  622. </div>
  623. `);
  624. // Preselect if available
  625. if (selectedValue) {
  626. $(`input[name="water_supply_${id}"][value="${selectedValue}"]`).prop('checked', true);
  627. }
  628. }
  629. if (/bore\s*-?\s*well/i.test(label)) {
  630. $('#editDrinkingWaterForm #borwell_status_container').show();
  631. }
  632. } else {
  633. // Save the selected value before removing it
  634. const selected = $(`input[name="water_supply_${id}"]:checked`).val();
  635. if (selected) {
  636. previousSupplySelections[id] = selected;
  637. }
  638. $(`#edit-water-supply-${id}`).remove();
  639. if (/bore\s*-?\s*well/i.test(label)) {
  640. $('#editDrinkingWaterForm #borwell_status_container').hide();
  641. }
  642. }
  643. });
  644. /*$(document).on('change', '#editDrinkingWaterForm .water-source-checkbox', function () {
  645. const id = $(this).val();
  646. const label = $(this).data('label');
  647. const container = $('#editDrinkingWaterForm #waterSupplyContainer');
  648. if ($(this).is(':checked')) {
  649. if ($(`#edit-water-supply-${id}`).length === 0) {
  650. container.append(`
  651. <div class="col-md-3 mb-3" id="edit-water-supply-${id}">
  652. <label class="fw-bold d-block mb-2">${label} Type Of Water Supply <span class="text-danger">*</span></label>
  653. <div class="d-flex gap-4">
  654. <div class="form-check form-check-inline">
  655. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Continious" id="edit_supply_${id}_1">
  656. <label class="form-check-label" for="edit_supply_${id}_1">Continious</label>
  657. </div>
  658. <div class="form-check form-check-inline">
  659. <input class="form-check-input" type="radio" name="water_supply_${id}" value="Intermittent" id="edit_supply_${id}_2">
  660. <label class="form-check-label" for="edit_supply_${id}_2">Intermittent</label>
  661. </div>
  662. </div>
  663. </div>
  664. `);
  665. }
  666. // ✅ Show Borewell count field if label matches "Borewell"
  667. if (/bore\s*-?\s*well/i.test(label)) {
  668. $('#editDrinkingWaterForm #borwell_status_container').show();
  669. }
  670. } else {
  671. $(`#edit-water-supply-${id}`).remove();
  672. if (/bore\s*-?\s*well/i.test(label)) {
  673. $('#editDrinkingWaterForm #borwell_status_container').hide();
  674. //$('#editDrinkingWaterForm #no_of_borwells').val('');
  675. }
  676. }
  677. });*/
  678. $('input[name="water_purifier_available"]').change(function () {
  679. if ($('#purifier_yes').is(':checked')) {
  680. $('#purifier_capacity_container').show();
  681. } else {
  682. $('#purifier_capacity_container').hide();
  683. $('#purifier_capacity').val(''); // Clear input when "No" or nothing is selected
  684. }
  685. });
  686. $('input[name="borwell_status_available"]').change(function () {
  687. if ($('#borwell_status_yes').is(':checked')) {
  688. $('#borwell_status_container').show();
  689. } else {
  690. $('#borwell_status_container').hide();
  691. $('#no_of_borwells').val(''); // Clear input when "No" or nothing is selected
  692. }
  693. });
  694. $('input[name="storage_status"]').change(function () {
  695. if ($('#storage_yes').is(':checked')) {
  696. $('#storage_type_container').show();
  697. $('#storage_capacity_container').show();
  698. // ✅ If options already loaded, just trigger change
  699. if (storageTypesLoaded) {
  700. $('#storage_types').trigger('change');
  701. } else {
  702. // First time loading storage types if not yet loaded
  703. fetchStorageTypes(function () {
  704. $('#storage_types').trigger('change');
  705. storageTypesLoaded = true;
  706. }, '#storage_types');
  707. }
  708. } else {
  709. $('#storage_type_container').hide();
  710. $('#storage_capacity_container').hide().empty();
  711. $('#storage_types').val(null).trigger('change');
  712. }
  713. });
  714. /*$('input[name="storage_status"]').change(function () {
  715. if ($('#storage_yes').is(':checked')) {
  716. $('#storage_type_container').show();
  717. //fetchStorageTypes();
  718. fetchStorageTypes(null, '#storage_types');
  719. } else {
  720. $('#storage_type_container').hide();
  721. $('#storage_capacity_container').empty();
  722. }
  723. });*/
  724. /*$(document).on('change', '#editDrinkingWaterForm input[name="storage_status"]', function () {
  725. if ($('#editDrinkingWaterForm #storage_yes').is(':checked')) {
  726. $('#editDrinkingWaterForm #storage_type_container').show();
  727. fetchStorageTypes(null, '#editDrinkingWaterForm #storage_types');
  728. } else {
  729. $('#editDrinkingWaterForm #storage_type_container').hide();
  730. $('#editDrinkingWaterForm #storage_capacity_container').empty();
  731. }
  732. });*/
  733. let storageTypesLoaded = false;
  734. fetchStorageTypes(function () {
  735. console.log("Storage types loaded initially.");
  736. storageTypesLoaded = true;
  737. }, '#storage_types');
  738. /* $(document).on('change', '#editDrinkingWaterForm input[name="storage_status"]', function () {
  739. const res = window.modalDrinkingRawResponse;
  740. const storageData = res?.WaterStorage || res[0]?.WaterStorage || [];
  741. if ($('#editDrinkingWaterForm #storage_yes').is(':checked')) {
  742. $('#editDrinkingWaterForm #storage_type_container').show();
  743. $('#editDrinkingWaterForm #storage_capacity_container').show();
  744. $('#editDrinkingWaterForm #storage_types').html(''); // clear dropdown
  745. fetchStorageTypes(function () {
  746. const $dropdown = $('#editDrinkingWaterForm #storage_types');
  747. const selectedIds = [];
  748. storageData.forEach(s => {
  749. const storageType = s.storage_type?.trim();
  750. $dropdown.find('option').each(function () {
  751. if ($(this).text().trim() === storageType) {
  752. selectedIds.push($(this).val());
  753. }
  754. });
  755. });
  756. $dropdown.val(selectedIds).trigger('change');
  757. setTimeout(() => {
  758. storageData.forEach(s => {
  759. const storageType = s.storage_type?.trim();
  760. const capacity = s.capacity;
  761. $dropdown.find('option').each(function () {
  762. if ($(this).text().trim() === storageType) {
  763. const id = $(this).val();
  764. if (!$(`#capacity_group_${id}`).length) {
  765. $('#editDrinkingWaterForm #storage_capacity_container').append(`
  766. <div class="col-md-4 form-group" id="capacity_group_${id}">
  767. <label>${storageType} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  768. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" value="${capacity}" placeholder="Enter Capacity (Liters)" required>
  769. </div>
  770. `);
  771. } else {
  772. $(`#capacity_${id}`).val(capacity);
  773. }
  774. }
  775. });
  776. });
  777. }, 300);
  778. }, '#editDrinkingWaterForm #storage_types');
  779. } else {
  780. $('#editDrinkingWaterForm #storage_type_container').hide();
  781. $('#editDrinkingWaterForm #storage_capacity_container').hide().empty();
  782. $('#editDrinkingWaterForm #storage_types').val(null).trigger('change');
  783. }
  784. }); */
  785. // Inside your $(document).ready(function () { ... });
  786. $(document).on('change', '#editDrinkingWaterForm input[name="storage_status"]', function () {
  787. const res = window.modalDrinkingRawResponse;
  788. const storageData = res?.WaterStorage || res[0]?.WaterStorage || [];
  789. const $dropdown = $('#editDrinkingWaterForm #storage_types');
  790. const $capacityContainer = $('#editDrinkingWaterForm #storage_capacity_container');
  791. if ($('#editDrinkingWaterForm #storage_yes').is(':checked')) {
  792. $('#editDrinkingWaterForm #storage_type_container').show();
  793. $capacityContainer.show();
  794. fetchStorageTypes(function () {
  795. const selectedIds = [];
  796. storageData.forEach(s => {
  797. const storageType = s.storage_type?.trim();
  798. $dropdown.find('option').each(function () {
  799. if ($(this).text().trim() === storageType) {
  800. selectedIds.push($(this).val());
  801. }
  802. });
  803. });
  804. $dropdown.val(selectedIds).trigger('change');
  805. // Wait for dropdown to be populated, then fill values
  806. setTimeout(() => {
  807. storageData.forEach(s => {
  808. const storageType = s.storage_type?.trim();
  809. const capacity = s.capacity;
  810. $dropdown.find('option').each(function () {
  811. if ($(this).text().trim() === storageType) {
  812. const id = $(this).val();
  813. if (!$(`#editDrinkingWaterForm #capacity_group_${id}`).length) {
  814. $capacityContainer.append(`
  815. <div class="col-md-4 form-group" id="capacity_group_${id}">
  816. <label>${storageType} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  817. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" value="${capacity}" placeholder="Enter Capacity (Liters)" required>
  818. </div>
  819. `);
  820. } else {
  821. // Important: Don't overwrite user modified values
  822. const currentVal = $(`#capacity_${id}`).val();
  823. if (!currentVal || parseFloat(currentVal) <= 0) {
  824. $(`#capacity_${id}`).val(capacity);
  825. }
  826. }
  827. }
  828. });
  829. });
  830. }, 300);
  831. }, '#editDrinkingWaterForm #storage_types');
  832. } else {
  833. $('#editDrinkingWaterForm #storage_type_container').hide();
  834. $capacityContainer.hide();
  835. // ❗ DO NOT empty container here, preserve previous fields
  836. }
  837. });
  838. /* function fetchStorageTypes() {
  839. $.ajax({
  840. url: '/gcc/api/gccschool/dropdown/getWaterStorage',
  841. method: 'GET',
  842. success: function (response) {
  843. $('#storage_types').empty();
  844. if (response.status === "OK") {
  845. response.data.forEach(item => {
  846. $('#storage_types').append(`<option value="${item.storage_water_id}" data-label="${item.storage_type}">${item.storage_type}</option>`);
  847. });
  848. $('#storage_types').select2({placeholder: "Select Storage Types", allowClear: true});
  849. }
  850. }
  851. });
  852. }*/
  853. function fetchStorageTypes(callback, dropdownSelector = '#storage_types') {
  854. $.ajax({
  855. url: '/gcc/api/gccschool/dropdown/getWaterStorage',
  856. method: 'GET',
  857. success: function (response) {
  858. const $dropdown = $(dropdownSelector);
  859. $dropdown.empty(); // Clear previous options
  860. if (response.status === "OK" && Array.isArray(response.data)) {
  861. response.data.forEach(item => {
  862. $dropdown.append(`<option value="${item.storage_water_id}" data-label="${item.storage_type}">${item.storage_type}</option>`);
  863. });
  864. $dropdown.select2({
  865. placeholder: "Select Storage Types",
  866. allowClear: false,
  867. minimumResultsForSearch: Infinity,
  868. closeOnSelect: false
  869. });
  870. if (typeof callback === "function") {
  871. callback();
  872. }
  873. }
  874. },
  875. error: function () {
  876. console.error("Failed to fetch storage types.");
  877. if (typeof callback === "function") {
  878. callback();
  879. }
  880. }
  881. });
  882. }
  883. /*$('#storage_types').on('change', function () {
  884. $('#storage_capacity_container').empty();
  885. $('#storage_types option:selected').each(function () {
  886. const id = $(this).val();
  887. const label = $(this).data('label');
  888. $('#storage_capacity_container').append(`
  889. <div class="col-md-4 form-group" id="capacity_group_${id}">
  890. <label>${label} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  891. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" placeholder="Enter Capacity (Liters)" required>
  892. </div>`);
  893. });
  894. });*/
  895. $('#storage_types').on('change', function () {
  896. const selected = $(this).val() || [];
  897. const container = $('#storage_capacity_container');
  898. // Step 1: Remove any capacity group not in selected list
  899. container.find('.form-group').each(function () {
  900. const id = $(this).attr('id')?.replace('capacity_group_', '');
  901. if (!selected.includes(id)) {
  902. $(this).remove(); // ❌ Remove only unselected
  903. }
  904. });
  905. // Step 2: Add any newly selected items if not already present
  906. $(this).find('option:selected').each(function () {
  907. const id = $(this).val();
  908. const label = $(this).data('label');
  909. // Add only if it doesn't already exist
  910. if (!container.find(`#capacity_group_${id}`).length) {
  911. container.append(`
  912. <div class="col-md-4 form-group" id="capacity_group_${id}">
  913. <label>${label} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  914. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" placeholder="Enter Capacity (Liters)" required>
  915. </div>
  916. `);
  917. }
  918. });
  919. });
  920. $(document).on('change', '#editDrinkingWaterForm #storage_types', function () {
  921. const selected = $(this).val() || [];
  922. const container = $('#editDrinkingWaterForm #storage_capacity_container');
  923. // Remove capacity groups not in selected
  924. container.find('.form-group').each(function () {
  925. const id = $(this).attr('id')?.replace('capacity_group_', '');
  926. if (!selected.includes(id)) {
  927. $(this).remove();
  928. }
  929. });
  930. // Add new selected
  931. $(this).find('option:selected').each(function () {
  932. const id = $(this).val();
  933. const label = $(this).data('label');
  934. if (!container.find(`#capacity_group_${id}`).length) {
  935. container.append(`
  936. <div class="col-md-4 form-group" id="capacity_group_${id}">
  937. <label>${label} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  938. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" placeholder="Enter Capacity (Liters)" required>
  939. </div>
  940. `);
  941. }
  942. });
  943. });
  944. /*$(document).on('change', '#editDrinkingWaterForm #storage_types', function () {
  945. const selected = $(this).val() || [];
  946. const container = $('#editDrinkingWaterForm #storage_capacity_container');
  947. // Step 1: Remove capacity fields that are no longer selected
  948. container.find('.form-group').each(function () {
  949. const id = $(this).attr('id')?.replace('capacity_group_', '');
  950. if (!selected.includes(id)) {
  951. $(this).remove(); // ❌ Only remove what is unselected
  952. }
  953. });
  954. // Step 2: Add capacity fields for newly selected items
  955. $(this).find('option:selected').each(function () {
  956. const id = $(this).val();
  957. const label = $(this).data('label');
  958. if (!container.find(`#capacity_group_${id}`).length) {
  959. container.append(`
  960. <div class="col-md-4 form-group" id="capacity_group_${id}">
  961. <label>${label} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  962. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" placeholder="Enter Capacity (Liters)" required>
  963. </div>
  964. `);
  965. }
  966. });
  967. });
  968. $(document).on('change', '#editDrinkingWaterForm #storage_types', function () {
  969. const $container = $('#editDrinkingWaterForm #storage_capacity_container');
  970. $container.empty(); // clear previous
  971. $('#editDrinkingWaterForm #storage_types option:selected').each(function () {
  972. const id = $(this).val();
  973. const label = $(this).data('label');
  974. $container.append(`
  975. <div class="col-md-4 form-group" id="capacity_group_${id}">
  976. <label>${label} Capacity Of Storage (Liters) <span class="text-danger">*</span></label>
  977. <input type="number" class="form-control storage-capacity" id="capacity_${id}" name="capacity_${id}" placeholder="Enter Capacity (Liters)" required>
  978. </div>
  979. `);
  980. });
  981. });*/
  982. $('#resetButton').click(function () {
  983. $('input[type="text"], input[type="number"]').val('');
  984. $('input[type="radio"]').prop('checked', false);
  985. $('select').val(null).trigger('change');
  986. $('#purifier_capacity_container').hide();
  987. $('#borwell_status_container').hide();
  988. $('#storage_type_container').hide();
  989. $('#storage_capacity_container').empty();
  990. $('#waterSupplyContainer').empty();
  991. });
  992. $('#drinkingWaterSubmitBtn').click(function (e) {
  993. e.preventDefault();
  994. let water = [], waterError = false;
  995. $('.water-source-checkbox:checked').each(function () {
  996. const id = $(this).val();
  997. const supplyType = $(`input[name="water_supply_${id}"]:checked`).val();
  998. if (!supplyType) waterError = true;
  999. water.push({source_water_id: parseInt(id), supply_type: supplyType});
  1000. });
  1001. /*if (waterError || water.length === 0) {
  1002. return Swal.fire({ icon: 'info', title: 'Info', text: 'Please select supply type for all selected water sources.' });
  1003. }
  1004. const isPurifier = $('input[name="water_purifier_available"]:checked').val();
  1005. if (!isPurifier) return Swal.fire({ icon: 'info', title: 'Info', text: 'Please select water purifier availability.' });
  1006. const purifierCapacity = isPurifier === '1' ? $('#purifier_capacity').val() : null;
  1007. if (isPurifier === '1' && !purifierCapacity) return Swal.fire({ icon: 'info', title: 'Info', text: 'Enter Capacity for Purifier.' });
  1008. const isBorewell = $('input[name="borwell_status_available"]:checked').val();
  1009. if (!isBorewell) return Swal.fire({ icon: 'info', title: 'Info', text: 'Please select Borewell Status.' });
  1010. const borewellCount = isBorewell === '1' ? $('#no_of_borwells').val() : null;
  1011. if (isBorewell === '1' && !borewellCount) return Swal.fire({ icon: 'info', title: 'Info', text: 'Enter No of Borewells.' });
  1012. const isStorage = $('input[name="storage_status"]:checked').val();
  1013. let storage = [], storageError = false;
  1014. if (isStorage === '1') {
  1015. const selected = $('#storage_types').val();
  1016. if (!selected.length) return Swal.fire({ icon: 'info', title: 'Info', text: 'Please select Type of Storage.' });
  1017. selected.forEach(id => {
  1018. const capacity = $(`#capacity_${id}`).val();
  1019. if (!capacity) storageError = true;
  1020. storage.push({ storage_water_id: parseInt(id), capacity: parseFloat(capacity) });
  1021. });
  1022. if (storageError) return Swal.fire({ icon: 'info', title: 'Info', text: 'Please enter capacity for all selected storage types.' });
  1023. }*/
  1024. if (waterError || water.length === 0) {
  1025. return Swal.fire({
  1026. icon: 'info',
  1027. title: 'Info',
  1028. text: 'Please select supply type for all selected water sources.',
  1029. allowOutsideClick: false,
  1030. allowEscapeKey: false,
  1031. allowEnterKey: false,
  1032. showConfirmButton: true
  1033. });
  1034. }
  1035. const isPurifier = $('input[name="water_purifier_available"]:checked').val();
  1036. if (!isPurifier) {
  1037. return Swal.fire({
  1038. icon: 'info',
  1039. title: 'Info',
  1040. text: 'Please select water purifier availability.',
  1041. allowOutsideClick: false,
  1042. allowEscapeKey: false,
  1043. allowEnterKey: false,
  1044. showConfirmButton: true
  1045. });
  1046. }
  1047. const purifierCapacity = isPurifier === '1' ? $('#purifier_capacity').val() : null;
  1048. /*if (isPurifier === '1' && !purifierCapacity && purifierCapacity <=0 ) {
  1049. return Swal.fire({
  1050. icon: 'info',
  1051. title: 'Info',
  1052. text: 'Enter Capacity for Purifier.',
  1053. allowOutsideClick: false,
  1054. allowEscapeKey: false,
  1055. allowEnterKey: false,
  1056. showConfirmButton: true
  1057. });
  1058. }*/
  1059. /*if (isPurifier === '1') {
  1060. if (!purifierCapacity || purifierCapacity <= 0) {
  1061. return Swal.fire({
  1062. icon: 'info',
  1063. title: 'Info',
  1064. text: 'Enter Capacity for Purifier and greater than 0.',
  1065. allowOutsideClick: false,
  1066. allowEscapeKey: false,
  1067. allowEnterKey: false,
  1068. showConfirmButton: true
  1069. });
  1070. }
  1071. }*/
  1072. if (isPurifier === '1') {
  1073. if (!purifierCapacity || purifierCapacity <= 0) {
  1074. return Swal.fire({
  1075. icon: 'info',
  1076. title: 'Info',
  1077. text: !purifierCapacity ? 'Enter Capacity for Purifier.' : 'Capacity for Purifier must be greater than 0.',
  1078. allowOutsideClick: false,
  1079. allowEscapeKey: false,
  1080. allowEnterKey: false,
  1081. showConfirmButton: true
  1082. });
  1083. }
  1084. }
  1085. /*if (purifierCapacity <=0 ) {
  1086. return Swal.fire({
  1087. icon: 'info',
  1088. title: 'Info',
  1089. text: ' Capacity for Purifier must be greater than 0.',
  1090. allowOutsideClick: false,
  1091. allowEscapeKey: false,
  1092. allowEnterKey: false,
  1093. showConfirmButton: true
  1094. });
  1095. }*/
  1096. const isBorewell = $('input[data-label="Borewell"]').is(':checked') ? '1' : '0';
  1097. if (!isBorewell) {
  1098. return Swal.fire({
  1099. icon: 'info',
  1100. title: 'Info',
  1101. text: 'Please select Borewell Status.',
  1102. allowOutsideClick: false,
  1103. allowEscapeKey: false,
  1104. allowEnterKey: false,
  1105. showConfirmButton: true
  1106. });
  1107. }
  1108. const borewellCount = isBorewell === '1' ? $('#no_of_borwells').val() : null;
  1109. if (isBorewell === '1') {
  1110. if (!borewellCount || borewellCount <= 0) {
  1111. return Swal.fire({
  1112. icon: 'info',
  1113. title: 'Info',
  1114. text: !borewellCount ? 'Enter No of Borewells.' : 'No of Borewells must be greater than 0.'
  1115. });
  1116. }
  1117. }
  1118. /* if (isBorewell === '1') {
  1119. if (!borewellCount || borewellCount <= 0) {
  1120. return Swal.fire({
  1121. icon: 'info',
  1122. title: 'Info',
  1123. text: 'Enter No of Borewells and greater than 0.',
  1124. allowOutsideClick: false,
  1125. allowEscapeKey: false,
  1126. allowEnterKey: false,
  1127. showConfirmButton: true
  1128. });
  1129. }
  1130. }*/
  1131. /* if (isBorewell === '1' && !borewellCount) {
  1132. return Swal.fire({
  1133. icon: 'info',
  1134. title: 'Info',
  1135. text: 'Enter No of Borewells.',
  1136. allowOutsideClick: false,
  1137. allowEscapeKey: false,
  1138. allowEnterKey: false,
  1139. showConfirmButton: true
  1140. });
  1141. }
  1142. if (borewellCount <=0 ) {
  1143. return Swal.fire({
  1144. icon: 'info',
  1145. title: 'Info',
  1146. text: ' Borewells must be greater than 0.',
  1147. allowOutsideClick: false,
  1148. allowEscapeKey: false,
  1149. allowEnterKey: false,
  1150. showConfirmButton: true
  1151. });
  1152. }*/
  1153. const isStorage = $('input[name="storage_status"]:checked').val();
  1154. let storage = [], storageError = false;
  1155. // Step 1: Check if Storage status is selected
  1156. if (!isStorage) {
  1157. return Swal.fire({
  1158. icon: 'info',
  1159. title: 'Info',
  1160. text: 'Please select Storage Status.',
  1161. allowOutsideClick: false,
  1162. allowEscapeKey: false,
  1163. allowEnterKey: false,
  1164. showConfirmButton: true
  1165. });
  1166. }
  1167. // Step 2: If "Yes", validate selected storage types and capacity
  1168. if (isStorage === '1') {
  1169. const selectedTypes = $('#storage_types').val();
  1170. if (!selectedTypes || selectedTypes.length === 0) {
  1171. return Swal.fire({
  1172. icon: 'info',
  1173. title: 'Info',
  1174. text: 'Please select Type of Storage.',
  1175. allowOutsideClick: false,
  1176. allowEscapeKey: false,
  1177. allowEnterKey: false,
  1178. showConfirmButton: true
  1179. });
  1180. }
  1181. selectedTypes.forEach(id => {
  1182. const capacity = $(`#capacity_${id}`).val();
  1183. if (!capacity || isNaN(capacity) || parseFloat(capacity) <= 0) {
  1184. storageError = true;
  1185. } else {
  1186. storage.push({
  1187. storage_water_id: parseInt(id),
  1188. capacity: parseFloat(capacity)
  1189. });
  1190. }
  1191. });
  1192. if (storageError ) {
  1193. return Swal.fire({
  1194. icon: 'info',
  1195. title: 'Info',
  1196. text: 'Please enter valid capacity for all selected storage types.',
  1197. allowOutsideClick: false,
  1198. allowEscapeKey: false,
  1199. allowEnterKey: false,
  1200. showConfirmButton: true
  1201. });
  1202. }
  1203. }
  1204. const requestData = {
  1205. school_id: schoolId,
  1206. water,
  1207. is_purifier: isPurifier,
  1208. purifier_capacity: purifierCapacity,
  1209. is_borewell: isBorewell,
  1210. borewell_count: borewellCount,
  1211. is_storage: isStorage,
  1212. storage
  1213. };
  1214. $.ajax({
  1215. url: '/gcc/api/gccschool/schoolproperty/saveDrinkingWater',
  1216. method: 'POST',
  1217. contentType: 'application/json',
  1218. data: JSON.stringify(requestData),
  1219. success: function (response) {
  1220. if (response.status === "OK") {
  1221. Swal.fire({icon: "success", title: "Success", text: "Drinking water details submitted successfully!"}).then(() => location.reload());
  1222. } else {
  1223. Swal.fire({icon: "error", title: "Submission Failed", text: response.message || "Please try again."});
  1224. }
  1225. },
  1226. error: function (xhr) {
  1227. let errorMessage = "An error occurred while submitting the form.";
  1228. try {
  1229. // If responseText is a valid JSON string
  1230. const response = JSON.parse(xhr.responseText);
  1231. if (response.message) {
  1232. errorMessage = response.message;
  1233. }
  1234. } catch (e) {
  1235. // fallback: responseText is not JSON, maybe plain text
  1236. if (xhr.responseText) {
  1237. errorMessage = xhr.responseText;
  1238. }
  1239. }
  1240. Swal.fire({
  1241. icon: "error",
  1242. title: "Error",
  1243. text: errorMessage // ✅ Make sure this is always a string
  1244. });
  1245. }
  1246. });
  1247. });
  1248. });
  1249. function resetDrinkingWaterFields() {
  1250. console.log("Reset button clicked - Drinking Water");
  1251. // Uncheck all radio buttons and checkboxes
  1252. $('input[type="radio"]').prop('checked', false);
  1253. $('input[type="checkbox"]').prop('checked', false);
  1254. // Clear input fields
  1255. $('#purifier_capacity').val('');
  1256. $('#no_of_borwells').val('');
  1257. // Hide dependent sections
  1258. $('#purifier_capacity_container').hide();
  1259. $('#borwell_status_container').hide();
  1260. $('#storage_type_container').hide();
  1261. // Reset multi-select dropdown
  1262. $('#storage_types').val(null).trigger('change');
  1263. // ✅ Keep checkboxes visible but hide extra fields that depend on them
  1264. $('#water_sources_container').show(); // Ensures checkboxes remain visible
  1265. // Hide and clear dependent section
  1266. $('#waterSupplyContainer').hide().empty(); // 👈 Hides + removes previous dynamic HTML
  1267. // Hide dependent section
  1268. }
  1269. // ✅ Add event listener to show dependent fields when checkbox is clicked
  1270. $(document).on('change', 'input[type="checkbox"]', function () {
  1271. if ($('input[type="checkbox"]:checked').length > 0) {
  1272. $('#waterSupplyContainer').show(); // Show if at least one checkbox is checked
  1273. } else {
  1274. $('#waterSupplyContainer').hide(); // Hide if no checkboxes are checked
  1275. }
  1276. });
  1277. // Event Listener for Reset Button (Drinking Water section)
  1278. $(document).on('click', '#resetButton', function (event) {
  1279. event.preventDefault();
  1280. resetDrinkingWaterFields();
  1281. });
  1282. // Event Listener for Reset Button (Drinking Water section)
  1283. </script>
  1284. </div>
  1285. </body>
  1286. </html>