<?php
$uri = $this->uri->segment(3);
$page = 'hospital_diagnostic_payments';
//echo $uri;exit;
?>


<!-- Content wrapper -->
<div class="content-wrapper">
  <!-- Content -->

  <div class="container-xxl flex-grow-1 container-p-y">
	<!-- Users List Table -->

	<div class="card">
	  <div class="card-header border-bottom">
		<!-- <h5 class="card-title mb-3">Search Filter</h5> -->
		<!-- Button trigger modal -->
		<div class="w3-sidebar w3-bar-block w3-card w3-animate-right" style="display:none;right:0;"
		  id="rightMenu">
		  <button style="margin: auto; margin-right:0;" onclick="closeRightMenu()"
			class="w3-bar-item w3-button w3-large">
			<span>&times;</span></button>
		</div>

		<div
		  style="display: flex;justify-content: space-between; align-items: center; gap: 10px; flex-wrap: wrap; ">

		  <h3>Diagnostic Payments</h3>
		  
		  <div
			style="display: flex;justify-content: flex-end; align-items: flex-end; gap: 10px; flex-wrap: wrap; ">
			<div style="display: flex; justify-content: center;align-items: center; gap: 10px;">
			<button id="button" class="w3-button btn-primary" style="width: 140px; border-radius: 5px;  ">Export
			  CSV</button>
			  <!--<a href="<?=base_url('admin/register/add_pharmacy')?>"><button id="button" class="w3-button btn-primary" style="width: 140px; border-radius: 5px;  "><i class="fa fa-plus" aria-hidden="true"></i>Add</button></a>-->
		  </div>
		  </div>

		</div>
		<style>
		  option {
			background-color: #fff !important;
			color: #000 !important;
			text-align: left !important;
		  }

		  .w3-sidebar {
			height: 100%;
			width: 400px;
			background-color: #fff;
			position: fixed !important;
			top: 0px;
			z-index: 2076 !important;
			overflow: auto;
		  }

		  .w3-bar-block .w3-bar-item {
			width: auto;
			display: block;
			border: none;
			white-space: normal;
			float: none;
			outline: 0;
		  }

		  @media(max-width:500px) {
			.btn-primary {
			  width: 100%;

			}
		  }
		</style>

	  </div>


	  <!-- Payment Settlement Filters -->
        <div class="card mt-3 mb-4">
          <div class="card-body">
            <!--<h4 class="mb-3">Hospital Payment Settlement</h4>-->
            <form id="paymentFilterForm">
              <div class="row">
                  <div class="col-md-3">
                  <label>Diagnostics</label>
                    <select class="form-select" id="hospital_id" required placeholder="Diagnostic">
                        <option value="">Select Diagnostic</option>
                        <?php foreach($hospitals as $row){?>
                            <option value="<?=$row['id']?>"><?=$row['name']?></option>
                        <?php } ?>
                    </select>
                </div>
                <div class="col-md-3">
                  <label>Start Date</label>
                  <input type="date" id="start_date" name="start_date" class="form-control" required onkeydown="return false;" />
                </div>
                <div class="col-md-3">
                  <label>End Date</label>
                  <input type="date" id="end_date" name="end_date" class="form-control" required onkeydown="return false;" />
                </div>
                
                <div class="col-md-3 d-flex align-items-end">
                  <button type="button" id="fetchPayments" class="btn btn-primary w-100">Fetch Payments</button>
                </div>
              </div>
            </form>
          </div>
        </div>
        
        <!--<script>-->
        <!--  function formatDate(date) {-->
        <!--      const year = date.getFullYear();-->
        <!--      const month = (date.getMonth() + 1).toString().padStart(2, '0');-->
        <!--      const day = date.getDate().toString().padStart(2, '0');-->
        <!--      return `${year}-${month}-${day}`;-->
        <!--    }-->
            
        <!--    document.addEventListener("DOMContentLoaded", function () {-->
        <!--      const today = new Date();-->
        <!--      const year = today.getFullYear();const month = today.getMonth(); // 0-indexed-->
              
            
        <!--      const firstDay = new Date(year, month, 1);-->
        <!--      const lastDay = new Date(year, month + 1, 0);-->
            
        <!--      const minDate = formatDate(firstDay);-->
        <!--      const maxDate = formatDate(lastDay);-->
            
        <!--      const startDate = document.getElementById("start_date");-->
        <!--      const endDate = document.getElementById("end_date");-->
            
        <!--      startDate.min = minDate;-->
        <!--      startDate.max = maxDate;-->
        <!--      endDate.min = minDate;-->
        <!--      endDate.max = maxDate;// Optional: set default values-->
            
              
        <!--      startDate.value = minDate;-->
        <!--      endDate.value = maxDate;-->
        <!--    });-->
        <!--</script>-->
        
        <script>
        document.addEventListener('DOMContentLoaded', function () {
            const startDateInput = document.getElementById('start_date');
            const endDateInput = document.getElementById('end_date');
        
            startDateInput.addEventListener('change', function () {
                endDateInput.min = this.value;
        
                // Optional: clear end date if it's before the new start date
                if (endDateInput.value && endDateInput.value < this.value) {
                    endDateInput.value = '';
                }
            });
        });
        </script>
        <!-- Payment Table -->
        <div class="card mb-4">
          <div class="card-body table-responsive">
            <table class="table table-bordered" id="hospitalPaymentTable">
              <thead>
                <tr>
                  <th>Diagnostic Name</th>
                  <th>Commission (%)</th>
                  <th>Total Revenue (₹)</th>
                  <th>Diagnostic Revenue (₹)</th>
                  <th>Transferred (₹)</th>
                  <th>Pending (₹)</th>
                  <th>Transfer Amount (₹)</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody id="hospitalPaymentBody">
                <!-- Data populated via JS -->
              </tbody>
            </table>
          </div>
        </div>


	<style>
	  .Options {
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
	  }

	  .btn .btn-primary {
		width: 10% !important;
	  }

	  .TABLE2 {
		display: none;
	  }

	  .TABLE1 {
		display: block;
	  }

	  @media(max-width:600px) {

		/* .MODAL1,
		  .MODAL {
			display: block;
			padding-bottom: 10px!important;
		  } */

		.select.btn {
		  width: 100% !important;
		}

		.TABLE1 {
		  display: none;
		}

		.TABLE2 {
		  display: block;
		}
	  }
	</style>
	
	
	<script>
      $('#fetchPayments').on('click', function () {
        const hospital_id = $('#hospital_id').val();
        const start = $('#start_date').val();
        const end = $('#end_date').val();
    
        if (!hospital_id) {
          showToast('Error', 'Please select diagnostic', 'error');
          return;
        }
        
        if (!start) {
          showToast('Error', 'Please select start date', 'error');
          return;
        }
        
        if (!end) {
          showToast('Error', 'Please select end date', 'error');
          return;
        }
    
        // Validate: End date must not be before Start date
        if (new Date(end) < new Date(start)) {
          showToast('Error', 'End Date cannot be earlier than Start Date', 'error');
          return;
        }
    
        $.ajax({
          url: '<?= base_url("admin/register/get_diagnostic_revenue_summary") ?>',
          method: 'POST',
          data: { hospital_id: hospital_id, start_date: start, end_date: end },
          success: function (response) {
            let parsed;
            try {
              parsed = JSON.parse(response);
            } catch (e) {
              console.error("JSON parse error:", e);
              showToast('Error', 'Invalid server response', 'error');
              return;
            }
    
            if (parsed.status === false) {
              showToast('Warning', parsed.message || 'Commission not set', 'warning');
              return;
            }
    
            const data = Array.isArray(parsed.data) ? parsed.data : [];
            const tbody = $('#hospitalPaymentBody');
            tbody.empty();
    
            if (data.length === 0) {
              tbody.append('<tr><td colspan="8" class="text-center">No records found</td></tr>');
              return;
            }
    
            data.forEach(row => {
              const pending = parseFloat(row.pending) || 0;
    
              tbody.append(`
                <tr data-hospital-id="${row.hospital_id}">
                  <td>${row.hospital_name}</td>
                  <td>${row.commission}</td>
                  <td>${row.total_amount}</td>
                  <td>${row.hospital_revenue}</td>
                  <td>${row.transferred_amount}</td>
                  <td>${pending}</td>
                  <td>
                    <input type="number" class="form-control transfer-amount" placeholder="Enter amount" min="0" max="${pending}">
                  </td>
                  <td>
                    <button class="btn btn-success submit-transfer">Submit</button>
                  </td>
                </tr>
              `);
            });
          },
          error: function () {
            showToast('Error', 'Failed to fetch data.', 'error');
          }
        });
      });
    
      $(document).on('click', '.submit-transfer', function () {
        const row = $(this).closest('tr');
        const hospitalId = row.data('hospital-id');
        const input = row.find('.transfer-amount');
        const amount = parseFloat(input.val()) || 0;
        const max = parseFloat(input.attr('max')) || 0;
    
        if (!amount || amount <= 0) {
          showToast('Error', 'Please enter a valid transfer amount.', 'error');
          return;
        }
    
        if (amount > max) {
          showToast('Error', `Amount cannot exceed pending amount (${max})`, 'error');
          return;
        }
    
        $.ajax({
          url: '<?= base_url("admin/register/save_diagnostic_payment_transfer") ?>',
          method: 'POST',
          data: {
            hospital_id: hospitalId,
            transfer_amount: amount,
            start_date: $('#start_date').val(),
            end_date: $('#end_date').val()
          },
          success: function () {
            showToast('Success', 'Transfer recorded successfully.', 'success');
            $('#fetchPayments').click(); // Refresh table
          },
          error: function () {
            showToast('Error', 'Failed to save transfer.', 'error');
          }
        });
      });
    </script>




<!-- Include Font Awesome for icons -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">


<style>

/* Style for the control buttons in the table */
td.dt-control {
    text-align: center; /* Center the icon */
    cursor: pointer;    /* Make the icon clickable */
    font-size: 1.2rem;  /* Adjust icon size */
    color: #007bff;     /* Primary color (Bootstrap default) */
}

td.dt-control i {
    transition: transform 0.2s ease, color 0.2s ease;
}

/* Change color on hover */
td.dt-control:hover i {
    color: #0056b3; /* Darker blue on hover */
}

/* Animate when switching between + and - */
tr.shown td.dt-control i {
    transform: rotate(180deg); /* Flip the minus icon for a smooth effect */
    color: #dc3545; /* Change to a danger (red) color for better visibility */
}

    tr.shown {
    background-color: #f9f9f9; /* Highlight rows when expanded */
}

.dtr-hidden{
    display:block!important;
}

/* Toggle switch container */
.switch {
    position: relative;
    display: inline-block;
    width: 34px;
    height: 20px;
}

/* Hide the default checkbox */
.switch input {
    display: none;
}

/* Slider (background and knob) */
.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
}

.slider:before {
    position: absolute;
    content: '';
    height: 14px;
    width: 14px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50%;
}

/* When checked */
input:checked + .slider {
    background-color: #4caf50;
}

input:checked + .slider:before {
    transform: translateX(14px);
}

/* Container for the details */
.p-3 {
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
    margin-top: 10px;
}

/* Styling for the action buttons */
button {
    margin-right: 10px; /* Space between buttons */
}

button i {
    margin-right: 5px; /* Space between icon and button text */
}

/* Button customization */
.btn {
    font-size: 14px;
    font-weight: bold;
    padding: 5px 15px;
    display: inline-flex;
    align-items: center;
}

.btn-primary {
    background-color: #007bff;
    border-color: #007bff;
}

.btn-primary:hover {
    background-color: #0056b3;
    border-color: #0056b3;
}

.btn-danger {
    background-color: #dc3545;
    border-color: #dc3545;
}

.btn-danger:hover {
    background-color: #c82333;
    border-color: #bd2130;
}

/* Image styling */
.img {
    border-radius: 50%;
    border: 2px solid #ddd;
    margin-top: 10px;
    margin-bottom: 10px;
}

/* Styling for strong labels */
strong {
    display: inline-block;
    width: 120px;
    font-weight: bold;
    color: #333;
}

/* Layout for labels and values */
.p-3 strong {
    margin-bottom: 5px;
}

.p-3 {
    line-height: 1.6;
}

/* Responsive design: Ensure it looks good on smaller screens */
@media (max-width: 768px) {
    .p-3 {
        padding: 15px;
    }

    .btn {
        font-size: 12px;
        padding: 4px 10px;
    }

    .p-3 strong {
        width: auto; /* Allow labels to adjust on smaller screens */
    }
}

  select.form-select {
    min-width: 140px;
  }
  .dataTables_wrapper .dataTables_scroll {
    overflow: auto;
  }
  
  table.dataTable tbody td {
    vertical-align: top;
  }
    table.dataTable tbody tr.shown td.dt-control:before {
        content: "\f068"; /* FontAwesome minus icon */
    }

</style>

    
  </div>
</div>
<!-- / Content -->

    
 
  <!-- Csv file download  -->
  <script>
    function download_csv(csv, filename) {
      var csvFile;
      var downloadLink;

      // CSV FILE
      csvFile = new Blob([csv], { type: "text/csv" });

      // Download link
      downloadLink = document.createElement("a");

      // File name
      downloadLink.download = filename;

      // We have to create a link to the file
      downloadLink.href = window.URL.createObjectURL(csvFile);

      // Make sure that the link is not displayed
      downloadLink.style.display = "none";

      // Add the link to your DOM
      document.body.appendChild(downloadLink);

      // Lanzamos
      downloadLink.click();
    }

    function export_table_to_csv(html, filename) {
      var csv = [];
      var rows = document.querySelectorAll("#Example tr");

      for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++)
          row.push(cols[j].innerText);

        csv.push(row.join(","));
      }

      // Download CSV
      download_csv(csv.join("\n"), filename);
    }

    document.querySelector("#button").addEventListener("click", function () {
      var html = document.querySelector("#Example").outerHTML;
      export_table_to_csv(html, "UserData.csv");
    });
  </script>

<!-- Toastr CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<!-- Toastr JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>


<script>
// Show toast using jQuery
function showToast(title, message, type) {
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000",
    };

    if (type === 'success') {
        toastr.success(message, title);
    } else if (type === 'error') {
        toastr.error(message, title);
    } else if (type === 'info') {
        toastr.info(message, title);
    } else if (type === 'warning') {
        toastr.warning(message, title);
    }
}


</script>