<?php $this->load->view('admin/includes/head'); ?>
<?php $this->load->view('admin/includes/sidebar'); ?>
<?php $this->load->view('admin/includes/topbar'); ?>
<style>
	#myDonations_filter {
		display: none !important;
	}

	#customSearchInput {
		margin-top: 8px !important;
		border: 1px solid !important;
	}

	#myDonations td {
		padding: 8px;
		text-align: center;
		/* border: 1px solid #ddd;  */
		white-space: normal;
		/* Allow text to wrap */
		word-wrap: break-word;
		/* Break long words to the next line */
		overflow-wrap: break-word;
		/* Another property to allow breaking words */
		max-width: 500px;
		/* Set a maximum width to control cell size */
		min-width: fit-content;
	}

	.service-name {
		max-width: 500px;
		min-width: 300px;
		white-space: normal;
		/* Allow text to wrap */
		word-wrap: break-word;
		/* Break long words to the next line */
		overflow-wrap: break-word;
		/* Allow breaking words */
	}

	#inputContainer input::placeholder {
		color: #888;
		font-style: italic;
	}

	#yearInput {
		height: 24px !important;
	}

	.ml-10 {
		margin-left: 10px !important;
	}

	.loader-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
		/* Adjust as needed */
	}

	.child {
		display: none;
	}
</style>
<!-- Main content-->
<div class="container px-2 mt-4">
	<?php

	$success = $this->session->flashdata('success');
	$failure = $this->session->flashdata('failure');

	echo $success ?  $success :  $failure;

	?>
	<div class="row">
			<div class="col-sm-12 d-flex">
			<!-- <label for="typeSelect">Select Date:</label>
			<select id="typeSelect" onchange="updateInputField();getFilterData()" class="ml-10">
				<option value="month">Month</option>
				<option value="date">Date</option>
			</select>

			<div id="inputContainer">
			</div> -->

			<div class="container-fluid mt-2 mb-2">
				<div class="row">
					<!-- Select Dropdown -->
					<div class="col-12 col-md-3 mb-2">
						<label for="typeSelect" class="form-label">Select Date:</label>
						<select id="typeSelect" onchange="updateInputField(); getFilterData()" class="form-select">
							<option value="month">Month</option>
							<option value="date">Date</option>
						</select>
					</div>

					<!-- Dynamic Inputs will come here -->
					<div class="col-12 col-md-9" id="inputContainer">
						<!-- JavaScript will inject input fields here -->
					</div>
				</div>
			</div>

		</div>
		<div class="col-sm-12">
			<div class="container-fluid mt-2 mb-2">
				<button id="searchIcon" class="btn btn-light">
					<i class="fa fa-search"></i> <!-- Font Awesome search icon -->
				</button>

				<!-- Hidden search input -->
				<input type="text" id="customSearchInput" class="form-control" placeholder="Search..." style="display:none;">
			</div>
		</div>
	</div>
	<style>
		td.details-control {
			cursor: pointer;
		}

		tr.shown td.details-control i {
			-webkit-transform: rotate(180deg);
			-moz-transform: rotate(180deg);
			-ms-transform: rotate(180deg);
			-o-transform: rotate(180deg);
			transform: rotate(180deg);
		}
	</style>
	<div class="table-responsive" id="TableData">
		<table id="myDonations" class="table table-hovered">
			<thead style="background-color: var(--devotee-table-header-bg); color: white;width: 100%;">
				<tr>
					<th class="text-center" style="vertical-align: top;">Receipt&nbsp;#</th>

					<th class="text-center" style="vertical-align: top;">Total Amount</th>
					<th class="text-center" style="vertical-align: top;">Payment Type</th>
					<th class="text-center" style="vertical-align: top;">Payment Source</th>
					<th class="text-center" style="vertical-align: top;">Booking Date</th>
					<th class="text-center" style="vertical-align: top;">Status</th>
					<!-- <th class="text-center" style="vertical-align: top;">Refund Payment</th> -->
					<th class="text-center" style="vertical-align: top;">View Receipt</th>
				</tr>
			</thead>
			<tbody style="width:100%">

			</tbody>
		</table>


	</div>



</div>
<!-- End Main content-->
<?php $this->load->view('admin/includes/footer'); ?>
<script>
	window.addEventListener('DOMContentLoaded', event => {

		// Toggle the side navigation
		const sidebarToggle = document.body.querySelector('#sidebarToggle');
		if (sidebarToggle) {
			// Uncomment Below to persist sidebar toggle between refreshes
			// if (localStorage.getItem('sb|sidebar-toggle') === 'true') {
			//     document.body.classList.toggle('sb-sidenav-toggled');
			// }
			sidebarToggle.addEventListener('click', event => {
				event.preventDefault();
				document.body.classList.toggle('sb-sidenav-toggled');
				localStorage.setItem('sb|sidebar-toggle', document.body.classList.contains('sb-sidenav-toggled'));
			});
		}

	});
	$(document).ready(function() {
		$("#heading").text('My Payments');
		// $('#myDonations').DataTable({
		// 	order: [
		// 		[0, 'desc']
		// 	],
		// 	"lengthChange": false,
		// 	"scrollX": true,
		// 	"ordering": false,
		// 	"searching": true,
		// 	language: {
		// 		emptyTable: "No Payments Available to show..",
		// 		search: ''
		// 	}
		// });
	});
	$(document).ready(function() {

		$("#myDonations_filter").css('display', 'none');
		// Hide the default DataTable search input
		// $('#myDonations_filter').hide();

		// Toggle the visibility of the custom search input when the icon is clicked
		$('#searchIcon').on('click', function() {
			$('#customSearchInput').toggle(); // Show/hide the input box
		});

		// Perform search when typing in the custom input box
		$('#customSearchInput').on('keyup', function() {
			$('#myDonations').DataTable().search($(this).val()).draw(); // Perform the search
		});
	});


	/*filert Data*/
	const typeSelect = document.getElementById('typeSelect');
	const inputContainer = document.getElementById('inputContainer');

	function updateInputField() {
		inputContainer.innerHTML = ''; // Clear previous input

		const currentDate = new Date();
		const today = currentDate.toISOString().split('T')[0];
		const currentMonth = today.slice(0, 7);
		const currentYear = currentDate.getFullYear();

		if (typeSelect.value === 'year') {
			const wrapper = document.createElement('div');
			wrapper.className = 'row';

			const col = document.createElement('div');
			col.className = 'col-12 col-sm-6';

			const yearLabel = document.createElement('label');
			yearLabel.textContent = 'Select Year:';
			yearLabel.setAttribute('for', 'yearInput');
			yearLabel.className = 'form-label';

			const yearSelect = document.createElement('select');
			yearSelect.id = 'yearInput';
			yearSelect.name = 'selecteddate';
			yearSelect.className = 'form-select';

			for (let year = currentYear; year >= 1900; year--) {
				const option = document.createElement('option');
				option.value = year;
				option.textContent = year;
				if (year === currentYear) option.selected = true;
				yearSelect.appendChild(option);
			}

			col.appendChild(yearLabel);
			col.appendChild(yearSelect);
			wrapper.appendChild(col);
			inputContainer.appendChild(wrapper);
			yearSelect.addEventListener('change', getFilterData);

		} else if (typeSelect.value === 'date') {
			const day = String(currentDate.getDate()).padStart(2, '0');
			const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Months are 0-based
			const year = currentDate.getFullYear();

			const newtoday = `${month}-${day}-${year}`;
			const wrapper = document.createElement('div');
			wrapper.className = 'row';

			const fromCol = document.createElement('div');
			fromCol.className = 'col-12 col-sm-6 mb-2';
			const fromLabel = document.createElement('label');
			fromLabel.textContent = 'From Date:';
			fromLabel.setAttribute('for', 'fromDate');
			fromLabel.className = 'form-label';
			const fromDate = document.createElement('input');
			fromDate.type = 'text';
			fromDate.id = 'fromDate';
			fromDate.name = 'fromDate';
			fromDate.value = newtoday;
			fromDate.className = 'form-control datepicker';
			fromCol.appendChild(fromLabel);
			fromCol.appendChild(fromDate);

			const toCol = document.createElement('div');
			toCol.className = 'col-12 col-sm-6';
			const toLabel = document.createElement('label');
			toLabel.textContent = 'To Date:';
			toLabel.setAttribute('for', 'toDate');
			toLabel.className = 'form-label';
			const toDate = document.createElement('input');
			toDate.type = 'text';
			toDate.id = 'toDate';
			toDate.name = 'toDate';
			toDate.value = newtoday;
			toDate.className = 'form-control datepicker';
			toCol.appendChild(toLabel);
			toCol.appendChild(toDate);

			wrapper.appendChild(fromCol);
			wrapper.appendChild(toCol);
			inputContainer.appendChild(wrapper);

			fromDate.addEventListener('change', getFilterData);
			toDate.addEventListener('change', getFilterData);

			$(".datepicker").datepicker({
				dateFormat: 'mm-dd-yy',
				changeMonth: true,
				changeYear: false,
				showButtonPanel: true,
				onSelect: function(dateText, inst) {
					// Format and set the selected date
					var date = $(this).datepicker('getDate');
					$(this).val($.datepicker.formatDate('mm-dd-yy', date));

					// ✅ Call your filter function
					getFilterData();
				}
			});


		} else if (typeSelect.value === 'month') {
			const wrapper = document.createElement('div');
			wrapper.className = 'row';

			const col = document.createElement('div');
			col.className = 'col-12 col-sm-6';

			const monthLabel = document.createElement('label');
			monthLabel.textContent = 'Select Month:';
			monthLabel.setAttribute('for', 'monthInput');
			monthLabel.className = 'form-label';

			const monthInput = document.createElement('input');
			monthInput.type = 'month';
			monthInput.id = 'monthInput';
			monthInput.name = 'selecteddate';
			monthInput.value = currentMonth;
			monthInput.className = 'form-control'; // ✅ Important fix

			col.appendChild(monthLabel);
			col.appendChild(monthInput);
			wrapper.appendChild(col);
			inputContainer.appendChild(wrapper);

			monthInput.addEventListener('change', getFilterData);
		}

	}


	// Call updateInputField initially to set up the initial input field
	updateInputField();

	function format(d) {
		// ✅ Ensure paymentsData is always defined
		let paymentsData = d.paymentsData || [];

		if (paymentsData.length === 0) {
			return '<div>No child data available</div>';
		}

		var childTable = `<table class="table table-bordered child-table"><thead><tr>
        <th>Service Name</th><th>Service Type</th><th>Service Date</th>
        <th>Unit Price</th><th>Quantity</th><th>Status</th>
    </tr></thead><tbody>`;

		paymentsData.forEach(item => {
			childTable += `<tr>
            <td>${item.ServiceSetup || 'N/A'}</td>
            <td>${item.serviceTypes || 'N/A'}</td>
            <td>${item.serviceDate || 'N/A'}</td>
            <td>$${parseFloat(item.serviceAmount || 0).toFixed(2)}</td>
            <td>${item.qty || 1}</td>
            <td><span class="badge">${item.statusName || 'N/A'}</span></td>
        </tr>`;
		});

		if (parseFloat(d.generaldonations) > 0) {
			childTable += `<tr style="background: #def1ff;">
            <td><b>General Donation</b></td><td></td><td></td>
            <td>$${parseFloat(d.generaldonations).toFixed(2)}</td>
            <td></td><td></td>
        </tr>`;
		}
		if (parseFloat(d.acharyasanbhavana) > 0) {
			childTable += `<tr style="background: #def1ff;">
            <td><b>Acharyasanbhavana</b></td><td></td><td></td>
            <td>$${parseFloat(d.acharyasanbhavana).toFixed(2)}</td>
            <td></td><td></td>
        </tr>`;
		}

		childTable += `</tbody></table>`;
		return childTable;
	}

	// ✅ Function to Load & Filter Data
	function getFilterData() {
		


		var requestData = {
			dateType: typeSelect.value,
		};

		if (typeSelect.value === 'year') {
			requestData.selecteddate = document.getElementById('yearInput')?.value || '';
		} else if (typeSelect.value === 'date') {
			requestData.selecteddate = document.getElementById('fromDate')?.value || '';
			requestData.selectedenddate = document.getElementById('toDate')?.value || '';
		} else if (typeSelect.value === 'month') {
			requestData.selecteddate = document.getElementById('monthInput')?.value || '';
		}

		console.log("Request Data:", requestData);


		$.ajax({
			url: '<?= base_url('Admin/Dashboard/FilterPaymentsData') ?>',
			type: 'POST',
			data: requestData,
			beforeSend: function() {
				// Show loader before the AJAX request (optional)
			},
			success: function(data) {
				var tableData = JSON.parse(data);
				console.log(tableData); // ✅ Debugging - Check API response

				// ✅ Ensure `paymentsData` exists in each entry
				tableData.forEach(row => {
					if (!row.paymentsData) {
						row.paymentsData = []; // Default empty array
					}
				});

				// Destroy existing DataTable if it exists
				if ($.fn.DataTable.isDataTable("#myDonations")) {
					$('#myDonations').DataTable().destroy();
				}

				// ✅ Initialize DataTable with new data
				var table = $("#myDonations").DataTable({
					data: tableData,
					columns: [{
							className: "details-control",
							orderable: false,
							data: null,
							defaultContent: '<img src="<?= base_url('assets/img/expand-more.svg') ?>" style="height: 50px;width: 50px;">',
							title: ""
						},
						{
							data: "batchNo",
							title: "Receipt #"
						},
						{
							data: "totalAmount",
							title: "Total Amount",
							render: $.fn.dataTable.render.number(',', '.', 2, '$')
						},
						{
							data: "source",
							title: "Payment Source"
						},
						{
							data: "recCreDate",
							title: "Booking Date"
						},
						{
							data: "paymentStatus",
							title: "Status",
							render: function(data) {
								return `<span class="badge">${data}</span>`;
							}
						},
						{
							data: "tokenNumber",
							title: "View Receipt",
							render: function(data) {
								return `<a href="<?= base_url('admin/download-reciept/') ?>${btoa(data)}/PAYMENTS" target="_blank"><i class="fa fa-eye" style="font-size:22px"></i></a>`;
							}
						}
					],
					order: [
						[1, "asc"]
					],
					paging: true,
					searching: true,
					lengthChange: false,
					scrollX: true,
					language: {
						emptyTable: "No data available" // ✅ Custom message
					}
				});

				// ✅ Rebind click event for expanding child rows
				$("#myDonations tbody").off("click", "td.details-control").on("click", "td.details-control", function() {
					var tr = $(this).closest("tr");
					var row = table.row(tr);

					if (row.child.isShown()) {
						row.child.hide();
						tr.removeClass("shown");
					} else {
						row.child(format(row.data()), "p-0").show();
						tr.addClass("shown");
					}
				});
			}
		});
	}


	getFilterData();



	// Function to toggle child rows
	function ShowChildRow(id) {
		// alert(id);
		$(".child_" + id).each(function() {
			$(this).toggle(); // Toggles display for each matching element
		});
	}
</script>
</body>

</html>