	<?php $this->load->view("common/header"); ?>

	<!-- 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">
								<h1>Cheque Manage</h1>
							</div>

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

							<div class="col-sm-3">
								<div class="form-group">
									<label>Route * </label>
									<select id="route_id" class="form-control search-select" name="route_id">
										<option value="">- select route -
										</option>
										<?php foreach ($routes_list as $row) { ?>
											<option value="<?php echo $row['route_id']; ?>">
												<?php echo $row['route_name']; ?>
											</option>
										<?php } ?>
									</select>
								</div>
							</div>

							<div class="col-md-4">

								<div class="form-group">
									<label for="cus_id">Customer * </label>
									<select id="cus_id" class="form-control search-select" name="cus_id">
										<option value="">-Select Customer-</option>
										<?php foreach ($customer_list as $row) { ?>
											<option value="<?php echo $row['cus_id']; ?>"><?php echo $row['cus_name'];
																							if ($row['cus_nic']) echo " - " . $row['cus_nic']; ?> </option>
										<?php }  ?>
									</select>

								</div>
							</div>


							<div class="col-sm-2">
								<div class="form-group">
									<label>From Date </label>
									<input id="srh_from_date" name="srh_from_date" type='text' class="form-control date" value="" data-bv-field="date" />
								</div>
							</div>

							<div class="col-sm-2">
								<div class="form-group">
									<label for="s2id_autogen1">To Date </label>

									<input id="srh_to_date" name="srh_to_date" type='text' class="form-control date" value="" data-bv-field="date" />
								</div>
							</div>

							<div class="col-sm-4 ">
								<div class="form-group">
									<label for="s2id_autogen1">
									</label><br>

									<input type="button" name="add_category" value="Filter Reuslt" class="btn btn-primary" onClick="loadGrid()"> &nbsp;&nbsp;



								</div>
							</div>
						</div>
					</div>
					<!-- end: PAGE HEADER -->
					<!-- start: PAGE CONTENT 
                    <!-- start grid -->
					<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>
									Cheque Management

								</div>
							</div>
							<div class="panel-body">
								<div id="error"></div>
								<table class="table table-bordered table-condensed table-hover table-striped dataTable" id="products_table">
									<thead>
										<tr>
											<th>Cheque Date</th>
											<th>Cheque No</th>
											<th>Amount</th>
											<th>Bank</th>
											<th>Branch</th>
											<th>Loan</th>
											<th>Customer Name </th>
											<th>Status</th>
											<th>Action</th>
										</tr>
									</thead>
									<tfoot>
										<tr>
											<th>Cheque Date</th>
											<th>Cheque No</th>
											<th>Amount</th>
											<th>Bank</th>
											<th>Branch</th>
											<th>Loan</th>
											<th>Customer Name </th>
											<th>Status</th>
											<th>Action</th>
										</tr>
								</table>
							</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>
		<!-- end: FOOTER -->
		<!-- start: RIGHT SIDEBAR -->
		<!-- end: RIGHT SIDEBAR -->
		<div id="event-management" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
							&times;
						</button>
						<h4 class="modal-title">Event Management</h4>
					</div>
					<div class="modal-body"></div>
					<div class="modal-footer">
						<button type="button" data-dismiss="modal" class="btn btn-light-grey">
							Close
						</button>
						<button type="button" class="btn btn-danger remove-event no-display">
							<i class='fa fa-trash-o'></i> Delete Event
						</button>
						<button type='submit' class='btn btn-success save-event'>
							<i class='fa fa-check'></i> Save
						</button>
					</div>
				</div>
			</div>
		</div>

		<div class="row" id="cheque_section" style="margin-top: 20px; display:none;">
			<div class="panel panel-default">
				<div class="panel-heading">Cheque Details</div>
				<div class="panel-body">
					<table class="table table-bordered" id="cheque_table">
						<thead>
							<tr>
								<th>Cheque Date</th>
								<th>Realization Date</th>
								<th>Cheque Amount</th>
								<th>Cheque No</th>
								<th>Bank</th>
								<th>Branch</th>
								<th>Days</th>
								<th>Charges</th>
								<th>Action</th>
							</tr>
						</thead>
						<tbody></tbody>
					</table>

					<button type="button" id="add_cheque_row" class="btn btn-success">
						<i class="fa fa-plus"></i> Add Cheque
					</button>
				</div>
			</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 src="<?php echo asset_url(); ?>js/moment-with-locales.js"></script>
		<script type="text/javascript" src="<?php echo asset_url(); ?>js/bootstrap-datetimepicker.js"></script>
		<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 src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		<script>
			let chequeCount = 0;

			$('#add_cheque_row').click(function() {
				chequeCount++;
				let term_id = $('#cheque_section').data('term-id'); // use term_id

				let row = `
    <tr id="cheque_row_${chequeCount}">
        <td><input type="date" name="cheque_date[]" class="form-control" required></td>
        <td><input type="date" name="realize_date[]" class="form-control"></td>
        <td><input type="number" step="0.01" name="cheque_amount[]" class="form-control" required></td>
        <td><input type="text" name="cheque_no[]" class="form-control" required></td>
        <td>
            <select name="bank_id[]" class="form-control" required>
                <option value="">Select Bank</option>
                <?php foreach ($banks as $bank): ?>
                    <option value="<?= $bank['bank_id'] ?>"><?= $bank['bank_name'] ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td>
            <select name="branch_id[]" class="form-control" required>
                <option value="">Select Branch</option>
            </select>
        </td>
        <td><input type="number" name="days[]" class="form-control"></td>
        <td><input type="number" step="0.01" name="charges[]" class="form-control"></td>
        <td>
            <button type="button" class="btn btn-danger btn-xs" onclick="removeChequeRow(${chequeCount})">
                <i class="fa fa-trash"></i>
            </button>
        </td>
    </tr>
    `;
				$('#cheque_table tbody').append(row);
			});

			function removeChequeRow(id) {
				$('#cheque_row_' + id).remove();
			}

			function showAddChequeSection(term_id) {
				// Show the hidden cheque section for adding new cheques
				$('#cheque_section').show();

				// Optional: Store term_id in a hidden field to save new cheque under this loan term
				$('#cheque_section').data('term-id', term_id);

				// SweetAlert to notify
				Swal.fire({
					icon: 'info',
					title: 'Add Cheque',
					text: 'You can now add a new cheque for this returned payment.'
				});
			}

			function updateChequeStatus(term_id, status) {

				if (term_id == '' || term_id == null) {
					Swal.fire('Error', 'Invalid cheque reference', 'error');
					return;
				}

				Swal.fire({
					title: 'Are you sure?',
					text: "Change cheque status to " + status + "?",
					icon: 'warning',
					showCancelButton: true,
					confirmButtonColor: '#3085d6',
					cancelButtonColor: '#d33',
					confirmButtonText: 'Yes, Update!'
				}).then((result) => {

					if (result.isConfirmed) {

						$.ajax({
							url: "<?php echo base_url('cheques/update_cheque_status'); ?>",
							type: "POST",
							dataType: "json",
							data: {
								term_id: term_id,
								status: status
							},
							success: function(res) {

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

									Swal.fire(
										'Updated!',
										res.message,
										'success'
									).then(() => {
										//location.reload();
									});

								} else {

									Swal.fire(
										'Error!',
										res.message,
										'error'
									);

								}

							},
							error: function() {
								Swal.fire(
									'Error!',
									'Server communication failed.',
									'error'
								);
							}

						});

					}

				});

			}

			jQuery(document).ready(function() {
				//TableData.init();

				$('#srh_to_date').datetimepicker({
					defaultDate: new Date()
				});
				$('#srh_from_date').datetimepicker({
					//defaultDate: currentDate
				});

				loadGrid();
			});


			function loadGrid() {

				var route_id = $('#route_id').val();
				var cus_id = $('#cus_id').val();
				var srh_from_date = $('#srh_from_date').val();
				var srh_to_date = $('#srh_to_date').val();

				$('#products_table').DataTable({
					"ajax": "<?php echo base_url('cheques/get_all_pending_cheques') ?>?route=" + route_id + "&cus_id=" + cus_id + "&srh_from_date=" + srh_from_date + "&srh_to_date=" + srh_to_date,
					"bDestroy": true,
					"iDisplayLength": 50,
					"order": [
						[0, "asc"]
					]
				});

			}

			function deleteUserData(user_id) {
				$("#myModal4").modal();
				$('#sel_id').val(user_id);
				$('#popup_type').val('delete');
				$('#page').val('supp');
				$("#label").text("Are you sure you want to delete this supplier?");
			}

			function disableUserData(user_id) {
				$("#myModal4").modal();
				$('#sel_id').val(user_id);
				$('#popup_type').val('disable');
				$('#page').val('supp');
				$("#label").text("Are you sure you want to disable this supplier?");
			}

			function enableUserData(user_id) {
				$("#myModal4").modal();
				$('#sel_id').val(user_id);
				$('#page').val('supp');
				$('#popup_type').val('enable');
				$("#label").text("Are you sure you want to enable this supplier?");
			}

			jQuery(document).ready(function() {
				//conirm
				$("#conirm").click(function() {
					var sel_id = $('#sel_id').val();
					var popup_type = $('#popup_type').val();
					var page = $('#page').val();
					var user_id = sel_id;
					if (page == 'supp') {
						if (popup_type == 'delete') {
							$.post("users/delete_user", {
									user_id: user_id
								})
								.done(function(data) {
									var obj = jQuery.parseJSON(data);
									loadGrid(); // load supplier data
									displayNotice('page', 'User has been deleted successfully!')
								});
						} else if (popup_type == 'disable') {
							$.post("users/disable_user", {
									user_id: user_id
								})
								.done(function(data) {
									var obj = jQuery.parseJSON(data);
									loadGrid(); // load supplier data
									displayNotice('page', 'User has been disabled successfully!')
								});
						} else if (popup_type == 'enable') {
							$.post("users/enable_user", {
									user_id: user_id
								})
								.done(function(data) {
									var obj = jQuery.parseJSON(data);
									loadGrid(); // load supplier data
									displayNotice('page', 'User has been enabled successfully!')
								});
						}
					} //end page check

				});


			});

			function fbs_click(id, d) {
				u = location.href;
				t = document.title;
				window.open('<?php echo base_url() ?>loan/print_loan_invoice/bkng_id/' + id, 'sharer', 'toolbar=0,status=0,width=700,height=700, left=10, top=10,scrollbars=yes');
				return false;
			}

			function cheque_deposit(pay_id) {
				bootbox.confirm("Are Your Sure!", function(result) {
					console.log('This was logged in the callback: ' + result);
					if (result == true) {
						//-----------------------------------------------------
						$.post("<?php echo base_url(); ?>cheque_management/update_deposit", {
								pay_id: pay_id
							})
							.done(function(data) {
								loadGrid();
							});
						//--------------------------------------------------			
					} else {

					}
				});
			}


			function cheque_realize(pay_id) {
				bootbox.confirm("Are Your Sure!", function(result) {
					console.log('This was logged in the callback: ' + result);
					if (result == true) {
						//-----------------------------------------------------
						$.post("<?php echo base_url(); ?>cheque_management/update_realize", {
								pay_id: pay_id
							})
							.done(function(data) {
								loadGrid();
							});
						//--------------------------------------------------			
					} else {

					}
				});
			}

			function cheque_reject(pay_id) {
				bootbox.confirm("Are Your Sure!", function(result) {
					console.log('This was logged in the callback: ' + result);
					if (result == true) {
						//-----------------------------------------------------
						$.post("<?php echo base_url(); ?>loan_payment_received/update_reject", {
								pay_id: pay_id
							})
							.done(function(data) {
								loadGrid();
							});
						//--------------------------------------------------			
					} else {

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

	</html>