<?php
session_start();
include("dbConfig.php");
if(isset($_SESSION['username']) && isset($_SESSION['name']))
{
    $username=$_SESSION['username'];
    $name=$_SESSION['name'];
}
else
{
     echo '<META http-equiv="refresh" content="0;logout.php">';
}
if (isset($_POST['datefrom']) && isset($_POST['patientType'])) {
    $from = $_POST['datefrom'];
    $to = $_POST['dateto'];
    $patientType = $_POST['patientType'];
    $doctorConditionOPD = $doctorConditionIPD = "";

    if (isset($_POST['doctor']) && $_POST['doctor'] !== 'All') {
        $selectedDoctor = mysqli_real_escape_string($db, $_POST['doctor']);
        $doctorConditionOPD = "AND p.Consultant = '$selectedDoctor'";
        $doctorConditionIPD = "AND d.doc_name = '$selectedDoctor'";
    }

    $query = $query1 = $query2 = $examinationQuery = null;

    if ($patientType == "OPD") {
        $query1 = mysqli_query($db, "
                                    SELECT DISTINCT p.Name AS PatientName, p.Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
                                                    ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare,
                                                    d.charge AS DoctorCharge
                                    FROM bill AS b
                                    INNER JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
                                    INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
                                    LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
                                    INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
                                    WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'OPD' $doctorConditionOPD
                                    ORDER BY p.Consultant, b.BDate
                                 ");

        if (!$query1) {
            die("Error in OPD query: " . mysqli_error($db));
        }
    } elseif ($patientType == "IPD") {
        $query2 = mysqli_query($db, "
                                    SELECT DISTINCT p.Name AS PatientName, d.doc_name AS Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
                                                    ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare
                                    FROM bill AS b
                                    INNER JOIN patientdetails AS p ON b.PatientId = p.PatId
                                    INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
                                    LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
                                    INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
                                    WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'IPD' $doctorConditionIPD
                                    ORDER BY d.doc_name, b.BDate
        ");

        if (!$query2) {
            die("Error in IPD query: " . mysqli_error($db));
        }
    } elseif ($patientType == "BOTH") {
        // OPD Query for BOTH
        $query1 = mysqli_query($db, "
                                    SELECT DISTINCT p.Name AS PatientName, p.Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
                                                    ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare,
                                                    d.charge AS DoctorCharge
                                    FROM bill AS b
                                    INNER JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
                                    INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
                                    LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
                                    INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
                                    WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'OPD' $doctorConditionOPD
                                    ORDER BY p.Consultant, b.BDate
                                ");

        // IPD Query for BOTH
        $query2 = mysqli_query($db, "
                                    SELECT DISTINCT p.Name AS PatientName, d.doc_name AS Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
                                                    ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare
                                    FROM bill AS b
                                    INNER JOIN patientdetails AS p ON b.PatientId = p.PatId
                                    INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
                                    LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
                                    INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
                                    WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'IPD' $doctorConditionIPD
                                    ORDER BY d.doc_name, b.BDate
        ");

        if (!$query1 || !$query2) {
            die("Error in BOTH query: " . mysqli_error($db));
        }
    }


    // // Consultant Condition Escaping
    // $doctorConditionOPD = !empty($doctorConditionOPD) ? "AND p.Consultant = '" . mysqli_real_escape_string($db, $doctorConditionOPD) . "'" : "";
    // $doctorConditionIPD = !empty($doctorConditionIPD) ? "AND d.doc_name = '" . mysqli_real_escape_string($db, $doctorConditionIPD) . "'" : "";

    // // Execute the Query
    // if ($patientType == "OPD") {
    //     // OPD Query
    //     $query1 = mysqli_query($db, "
    //     SELECT DISTINCT 
    //         p.Name AS PatientName, 
    //         p.Consultant, 
    //         b.BDate AS BillDate, 
    //         b.BillNo, 
    //         b.PayableAmount,
    //         ROUND(b.PayableAmount * 0.7) AS DoctorShare, 
    //         ROUND(b.PayableAmount * 0.3) AS HospitalShare,
    //         d.charge AS DoctorCharge
    //     FROM bill AS b
    //     INNER JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
    //     INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
    //     LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
    //     INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
    //     WHERE b.BDate >= '$from' AND b.BDate <= '$to' 
    //     AND b.PatientType = 'OPD' 
    //     $doctorConditionOPD
    //     ORDER BY p.Consultant, b.BDate
    // ");

    //     if (!$query1) {
    //         die("Error in OPD query: " . mysqli_error($db));
    //     }
    // } elseif ($patientType == "IPD") {
    //     // IPD Query
    //     $query2 = mysqli_query($db, "
    //     SELECT DISTINCT 
    //         p.Name AS PatientName, 
    //         d.doc_name AS Consultant, 
    //         b.BDate AS BillDate, 
    //         b.BillNo, 
    //         b.PayableAmount,
    //         ROUND(b.PayableAmount * 0.7) AS DoctorShare, 
    //         ROUND(b.PayableAmount * 0.3) AS HospitalShare
    //     FROM bill AS b
    //     INNER JOIN patientdetails AS p ON b.PatientId = p.PatId
    //     INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
    //     LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
    //     INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
    //     WHERE b.BDate >= '$from' AND b.BDate <= '$to' 
    //     AND b.PatientType = 'IPD' 
    //     $doctorConditionIPD
    //     ORDER BY d.doc_name, b.BDate
    // ");

    //     if (!$query2) {
    //         die("Error in IPD query: " . mysqli_error($db));
    //     }
    // } elseif ($patientType == "BOTH") {
    //     // OPD Query for BOTH
    //     $query1 = mysqli_query($db, "
    //                                 SELECT DISTINCT p.Name AS PatientName, p.Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
    //                                     ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare,
    //                                     d.charge AS DoctorCharge
    //                                 FROM bill AS b
    //                                 INNER JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
    //                                 INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
    //                                 LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
    //                                 INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
    //                                 WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'OPD' $doctorConditionOPD
    //                                 ORDER BY p.Consultant, b.BDate
    // ");

    //     // IPD Query for BOTH
    //     $query2 = mysqli_query($db, "
    //                                 SELECT DISTINCT p.Name AS PatientName, d.doc_name AS Consultant, b.BDate AS BillDate, b.BillNo, b.PayableAmount,
    //                                     ROUND(b.PayableAmount * 0.7) AS DoctorShare, ROUND(b.PayableAmount * 0.3) AS HospitalShare
    //                                 FROM bill AS b
    //                                 INNER JOIN patientdetails AS p ON b.PatientId = p.PatId
    //                                 INNER JOIN billparticulars AS bp ON b.PatientId = bp.PatId
    //                                 LEFT JOIN edited_billparticulars AS ebp ON b.PatientId = ebp.PatId
    //                                 INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
    //                                 WHERE b.BDate >= '$from' AND b.BDate <= '$to' AND b.PatientType = 'IPD' $doctorConditionIPD
    //                                 ORDER BY d.doc_name, b.BDate
    // ");

    //     if (!$query1 || !$query2) {
    //         die("Error in BOTH query: " . mysqli_error($db));
    //     }
    // }




    $opdReport = [];
    $ipdReport = [];

    if ($patientType == "OPD" || $patientType == "BOTH") {
        while ($row = mysqli_fetch_assoc($query ?? $query1)) {
            $opdReport[] = $row;
        }
    }

    if ($patientType == "IPD" || $patientType == "BOTH") {
        while ($row = mysqli_fetch_assoc($query ?? $query2)) {
            $ipdReport[] = $row;
        }
    }

    $opdTotalPatients = $opdTotalAmount = $opdDoctorShare = $opdHospitalShare = 0;
    $ipdTotalPatients = $ipdTotalAmount = 0;

    $opd_cardiology_total = $opd_radiology_total = $opd_laboratory_total = 0;
    $ipd_cardiology_total = $ipd_radiology_total = $ipd_laboratory_total = 0;
    $data_found = false;

    if (isset($_POST['doctor']) && $_POST['doctor'] !== 'All') {
        $selectedDoctor = mysqli_real_escape_string($db, $_POST['doctor']);
        $doctorCondition = "AND (e.consultant = '$selectedDoctor')";
    } else {
        $doctorCondition = "";
    }

    $examinationQuery = mysqli_query($db, "
                                            SELECT
                                                optionlab, 
                                                SUM(Amount) AS TotalAmount,
                                                CASE 
                                                    WHEN PatId LIKE '%OPD%' THEN 'OPD'
                                                    ELSE 'IPD'
                                                END AS patient_type
                                            FROM examination e
                                            LEFT JOIN docotorslist d ON e.consultant = d.doc_name
                                            WHERE e.created_at >= '$from' AND e.created_at <= '$to'
                                            $doctorCondition
                                            GROUP BY optionlab, patient_type
                                            ");
    $examinationData = [
        'OPD' => ['Cardiology' => 0, 'Radiology' => 0, 'Lab Test' => 0],
        'IPD' => ['Cardiology' => 0, 'Radiology' => 0, 'Lab Test' => 0],
    ];

    while ($row = $examinationQuery->fetch_assoc()) {
        $data_found = true; // Data is found
        $patient_type = $row['patient_type'];
        $optionlab = $row['optionlab'];
        $totalAmount = $row['TotalAmount'];

        $examinationData[$patient_type][$optionlab] = $totalAmount;
    }
    $opd_cardiology_total = $examinationData['OPD']['Cardiology'];
    $opd_radiology_total = $examinationData['OPD']['Radiology'];
    $opd_laboratory_total = $examinationData['OPD']['Lab Test'];
    $ipd_cardiology_total = $examinationData['IPD']['Cardiology'];
    $ipd_radiology_total = $examinationData['IPD']['Radiology'];
    $ipd_laboratory_total = $examinationData['IPD']['Lab Test'];
}

?>
<!DOCTYPE html>
<html>
<head>
  <title>
    
  </title>
  <meta charset="UTF-8">
  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css'>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Raleway:300,400,500,700,800|Montserrat:300,400,700" rel="stylesheet">
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css'>

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/ionicons/css/ionicons.min.css" rel="stylesheet">
  <link href="assets/vendor/animate.css/animate.min.css" rel="stylesheet">
  <link href="assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <link href="assets/vendor/venobox/venobox.css" rel="stylesheet">
  <link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <script src="jquery.dependent.fields.js"></script>
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery.min.js"></script>
<script src="jquery.dependent.fields.js"></script>

<link rel="stylesheet" href="js/select2.min.css" />
<style type="text/css">
.nav-menu a {
    padding: 3px 3px;
}

  .hide {
  display: none;
}
h4{
  padding-top: 5px;
  padding-bottom: 0px;
  color:#1abfbf;
  font-weight: bold;
}
hr{
  background-color:#1abfbf;
}
.footer {
   position: fixed;
   left: 0;
   bottom: 0;
   width: 100%;
   background-color: #efe8e8;
   color: black;
   text-align: center;
   padding:4px;
   font-size:12px;
}.footer a{
  font-weight: bold;
  color:#0c0c67;
}
</style>

</head>
<body>
  <div style="text-align: center">
     <img src="assets/img/logo.png" width="100px" height="100px">
  </div>
      <header id="header">     

    <div class="container">
    <nav id="nav-menu-container">
        <ul class="nav-menu">
      <li class="menu-active">
        <a class="nav-link" style="padding:2;font-size:14px" href="index.php">Home</a>
      </li>
            <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">IPD Patients</a>
        <ul>
              <li><a href="AddPatient.php">IPD Patient Registration</a></li>
              <li><a href="AddAdvance.php">IPD add Advance</a></li>
              <li><a href="UpdateWard.php">Update Ward</a></li>
              <li><a href="IPDPatients.php">View IPD Patients</a></li>
              
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">OPD Patients</a>
        <ul>
            <li><a href="OPDRegistration.php">OPD Patient Registration</a></li>
            <li><a href="OPDPatients.php">View OPD Patients</a></li>
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">Staff</a>
        <ul>
              <li><a href="AddStaff.php">Add Staff</a></li>
              <li><a href="StaffList.php">Staff List</a></li>
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">Billing</a>
        <ul>
              <li><a href="billingId.php">Generate Consolidate Bill</a></li>
              <li><a href="InvestigationId.php">Generate Investigation Bill</a></li>
              <li><a href="FinaleBillId.php">Generate Discharge Bill</a></li>
              <li><a href="SearchBill.php">Search Bill</a></li>
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">Particular</a>
        <ul>
              <li><a href="AddParticulars.php">Add Particulars</a></li>
              <li><a href="ViewParticulars.php">View Particulars</a></li>
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#">Report</a>
        <ul>
               <li><a href="UploadReport.php">Upload Patient Report</a></li>
              <li><a href="DailyTrans.php">Transactions</a></li>
              <li><a href="userTrans.php">User Transactions</a></li>
              <li><a href="ViewReport.php">View Patient Reports</a></li>
              
        </ul>
      </li>
      <li class="menu-has-children">
        <a class="nav-link" style="padding:2;font-size:14px" href="#" style="font-size:15px"><? echo $name?></a>
        <ul>
               <li><a href="logout.php">Logout</a></li>
              <li><a href="ResetPassword.php">Reset Password</a></li>              
        </ul>
      </li>
        </ul>
      </nav><!-- #nav-menu-container -->
    </div>
  </header><!-- End Header -->   
  <section>
  <div class="row">
<div class="col-md-2"></div> 
<div class="col-md-8">
  <div class="shadow p-3 mb-5 bg-light rounded">
 <form method="POST" action="">
                                <div class="row">
                                    <div class="form-group col">
                                        <label for="datefrom">From</label>
                                        <input class="form-control" type="date" name="datefrom" id="datefrom" value="<?php echo isset($_POST['datefrom']) ? htmlspecialchars($_POST['datefrom']) : ''; ?>" required>
                                    </div>
                                    <div class="form-group col">
                                        <label for="dateto">To</label>
                                        <input class="form-control" type="date" name="dateto" id="dateto" value="<?php echo isset($_POST['dateto']) ? htmlspecialchars($_POST['dateto']) : ''; ?>" required>
                                    </div>
                                    </div>
                                    <div class="row">
                                    <div class="form-group col">
                                        <label for="patientType">Patient Type</label>
                                        <select class="form-control" name="patientType" id="patientType" required>
                                            <!-- <option value="BOTH" <?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'BOTH') ? 'selected' : ''; ?>>IPD & OPD</option> -->
                                            <option value="OPD" <?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'OPD') ? 'selected' : ''; ?>>OPD</option>
                                            <option value="IPD" <?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'IPD') ? 'selected' : ''; ?>>IPD</option>
                                        </select>
                                    </div>
                                    <div class="form-group col">
                                        <label for="doctor">Doctor</label>
                                        <select class="form-control" name="doctor" id="doctor" required>
                                            <option value="All">All</option>
                                            <?php
                                            // Fetch doctor names from docotorslist table for dropdown
                                            $doctorQuery = mysqli_query($db, "SELECT doc_name FROM docotorslist");
                                            while ($doctorRow = mysqli_fetch_assoc($doctorQuery)) {
                                                $selected = (isset($_POST['doctor']) && $_POST['doctor'] == $doctorRow['doc_name']) ? 'selected' : '';
                                                echo "<option value='{$doctorRow['doc_name']}' $selected>{$doctorRow['doc_name']}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col">
                                        <button type="submit" class="btn btn-primary" id="viewbtn">View</button>
                                    </div>
                                </div>
                            </form>

                            <?php if (!empty($opdReport) || !empty($ipdReport)): ?>

                                <button name="export" class="btn btn-primary" onclick="exportToExcel()">Export to Excel</button>
                                <h2>Consultant Fee <?php echo $patientType === 'BOTH' ? 'OPD and IPD' : $patientType; ?> Bills Details From <?php echo date("d-m-Y", strtotime($from)) . " To " . date("d-m-Y", strtotime($to)); ?></h2>
                                <table border="1" class="table table-hover" id="tblexportData">
                                    <thead>
                                        <tr>
                                            <th>SI NO.</th>
                                            <!--<th>Patient Name</th>-->
                                            <th>Patient Name</th>
                                            <th>Bill Date</th>
                                            
                                        </tr>
                                    </thead>
                                    <tbody>
    <?php
    $currentConsultant = null;
    $doctorTotalOPD = 0;
    $doctorTotalIPD = 0;
    $serialNumber = 1; // Initialize the serial number counter

    // Merge OPD and IPD reports and sort by Consultant name
    $mergedReport = array_merge($opdReport, $ipdReport);
    usort($mergedReport, function ($a, $b) {
        return strcmp($a['Consultant'], $b['Consultant']);
    });

    foreach ($mergedReport as $row):
        if ($currentConsultant !== $row['Consultant']) {
            if ($currentConsultant !== null) {
                if ($patientType === 'OPD' || $patientType === 'BOTH') {
                    echo "<tr>
                            <td colspan='3'><strong>Total for OPD:</strong></td>
                            <td><strong>" . number_format($doctorTotalOPD, 2) . "</strong></td>
                        </tr>";
                }
                $doctorTotalOPD = 0;
            }
            $currentConsultant = $row['Consultant'];
            echo "<tr>
                    <td colspan='4'><strong>Consultant Doctor: $currentConsultant</strong></td>
                 </tr>";
        }

        if ($patientType === 'OPD') {
            $consultantShare = isset($row['DoctorCharge']) ? $row['DoctorCharge'] : 111.00;
        } elseif (isset($row['ConsultantShare'])) {
            $consultantShare = $row['ConsultantShare'];
        } else {
            $consultantShare = round($row['PayableAmount'] * 0.7);
        }

        if (in_array($row, $opdReport)) {
            $doctorTotalOPD += $consultantShare;
        } elseif (in_array($row, $ipdReport)) {
            $doctorTotalIPD += $consultantShare;
        }

        // Display bill details with dynamically generated serial number
        echo "<tr>
                <td>" . $serialNumber++ . "</td> <!-- Increment the serial number -->
                <td>" . htmlspecialchars($row['PatientName'] ?? '') . "</td>
                <td>" . htmlspecialchars(date("d/m/Y", strtotime($row['BillDate']))) . "</td>
             </tr>";
    endforeach;
    ?>
</tbody>

                                </table>
                            <?php endif; ?>



                            <script>
                                function exportToExcel() {
                                    // Get filter values
                                    let from = document.getElementById("datefrom").value;
                                    let to = document.getElementById("dateto").value;
                                    let patientType = document.getElementById("patientType").value;
                                    let doctor = document.getElementById("doctor").value;

                                    // Construct filename
                                    let doctorName = (doctor !== 'All') ? `Dr. ${doctor}` : "All Doctors";
                                    let filename = `Report_${from}_to_${to}_${patientType}_${doctorName}.csv`;

                                    // Collect the data from the table
                                    let table = document.getElementById("tblexportData");
                                    console.log(table); // Debug: Check if the table is found

                                    if (!table) {
                                        alert("Table not found. Make sure the table exists.");
                                        return; // Exit the function if the table is not found
                                    }

                                    let rows = Array.from(table.querySelectorAll("tr"));

                                    // Generate CSV content
                                    let csvContent = "";
                                    rows.forEach(row => {
                                        let cols = Array.from(row.querySelectorAll("td, th"));
                                        let rowData = cols.map(col => `"${col.innerText.replace(/"/g, '""')}"`).join(",");
                                        csvContent += rowData + "\n";
                                    });

                                    // Create a Blob for the CSV data and create a download link
                                    let blob = new Blob([csvContent], {
                                        type: "text/csv;charset=utf-8;"
                                    });
                                    let link = document.createElement("a");
                                    let url = URL.createObjectURL(blob);
                                    link.setAttribute("href", url);
                                    link.setAttribute("download", filename);

                                    // Trigger the download
                                    link.style.visibility = "hidden";
                                    document.body.appendChild(link);
                                    link.click();
                                    document.body.removeChild(link);
                                }
                            </script>
</div>
</div>
<div class="col-md-2"></div> 
</div>
  </section>
  <div class="footer">
        &copy; Copyright 2024 All Rights Reserved <strong>Vidyaranya Hospital PVt LTD.</strong>. | Designed by <a href="http://www.vatsinsoft.in/">Vatsin Soft</a>
      </div>
 <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
  <script src="assets/vendor/jquery/jquery.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/jquery.easing/jquery.easing.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>
  <script src="assets/vendor/wow/wow.min.js"></script>
  <script src="assets/vendor/venobox/venobox.min.js"></script>
  <script src="assets/vendor/owl.carousel/owl.carousel.min.js"></script>
  <script src="assets/vendor/jquery-sticky/jquery.sticky.js"></script>
  <script src="assets/vendor/superfish/superfish.min.js"></script>
  <script src="assets/vendor/hoverIntent/hoverIntent.js"></script>
  <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
  <script src="assets/js/main.js"></script>
  <script src="js/select2.min.js"></script>
  <script type="text/javascript">
        $("#doctor").select2( {
        	placeholder: "Select",
        	allowClear: true
    	
    	} );
  </script>
</body>
</html>