	<?php $this->load->view("common/header"); ?>
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
	<!-- end: HEAD -->


	<!-- end: CSS REQUIRED FOR THIS PAGE ONLY -->
	<!-- end: HEAD -->
	<!-- start: BODY -->

	<body>
		<!-- start: HEADER -->
		<div class="navbar navbar-inverse navbar-fixed-top">
			<!-- start: TOP NAVIGATION CONTAINER -->
			<div class="container">
				<div class="navbar-header">
					<!-- start: RESPONSIVE MENU TOGGLER -->
					<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button">
						<span class="clip-list-2"></span>
					</button>
					<!-- end: RESPONSIVE MENU TOGGLER -->
					<!-- start: LOGO -->
					<?php $this->load->view("common/logo"); ?>
					<!-- end: LOGO -->
				</div>
				<div class="navbar-tools">
					<!-- start: TOP NAVIGATION MENU -->
					<?php $this->load->view("common/notifications.php"); ?>
					<!-- end: TOP NAVIGATION MENU -->
				</div>
			</div>
			<!-- end: TOP NAVIGATION CONTAINER -->
		</div>
		<!-- end: HEADER -->
		<!-- start: MAIN CONTAINER -->
		<div class="main-container">
			<div class="navbar-content">
				<!-- start: SIDEBAR -->
				<?php $this->load->view("common/navigation"); ?>
				<!-- end: SIDEBAR -->
			</div>
			<!-- start: PAGE -->
			<div class="main-content">
				<!-- end: SPANEL CONFIGURATION MODAL FORM -->
				<div class="container">
					<!-- start: PAGE HEADER -->
					<div class="row">
						<div class="col-sm-12">
							<!-- start: PAGE TITLE & BREADCRUMB -->
							<ol class="breadcrumb">
								<li>
									<a href="<?php echo base_url('dashboard'); ?>">
										Dashboard
									</a>
								</li>
								<li>
									<a href="#">
										Loan
									</a>
								</li>


								<li class="active">
									Loan Payment Pending List
								</li>
								<li class="search-box">
									<form class="sidebar-search">
										<div class="form-group">
											<input type="text" placeholder="Start Searching...">
											<button class="submit">
												<i class="clip-search-3"></i>
											</button>
										</div>
									</form>
								</li>
							</ol>
							<div class="page-header">
								<h3>Loan Payment Pending List</h3>
							</div>

							<p>Please use the table below to navigate or filter the results. </p>

							<div class="col-md-3">
								<div class="form-group">

									<label for="loan_payment_term">Payment Term * </label>
									<input type="date" id="selected_date" name="selected_date" class="form-control" />
								</div>
							</div>

							<div class="col-sm-4 ">
								<div class="form-group">
									<label for="s2id_autogen1"></label><br>
									<input type="button" id="load_terms_btn" value="Filter Result" class="btn btn-primary">

								</div>
							</div>



						</div>
					</div>
					<!-- end: PAGE HEADER -->
					<div class="row">
						<div class="col-md-12">
							<!-- start: DYNAMIC TABLE PANEL -->
							<div class="panel panel-default">
								<div class="panel-heading">
									<i class="fa fa-external-link-square"></i>
									Payment List

								</div>
							</div>
							<div class="panel-body">
								<div id="error"></div>
								<!-- TABLE -->
								<table class="table table-bordered table-condensed table-hover table-striped" id="terms_table">
									<thead>
										<tr>
											<th>Loan</th>
											<th>Customer Name</th>
											<th>Term Amount</th>
											<th>Term No</th>
											<th>Pay Amount</th>
											<th>Not Collected</th>
											<th>Reason</th>
										</tr>
									</thead>
									<tbody></tbody>
								</table>
								<div class="modal-footer">
									<div class="col-md-3">
										<input type="button" name="update" value="Add Payment" class="btn btn-primary" id="update">
										<input type="reset" value="Reset" class="btn btn-danger">
									</div>
								</div>
							</div>
						</div>
						<!-- end: DYNAMIC TABLE PANEL -->
					</div>
				</div>

				<!-- end grid -->


			</div>
			<!-- end: PAGE -->
		</div>
		<!-- end: MAIN CONTAINER -->
		<!-- start: FOOTER -->
		<div class="footer clearfix">
			<div class="footer-inner">
				<?php echo date("Y"); ?> © A.S.S.K Loan Management System
			</div>
			<div class="footer-items">
				<span class="go-top"><i class="clip-chevron-up"></i></span>
			</div>
		</div>


		<!-- start ajax model -->
		<div id="ajax-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" style="display: none;"></div>
		<!-- end ajax model -->

		<!-- start: MAIN JAVASCRIPTS -->
		<?php $this->load->view("common/footer"); ?>
		<!-- end: MAIN JAVASCRIPTS -->
		<script type="text/javascript" src="<?php echo asset_url(); ?>js/jquery.dataTables.min.js"></script>
		<script type="text/javascript" src="<?php echo asset_url(); ?>js/dataTables.bootstrap.min.js"></script>
		<script type="text/javascript" src="<?php echo base_url('thems/js/bootbox.min.js'); ?>"></script>
		<script>
			jQuery(document).ready(function() {

				// ✅ Load Terms by Date
				$("#load_terms_btn").click(function() {

					let date = $("#selected_date").val();

					if (!date) {
						Swal.fire({
							icon: "warning",
							title: "Date Required",
							text: "Please select a date before filtering!"
						});
						return;
					}

					$.ajax({
						url: "<?= base_url(); ?>loan_payment_received/get_terms_by_date",
						type: "POST",
						data: {
							date: date
						},
						dataType: "json",

						success: function(res) {

							let rows = "";

							// ✅ If no terms + no delay charges
							if ((!res.terms || res.terms.length === 0) &&
								(!res.delay_charges || res.delay_charges.length === 0) &&
								(!res.arrears || res.arrears.length === 0)
								) {

								Swal.fire({
									icon: "info",
									title: "No Records",
									text: "No pending payments for selected date."
								});

								$("#terms_table tbody").html('');
								return;
							}

							// ✅ -------------------------------
							// ✅ LOAD LOAN TERMS
							// ✅ -------------------------------
							if (res.terms && res.terms.length > 0) {

								$.each(res.terms, function(i, v) {

									rows += `
                        <tr>
                            <td>${v.loan_code}</td>
                            <td>${v.cus_name}</td>
                            <td>${v.term_amount}</td>
                            <td>${v.term_no}</td>

                            <td>
                                <input type="text"
                                    class="form-control pay_amount"
                                    name="pay_amount[${v.term_id}]"
                                    value="${v.term_amount}">
                            </td>

                            <td class="text-center">
                                <input type="checkbox"
                                    class="not_collected"
                                    data-id="${v.term_id}">
                            </td>

                            <td>
                                <textarea class="form-control reason"
                                    name="reason[${v.term_id}]"
                                    style="display:none"
                                    placeholder="Enter reason"></textarea>
                            </td>
                        </tr>
                    `;
								});
							}

							// ✅ -------------------------------
							// ✅ LOAD DELAY CHARGES (IF ANY)
							// ✅ -------------------------------
							// ✅ Load Delay Charges
							if (res.delay_charges && res.delay_charges.length > 0) {

								rows += `
									<tr style="background:#d9edf7; font-weight:bold;">
										<td colspan="7">Delay Charge Payments</td>
									</tr>
								`;

								$.each(res.delay_charges, function(i, d) {

									rows += `
										<tr class="delay-row">
											<td>${d.loan_code}</td>
											<td>${d.cus_name}</td>
											<td>${d.total_delay_charge}</td>
											<td>Delay Charge</td>

											<td>
												<input type="text"
													class="form-control delay_pay_amount"
													name="delay_pay_amount[${d.loan_id}]"
													data-id="${d.loan_id}"
													value="">
											</td>

											<td class="text-center">
												
											</td>

											<td>
												
											</td>
										</tr>
									`;
								});
							}
							
							
							// ✅ -------------------------------
                            // ✅ LOAD ARREARS (IF ANY)
                            // ✅ -------------------------------
                            if (res.arrears && res.arrears.length > 0) {
                            
                                rows += `
                                    <tr style="background:#f2dede; font-weight:bold;">
                                        <td colspan="7">Arrears Loans</td>
                                    </tr>
                                `;
                            
                                $.each(res.arrears, function(i, a) {
                            
                                    rows += `
                                        <tr class="arrears-row">
                                            <td>${a.loan_code}</td>
                                            <td>${a.cus_name}</td>
                                            <td>${a.balance_amount}</td>
                                            <td>Arrears</td>
                            
                                            <td>
                                                <input type="text"
                                                    class="form-control arrears_pay_amount"
                                                    name="arrears_pay_amount[${a.loan_id}]"
                                                    data-id="${a.loan_id}"
                                                    value="">
                                            </td>
                            
                                            <td></td>
                                            <td></td>
                                        </tr>
                                    `;
                                });
                            }


							// ✅ Apply rows to table
							$("#terms_table tbody").html(rows);
						},

						error: function() {
							Swal.fire({
								icon: "error",
								title: "Error",
								text: "Failed to load data!"
							});
						}
					});

				});


				// ✅ Toggle reason box
				$(document).on("change", ".not_collected", function() {
					let row = $(this).closest("tr");

					if ($(this).is(":checked")) {
						row.find(".pay_amount").val("0").prop("readonly", true);
						row.find(".reason").show().prop("required", true);
					} else {
						row.find(".pay_amount").prop("readonly", false);
						row.find(".reason").hide().prop("required", false);
					}
				});


				// ✅ Save All Payments
				$("#update").click(function() {

					let formData = {};
					formData["pay_amount"] = {};
					formData["not_collected"] = {};
					formData["reason"] = {};
					formData["delay_pay_amount"] = {};
					formData["arrears_pay_amount"] = {};

					let emptyReason = false;

					$("#terms_table tbody tr").each(function() {

						let id = $(this).find(".not_collected").data("id");
						let isNotCollected = $(this).find(".not_collected").is(":checked");
						let reason = $(this).find(".reason").val();

						if (isNotCollected && reason.trim() === "") {
							emptyReason = true;
						}

						formData["pay_amount"][id] = $(this).find(".pay_amount").val();
						formData["not_collected"][id] = isNotCollected ? 1 : 0;
						formData["reason"][id] = reason;

						let delay_id = $(this).find(".delay_pay_amount").data("id");
						
						formData["delay_pay_amount"][delay_id] = $(this).find(".delay_pay_amount").val();
						// -------- ARREARS --------
                        let arrears_id = $(this).find(".arrears_pay_amount").data("id");
                        if (arrears_id !== undefined) {
                            formData["arrears_pay_amount"][arrears_id] =
                                $(this).find(".arrears_pay_amount").val();
                        }
					});

					// ✅ Check reason requirement
					if (emptyReason) {
						Swal.fire({
							icon: "warning",
							title: "Reason Required",
							text: "Please enter reason for all Not Collected terms."
						});
						return;
					}

					Swal.fire({
						title: "Are you sure?",
						text: "Do you want to save all payments?",
						icon: "question",
						showCancelButton: true,
						confirmButtonText: "Yes, Save",
						cancelButtonText: "Cancel"
					}).then((result) => {

						if (result.isConfirmed) {

							$.ajax({
								url: "<?= base_url('loan_payment_received/save_terms'); ?>",
								type: "POST",
								data: formData,
								dataType: "json",

								success: function(res) {

									if (res.status === "success") {

										Swal.fire({
											icon: "success",
											title: "Saved!",
											text: "Payments updated successfully!"
										});

										$("#load_terms_btn").trigger("click"); // refresh table

									} else {

										Swal.fire({
											icon: "error",
											title: "Error",
											text: res.message
										});

									}

								},

								error: function() {
									Swal.fire({
										icon: "error",
										title: "Error",
										text: "Something went wrong while saving!"
									});
								}

							});

						}

					});

				});

			});
		</script>
	</body>
	<!-- end: BODY -->

	</html>