<?php
$uri = $this->uri->segment(3);
$page = 'online_doctor_completed_doctor_bookings';
//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>Completed Online Doctor Bookings</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>


	  <div class=" card-datatable table-responsive TABLE1">

		<table id="Example" class="Table display nowrap" style="width:100%">
		  <thead>
			<tr>
			  <th></th>
			  <th>ID</th>
			  <th>Booking Id</th>
			  <th>Consult Type</th>
			  <th>Doctor Details</th>
			  <th>Patient Details</th>
    		  <th>Booking Status</th>
    		  <th>Booking Date</th>
    		  <th>Time</th>
    		  <th>Actual Fee</th>
    		  <th>Total Fee</th>
    		  <th>Coupon Name</th>
    		  <th>Coupon Percentage</th>
    		  <th>Coupon Discount</th>
    		  <th>Payment Type</th>
			</tr>
		  </thead>
		</table>
	  </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>
        $(document).ready(function () {
        // Format the child row
        function format(details) {
            var baseURL = "<?php echo base_url(); ?>";
            return `
                <div class="p-3">
                <strong>Medicines: </strong> 
                    <a href="#" class="view-product-details" data-medicines='${JSON.stringify(details.medicines)}' data-booking-id="${details.booking_id}">
                        <i class="fa fa-eye"></i>
                    </a>
            
                 <br>
                 
                 <strong>Tests: </strong> 
                    <a href="#" class="view-tests-details" data-tests='${JSON.stringify(details.tests)}' data-booking-id="${details.booking_id}">
                        <i class="fa fa-eye"></i>
                    </a>
                </a>
            
                 <br>
                 
                 <strong>Notes: </strong> 
                    <a href="#" class="view-notes-details" data-notes='${JSON.stringify(details.notes)}' data-booking-id="${details.booking_id}">
                        <i class="fa fa-eye"></i>
                    </a>
            
                 <br>
                 
                    <strong>Created on: </strong> ${details.created_on} <br>
                    <strong>Transaction Id: </strong> ${details.transaction_id ? details.transaction_id : 'N/A'}
                </div>
            `;
        }

        // Initialize DataTable
        const table = $('#Example').DataTable({
            serverSide: true,
            processing: true,
            scrollX: true,
            scrollY: '400px',
            scrollCollapse: true,
            ajax: {
                url: '<?= base_url("admin/register/get_online_doctor_completed_doctor_bookings") ?>',
                type: 'POST',
                dataSrc: 'data'
            },
            columns: [
                {
                    className: 'dt-control',
                    orderable: false,
                    data: null,
                    defaultContent: '<i class="fas fa-plus-circle"></i>', // Icon for toggling
                },
                { data: 'id' },
                { data: 'booking_id' },
                { data: 'consult_type' },
                {
                    data: null,
                    render: function (data ,type, row) {
                        return `
                            <a href="#" 
                              class="view-doctor-details"
                              data-doctor_name="${data.name}"
                              data-doctor_mobile="${data.doctor_mobile}"
                              data-doctor_image="${data.doctor_image}",
                              data-doctor_email="${data.doctor_email}"
                              data-doctor_qualification="${data.qualification}"
                            >
                                <i class="fa fa-eye"></i> ${row.name}
                            </a>`;
                    }
                },
                {
                    data: null,
                    render: function (data ,type, row) {
                        return `
                            <a href="#" 
                              class="view-user-details"
                              data-patient_name="${data.patient_name}"
                              data-mobile="${data.mobile}"
                              data-image="${data.image}",
                              data-email="${data.email}"
                              data-dob="${data.dob}"
                              data-blood_group="${data.blood_group}"
                            >
                                <i class="fa fa-eye"></i> ${row.patient_name}
                            </a>`;
                    }
                },
                { data: 'booking_status'},
                { data: 'date'},
                { data: 'time'},
                { data: 'fee' },
                { data: 'consultation_fee' },
                { data: 'coupon_name' },
                { data: 'coupon_percentage' },
                { data: 'coupon_discount' },
                { data: 'payment_type' }
            ],
            order: [[1, 'asc']],
            pageLength: 10
        });
        
        // Adjust column widths after init
        setTimeout(() => {
          table.columns.adjust().draw(false);
        }, 500);
        
    
        // Handle expand/collapse details
        $('#Example tbody').on('click', 'td.dt-control', function () {
            const tr = $(this).closest('tr');
            const row = table.row(tr);

            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
                $(this).html('<i class="fas fa-plus-circle"></i>');
            } else {
                row.child(format(row.data())).show();
                tr.addClass('shown');
                $(this).html('<i class="fas fa-minus-circle"></i>');
            }
        });
        
        // Handle doctor details Modal
        $('#Example').on('click', '.view-doctor-details', function (e) {
            e.preventDefault();

            const userdetails = $(this).data();
            const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";

            const doctordetailsHtml = `
            
            <div class="row">
                <div class="col-lg-6">
                    <p><strong>Name:</strong> ${userdetails.doctor_name}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Mobile:</strong> ${userdetails.doctor_mobile}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Image:</strong> <img class="img" src="${bharosa_base_url}${userdetails.doctor_image}" alt="image" width="60"> </p>
                </div>
        
                <div class="col-lg-6">
                    <p><strong>Qualification:</strong> ${userdetails.doctor_qualification}</p>
                </div>
                
            </div>
            `;

            $('#doctorDetails').html(doctordetailsHtml);
            $('#doctordetailsModal').modal('show');
        });
        
        // Handle user details Modal
        $('#Example').on('click', '.view-user-details', function (e) {
            e.preventDefault();

            const userdetails = $(this).data();
            const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";

            const userdetailsHtml = `
            
            <div class="row">
                <div class="col-lg-6">
                    <p><strong>Name:</strong> ${userdetails.patient_name}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Mobile:</strong> ${userdetails.mobile}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Image:</strong> <img class="img" src="${bharosa_base_url}${userdetails.image}" alt="image" width="60"> </p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Email:</strong> ${userdetails.email}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>DOB:</strong> ${userdetails.dob}</p>
                </div>
                <div class="col-lg-6">
                    <p><strong>Blood Group:</strong> ${userdetails.blood_group}</p>
                </div>
                
            </div>
            `;

            $('#userDetails').html(userdetailsHtml);
            $('#userdetailsModal').modal('show');
        });
        
        // Handle medicine details Modal
        $(document).on('click', '.view-product-details', function (e) {
            e.preventDefault();
            const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";
            const products = JSON.parse($(this).attr('data-medicines'));
            const bookingId = $(this).attr('data-booking-id');
            
            $('#modalBookingId').text(bookingId);
            
            let rowsHtml = '';
            products.forEach(p => {
                rowsHtml += `
                    <tr>
                        <td>${p.medicine}</td>
                        <td>${p.medicine_time}</td>
                    </tr>`;
            });
            
            $('#productDetailsTableBody').html(rowsHtml);
            $('#productDetailsModal').modal('show');
        });
        
        // Handle tests details Modal
        $(document).on('click', '.view-tests-details', function (e) {
            e.preventDefault();
            const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";
            const tests = JSON.parse($(this).attr('data-tests'));
            const bookingId = $(this).attr('data-booking-id');
            
            $('#modalBookingIdd').text(bookingId);
            
            let rowsHtml = '';
            tests.forEach(t => {
                rowsHtml += `
                    <tr>
                        <td>${t.test}</td>
                        <td>${t.test_instruction}</td>
                    </tr>`;
            });
            
            $('#testsDetailsTableBody').html(rowsHtml);
            $('#testsDetailsModal').modal('show');
        });
        
        // Handle notes details Modal
        $(document).on('click', '.view-notes-details', function (e) {
            e.preventDefault();
            const bharosa_base_url = "<?php echo $this->config->item('bharosa_base_url'); ?>";
            const notes = JSON.parse($(this).attr('data-notes'));
            const bookingId = $(this).attr('data-booking-id');
            
            $('#modalBookingIddd').text(bookingId);
            
            let rowsHtml = '';
            notes.forEach(n => {
                rowsHtml += `
                    <tr>
                        <td>${n.notes}</td>
                    </tr>`;
            });
            
            $('#notesDetailsTableBody').html(rowsHtml);
            $('#notesDetailsModal').modal('show');
        });
    });
    </script>


<!-- User Modal -->
<div class="modal fade" id="userdetailsModal" tabindex="-1" aria-labelledby="userdetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="userdetailsModalLabel">User Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="userDetails" class="p-3">
          <!-- User details will be dynamically loaded here -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- User Modal -->

<!-- Doctor Modal -->
<div class="modal fade" id="doctordetailsModal" tabindex="-1" aria-labelledby="doctordetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="doctordetailsModalLabel">Doctor Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="doctorDetails" class="p-3">
          <!-- User details will be dynamically loaded here -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- Doctor Modal -->

<!-- Medicines Modal -->
<div class="modal fade" id="productDetailsModal" tabindex="-1" aria-labelledby="productDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg"> <!-- Use modal-lg for wider view -->
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Medicines for <span id="modalBookingId"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-bordered mb-0">
            <thead class="table-light">
              <tr>
                <th>Medicine</th>
                <th>Medicine Time</th>
              </tr>
            </thead>
            <tbody id="productDetailsTableBody">
              <!-- JS will inject product rows here -->
            </tbody>
          </table>
        </div>
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- Medicines Modal -->

<!-- tests Modal -->
<div class="modal fade" id="testsDetailsModal" tabindex="-1" aria-labelledby="testsDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg"> <!-- Use modal-lg for wider view -->
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Tests for <span id="modalBookingIdd"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-bordered mb-0">
            <thead class="table-light">
              <tr>
                <th>Test</th>
                <th>Test Instruction</th>
              </tr>
            </thead>
            <tbody id="testsDetailsTableBody">
              <!-- JS will inject product rows here -->
            </tbody>
          </table>
        </div>
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- tests Modal -->

<!-- notes Modal -->
<div class="modal fade" id="notesDetailsModal" tabindex="-1" aria-labelledby="notesDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg"> <!-- Use modal-lg for wider view -->
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Notes for <span id="modalBookingIddd"></span></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-bordered mb-0">
            <thead class="table-light">
              <tr>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody id="notesDetailsTableBody">
              <!-- JS will inject product rows here -->
            </tbody>
          </table>
        </div>
      </div>
      
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!-- tests Modal -->

<!-- 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>