<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Hide warnings and notices, show only fatal errors
error_reporting(E_ERROR);

// Or hide all errors (not recommended)
error_reporting(0);


session_start();
include("dbconfig.php"); // Make sure this file exists and sets up the $db connection

// Check if the user is logged in
if (!isset($_SESSION['username']) || !isset($_SESSION['password'])) {
    header('Location: logout.php'); // Use header for redirection
    exit();
}

// Initialize report arrays and data flags
$opdReport = [];
$opdproReport = [];
$ipdReport = [];
$bothReport = [];
$examinationData = [
    'OPD' => ['Cardiology' => 0, 'Radiology' => 0, 'Lab Test' => 0],
    'IPD' => ['Cardiology' => 0, 'Radiology' => 0, 'Lab Test' => 0],
];
$data_found = false;

// Check if the form has been submitted
if (isset($_POST['datefrom']) && isset($_POST['dateto']) && isset($_POST['patientType'])) {
    $from = $_POST['datefrom'];
    $to = $_POST['dateto'];
    $patientType = $_POST['patientType'];
    $selectedDoctor = isset($_POST['doctor']) && $_POST['doctor'] !== 'All' ? $_POST['doctor'] : '';

    $doctorConditionOPD = !empty($selectedDoctor) ? "AND bp.consultant = ?" : "";
    $doctorConditionIPD = !empty($selectedDoctor) ? "AND bp.consultant = ?" : "";
    $doctorConditionExamination = !empty($selectedDoctor) ? "AND (e.consultant = ?)" : "";

// --- ProcedureCharges Query ---
if ($patientType == "ProcedureCharges") {
    $procedureChargesSql = "
        SELECT DISTINCT
            ROUND(b.PayableAmount * 0.5) AS DoctorShare,
            ROUND(b.PayableAmount * 0.5) AS HospitalShare,
            d.charge AS DoctorCharge
        FROM bill AS b
        LEFT JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
        INNER JOIN billparticulars AS bp ON b.BillNo = bp.BillNo AND b.PatientId = bp.PatId -- Use BillNo for consistency
        LEFT JOIN edited_billparticulars AS ebp ON b.BillNo = ebp.BillNo -- Adjust join condition if needed
        LEFT JOIN docotorslist AS d ON bp.consultant = d.doc_name
        WHERE b.BDate >= ? AND b.BDate <= ?
        AND b.PatientType = 'ProcedureCharges'
        $doctorConditionOPD
        ORDER BY bp.consultant ASC, DAY(b.BDate) ASC;
    ";

    $stmt = $db->prepare($procedureChargesSql);
    if ($stmt === false) {
        die('ProcedureCharges Prepare failed: ' . htmlspecialchars($db->error));
    }

    if (!empty($selectedDoctor)) {
        $stmt->bind_param("sss", $from, $to, $selectedDoctor);
    } else {
        $stmt->bind_param("ss", $from, $to);
    }

    $stmt->execute();
    $queryProcedureCharges = $stmt->get_result();
    if ($queryProcedureCharges) {
        while ($row = $queryProcedureCharges->fetch_assoc()) {
            $procedureCharges[] = $row;
            $data_found = true;
        }
    }
    $stmt->close();
}
?>
<?

    // --- OPD Query ---
    if ($patientType == "OPD") {
        $opdSql = "
            SELECT DISTINCT
                p.Name AS PatientName,
                bp.consultant AS 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
            LEFT JOIN opdpatientregister AS p ON b.PatientId = p.PatientId
            INNER JOIN billparticulars AS bp ON b.BillNo = bp.BillNo AND b.PatientId = bp.PatId -- Use BillNo for consistency
            LEFT JOIN edited_billparticulars AS ebp ON b.BillNo = ebp.BillNo -- Adjust join condition if needed
            LEFT JOIN docotorslist AS d ON bp.consultant = d.doc_name
            WHERE b.BDate >= ? AND b.BDate <= ?
            AND b.PatientType = 'OPD'
            $doctorConditionOPD
            ORDER BY bp.consultant ASC, DAY(b.BDate) ASC;
        ";

        $stmt = $db->prepare($opdSql);
        if ($stmt === false) {
            die('OPD Prepare failed: ' . htmlspecialchars($db->error));
        }

        if (!empty($selectedDoctor)) {
            $stmt->bind_param("sss", $from, $to, $selectedDoctor);
        } else {
            $stmt->bind_param("ss", $from, $to);
        }

        $stmt->execute();
        $query1 = $stmt->get_result();
        if ($query1) {
            while ($row = $query1->fetch_assoc()) {
                $opdReport[] = $row;
                $data_found = true;
            }
        }
        $stmt->close();
    }

    // --- IPD Query ---
    if ($patientType == "IPD" || $patientType == "BOTH") {
        $ipdSql = "
            SELECT
    p.Name AS PatientName,
    bp.consultant AS Consultant,
    b.BDate AS BillDate,
    b.BillNo,
    b.PayableAmount,
    -- Assuming d.charge is the standard charge for the consultant's service for this bill
    -- If a specific 'particulars' indicates the consultant's main charge item,
    -- you might need to adjust this logic based on your data.
    -- For simplicity, let's assume d.charge is the base consultant fee.
    -- If multiple bill particulars can contribute to the consultant's total charge,
    -- and bp.Amount for those particular items represents the consultant's earnings,
    -- then SUM(bp.Amount) for consultant-related particulars would be more accurate.
    -- For now, we'll use d.charge as a direct lookup based on the consultant.
    d.charge AS ConsultantCharge, -- Directly fetch the consultant's charge from the doctor's list
    -- If ConsultantCharge should be based on a sum of specific particulars related to the consultant,
    -- you'll need more refined logic, possibly involving a subquery or a more complex CASE statement.
    -- Example for SUM(bp.Amount) for consultant's own specific service particulars:
    -- SUM(CASE WHEN bp.particulars LIKE '%' || d.doc_name || '%' THEN bp.Amount ELSE 0 END) AS ConsultantCharge_FromParticulars,

    -- Calculate DoctorShare and HospitalShare based on PayableAmount, not on ConsultantCharge unless specified.
    b.PayableAmount * 0.7 AS DoctorShare,
    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.BillNo = bp.BillNo
-- LEFT JOIN edited_billparticulars AS ebp ON b.BillNo = ebp.BillNo -- Only include if actually used
INNER JOIN docotorslist AS d ON bp.consultant = d.doc_name
WHERE b.BDate BETWEEN ? AND ?
AND b.PatientType = 'IPD'
-- Add a NULL check for consultant to ensure records with no consultant aren't excluded by the INNER JOIN
-- OR consider changing the INNER JOIN to LEFT JOIN for docotorslist if some bills might legitimately not have a matched consultant
AND bp.consultant IS NOT NULL
$doctorConditionIPD
GROUP BY p.Name, bp.consultant, b.BDate, b.BillNo, b.PayableAmount, d.charge -- Add d.charge to GROUP BY if used directly
ORDER BY bp.consultant ASC, DAY(b.BDate) ASC";

        $stmt = $db->prepare($ipdSql);
        if ($stmt === false) {
            die('IPD Prepare failed: ' . htmlspecialchars($db->error));
        }

        if (!empty($selectedDoctor)) {
            $stmt->bind_param("sss", $from, $to, $selectedDoctor);
        } else {
            $stmt->bind_param("ss", $from, $to);
        }

        $stmt->execute();
        $query2 = $stmt->get_result();
        if ($query2) {
            while ($row = $query2->fetch_assoc()) {
                $ipdReport[] = $row;
                $data_found = true;
            }
        }
        $stmt->close();
    }

    // --- Combine Reports for 'BOTH' display ---
    // If patientType is 'BOTH', we just combine the previously fetched OPD and IPD reports
    // and add a 'PatientType' column for display differentiation.
    if ($patientType == "BOTH") {
        foreach ($opdReport as $row) {
            $row['PatientType'] = 'OPD';
            $row['ConsultantCharge'] = null; // IPD specific, so null for OPD
            $bothReport[] = $row;
        }
        foreach ($opdproReport as $row) {
            $row['PatientType'] = 'ProcedureCharges';
            $row['DoctorShare'] = $row['DoctorShare'] ?? null; // Null if not set from IPD query
            $row['HospitalShare'] = $row['HospitalShare'] ?? null; // Null if not set from IPD query
            $row['DoctorCharge'] = null; // OPD specific, so null for IPD
            $bothReport[] = $row;
        }
        foreach ($ipdReport as $row) {
            $row['PatientType'] = 'IPD';
            $row['DoctorShare'] = $row['DoctorShare'] ?? null; // Null if not set from IPD query
            $row['HospitalShare'] = $row['HospitalShare'] ?? null; // Null if not set from IPD query
            $row['DoctorCharge'] = null; // OPD specific, so null for IPD
            $bothReport[] = $row;
        }
        // Sort the combined report by Consultant then BillDate
        usort($bothReport, function($a, $b) {
            $cmpConsultant = strcmp($a['Consultant'], $b['Consultant']);
            if ($cmpConsultant !== 0) {
                return $cmpConsultant;
            }
            return strtotime($a['BillDate']) - strtotime($b['BillDate']);
        });
    }


    // --- Examination Data Query ---
    $examinationSql = "
        SELECT
            optionlab,
            SUM(Amount) AS TotalAmount,
            CASE
                WHEN PatId LIKE '%OPD%' THEN 'OPD'
                ELSE 'IPD'
            END AS patient_type_exam
        FROM examination e
        LEFT JOIN docotorslist d ON e.consultant = d.doc_name
        WHERE e.created_at >= ? AND e.created_at <= ?
        $doctorConditionExamination
        GROUP BY optionlab, patient_type_exam;
    ";

    $stmt = $db->prepare($examinationSql);
    if ($stmt === false) {
        die('Examination Prepare failed: ' . htmlspecialchars($db->error));
    }

    if (!empty($selectedDoctor)) {
        $stmt->bind_param("sss", $from, $to, $selectedDoctor);
    } else {
        $stmt->bind_param("ss", $from, $to);
    }

    $stmt->execute();
    $examinationQuery = $stmt->get_result();
    if ($examinationQuery) {
        while ($row = $examinationQuery->fetch_assoc()) {
            $data_found = true; // Data is found if examination data exists
            $patient_type_exam = $row['patient_type_exam'];
            $optionlab = $row['optionlab'];
            $totalAmount = $row['TotalAmount'];
            // Ensure the key exists before assigning
            if (isset($examinationData[$patient_type_exam]) && isset($examinationData[$patient_type_exam][$optionlab])) {
                $examinationData[$patient_type_exam][$optionlab] = $totalAmount;
            }
        }
    }
    $stmt->close();

    $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 lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VH-Admin</title>
    <link rel="icon" href="images/logo.png" type="image/x-icon">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Quicksand:500,700" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../files/bower_components/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../files/assets/pages/waves/css/waves.min.css" type="text/css" media="all">
    <link rel="stylesheet" type="text/css" href="../files/assets/icon/feather/css/feather.css">
    <link rel="stylesheet" type="text/css" href="../files/assets/css/font-awesome-n.min.css">
    <link rel="stylesheet" href="../files/bower_components/chartist/css/chartist.css" type="text/css" media="all">
    <link rel="stylesheet" type="text/css" href="../files/assets/css/style.css">
    <link rel="stylesheet" type="text/css" href="../files/assets/css/widget.css">

    <style>
        .img-fluid {
            max-width: 66%;
            height: auto;
            margin-left: -47px;
        }

        .pcoded li.pcoded-hasmenu[dropdown-icon=style1]>a:after {
            content: none;
        }

        .pcoded[theme-layout=vertical] .pcoded-navbar .pcoded-item[item-border=true][item-border-style=solid] li>a {
            border-bottom-style: solid;
            height: 53px;
        }

        div#c1 {
            background-color: cadetblue;
        }

        div#c2 {
            background-color: slategrey;
        }

        div#c3 {
            background-color: salmon;
        }

        div#c4 {
            background-color: #a549a5;
        }

        /* Table styling for better readability */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table,
        th,
        td {
            border: 1px solid #ddd;
        }

        th,
        td {
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .no-data-message {
            text-align: center;
            color: #888;
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #eee;
            background-color: #f9f9f9;
        }

        /* Adjust button styling to be more visible */
        #viewbtn {
            margin-top: 30px;
        }
    </style>

</head>

<body>

    <div class="loader-bg">
        <div class="loader-bar"></div>
    </div>

    <div id="pcoded" class="pcoded">
        <div class="pcoded-overlay-box"></div>
        <div class="pcoded-container navbar-wrapper">

            <nav class="navbar header-navbar pcoded-header">
                <div class="navbar-wrapper">
                    <div class="navbar-logo">
                        <a href="index.php">
                            <h5>Admin</h5>
                        </a>
                        <a class="mobile-menu" id="mobile-collapse" href="#!">
                            <i class="feather icon-menu icon-toggle-right"></i>
                        </a>
                        <a class="mobile-options waves-effect waves-light">
                            <i class="feather icon-more-horizontal"></i>
                        </a>
                    </div>
                    <div class="navbar-container container-fluid">
                        <ul class="nav-left">
                            <li class="header-search">
                                <div class="main-search morphsearch-search">
                                    <div class="input-group">
                                        <input type="text" class="form-control" placeholder="Enter Keyword">
                                    </div>
                                </div>
                            </li>
                        </ul>
                        <ul class="nav-right">
                            <li class="header-notification">
                                <div class="dropdown-primary dropdown">
                                    <ul class="show-notification notification-view dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
                                    </ul>
                                </div>
                            </li>

                            <li class="user-profile header-notification">
                                <div class="dropdown-primary dropdown">
                                    <div class="dropdown-toggle" data-toggle="dropdown">
                                        <img src="../files/assets/images/avatar-4.jpg" class="img-radius" alt="User-Profile-Image">
                                        <span>Admin</span>
                                        <i class="feather icon-chevron-down"></i>
                                    </div>
                                    <ul class="show-notification profile-notification dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
                                        <li>
                                            <a href="logout.php">
                                                <i class="feather icon-log-out"></i> Logout
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>

            <div class="pcoded-main-container">
                <div class="pcoded-wrapper">

                    <nav class="pcoded-navbar">
                        <div class="nav-list">
                            <div class="pcoded-inner-navbar main-menu">
                                <div class="pcoded-navigation-label">Navigation</div>
                                <ul class="pcoded-item pcoded-left-item">

                                    <li class="pcoded-hasmenu">
                                        <a href="index.php" class="waves-effect waves-dark">
                                            <span class="pcoded-micon"><i class="feather icon-home"></i></span>
                                            <span class="pcoded-mtext">Dashboard</span>
                                        </a>
                                    </li>
                                    <li class="pcoded-hasmenu active pcoded-trigger">
                                        <a href="opddoctor.php" class="waves-effect waves-dark">
                                            <span class="pcoded-micon"><i class="feather icon-home"></i></span>
                                            <span class="pcoded-mtext">Consultant Charges </span>
                                        </a>
                                    </li>
                                    <li class="pcoded-hasmenu">
                                        <a href="PatientDetails.php" class="waves-effect waves-dark">
                                            <span class="pcoded-micon"><i class="fa fa-registered"></i></span>
                                            <span class="pcoded-mtext">Patient Details</span>
                                        </a>
                                    </li>
                                    <li class="pcoded-hasmenu">
                                        <a id="text" href="DailyTrans.php">
                                            <span class="pcoded-micon"><i class="fa fa-registered"></i></span>
                                            <span class="pcoded-mtext">Daily Transactions</span>
                                        </a>
                                    </li>
                                    <li class="pcoded-hasmenu">
                                        <a href="StaffDetails.php" class="waves-effect waves-dark">
                                            <span class="pcoded-micon"><i class="fa fa-registered"></i></span>
                                            <span class="pcoded-mtext">Staff Details</span>
                                        </a>
                                    </li>
                                    <li class="pcoded-hasmenu ">
                                        <a href="javascript:void(0)" class="waves-effect waves-dark">
                                            <span class="pcoded-micon"><i class="fa fa-users"></i></span>
                                            <span class="pcoded-mtext">Users</span>
                                        </a>
                                        <ul class="pcoded-submenu">
                                            <li class="">
                                                <a href="CreateUsers.php" class="waves-effect waves-dark">
                                                    <span class="pcoded-mtext">Create Billing Users</span>
                                                </a>
                                            </li>
                                            <li class="">
                                                <a href="ViewUsers.php" class="waves-effect waves-dark">
                                                    <span class="pcoded-mtext">View Billing Users</span>
                                                </a>
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>

                    <div class="pcoded-content">
                        <div class="page-header card">
                            <div class="row align-items-end">
                                <div class="col-lg-8">
                                    <div class="page-header-title">
                                        <i class="feather icon-inbox bg-c-blue"></i>
                                        <div class="d-inline">
                                            <h5>Consultant Charges</h5>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-4">
                                    <div class="page-header-breadcrumb">
                                        <ul class=" breadcrumb breadcrumb-title">
                                            <li class="breadcrumb-item">
                                                <a href="index.php"><i class="feather icon-home"></i></a>
                                            </li>
                                            <li class="breadcrumb-item"><a href="#!">Home</a>
                                            </li>
                                            <li class="breadcrumb-item"><a href="#!">Consultant Charges</a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="pcoded-inner-content" style="margin:0% ;">
                            <h2 style="text-align: center;font-weight: bold;color:#fff;background-color: #279480;padding:10px;">List of Bills</h2><br>
                            <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 class="form-group col">
                                        <label for="patientType">Patient Type</label>
                                        <select class="form-control" name="patientType" id="patientType" required>
                                            <option value="Procedure Charges" <?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'Procedure Charges') ? 'selected' : ''; ?>>Procedure Charges</option>
                                            <option value="OPD" <?php echo (isset($_POST['patientType']) && $_POST['patientType'] == ' OPD') ? 'selected' : ''; ?>>OPD </option>
        <!--                                    <!?php-->
        <!--if (isset($_POST['patientType']) && $_POST['patientType'] == 'OPD + ProcedureCharges') {-->
        <!--     $proQuery = mysqli_query($db, "SELECT doc_name FROM docotorslist WHERE patient_type = 'OPD + ProcedureCharges' ORDER BY doc_name ASC");-->

        <!--    if ($proQuery) {-->
        <!--        while ($proRow = mysqli_fetch_assoc($proQuery)) {-->
        <!--            $selected = (isset($_POST['doctor']) && $_POST['doctor'] == $doctorRow['doc_name']) ? 'selected' : '';-->
        <!--            echo "<option value='{$doctorRow['doc_name']}' $selected>" . htmlspecialchars($doctorRow['doc_name']) . "</option>";-->
        <!--        }-->
        <!--    } else {-->
                <!--// echo "<option value='OPD + ProcedureCharges'>OPD + Procedure Charges</option>";-->
        <!--    }-->
        <!--}-->
        <!--?>-->
                                            <!--<option value="IPD" <!?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'IPD') ? 'selected' : ''; ?>>IPD</option>-->
                                            <!--<option value="BOTH" <!?php echo (isset($_POST['patientType']) && $_POST['patientType'] == 'BOTH') ? 'selected' : ''; ?>>BOTH</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 ORDER BY doc_name ASC");
                                            if ($doctorQuery) {
                                                while ($doctorRow = mysqli_fetch_assoc($doctorQuery)) {
                                                    $selected = (isset($_POST['doctor']) && $_POST['doctor'] == $doctorRow['doc_name']) ? 'selected' : '';
                                                    echo "<option value='{$doctorRow['doc_name']}' $selected>" . htmlspecialchars($doctorRow['doc_name']) . "</option>";
                                                }
                                            } else {
                                                echo "<option value=''>Error fetching doctors</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <div class="col">
                                        <button type="submit" class="btn btn-primary" id="viewbtn">View</button>
                                        <br><br>
                                          <button type="submit" class="btn btn-success" id="DownloadExcel">Download Excel sheet</button>
                                    </div>
                                </div>
                            </form>
                            
                            <?php if (isset($_POST['datefrom']) && isset($_POST['dateto'])) : ?>
                                <hr>
                                <h3 style="text-align: center; margin-top: 20px;">Report from <?php echo htmlspecialchars($from); ?> to <?php echo htmlspecialchars($to); ?></h3>
                                <?php if (!empty($selectedDoctor)) : ?>
                                    <h4 style="text-align: center;">For Doctor: <?php echo htmlspecialchars($selectedDoctor); ?></h4>
                                <?php endif; ?>

                                <?php
                                $displayOPDTable = ($patientType == "OPD" && !empty($opdReport)) || ($patientType == "BOTH" && !empty(array_filter($bothReport, function($item) { return $item['PatientType'] == 'OPD'; })));
                                $displayIPDTable = ($patientType == "IPD" && !empty($ipdReport)) || ($patientType == "BOTH" && !empty(array_filter($bothReport, function($item) { return $item['PatientType'] == 'IPD'; })));
                                // $displayProcedureCharges = ($patientType == "OPD + ProcedureCharges" && !empty($opdproReport)) || ($patientType == "BOTH" && !empty(array_filter($bothReport, function($item) { return $item['PatientType'] == 'IPD' && !empty($item['ProcedureCharges']); })));
                                // $displayProcedureCharges = ($patientType == "OPD + ProcedureCharges" && !empty($opdproReport));
    
    
                                ?>



<!--// <!?php-->
<!--// // Initialize totals-->
<!--// $totalProcedureCharges = 0;-->
<!--// $totalDoctorShare = 0;-->
<!--// $totalHospitalShare = 0;-->

<!--// // Sample data (as seen in the image provided)-->
<!--// $patients = [-->
<!--//     ['ConsultantCharges' => 300.00],-->
<!--//     ['ConsultantCharges' => 1050.00],-->
<!--//     ['ConsultantCharges' => 800.00],-->
<!--//     ['ConsultantCharges' => 1050.00]-->
<!--// ];-->

<!--// // Loop through the patients' data to calculate and accumulate totals-->
<!--// foreach ($patients as $row) {-->
<!--//     // Calculate Procedure Charges (10%)-->
<!--//     $procedureCharge = $row['ConsultantCharges'] * 0.10;-->

<!--//     // Calculate Doctor Share (50% of Procedure Charges)-->
<!--//     $doctorShare = $procedureCharge * 0.50;-->

<!--//     // Calculate Hospital Share (50% of Procedure Charges)-->
<!--//     $hospitalShare = $procedureCharge * 0.50;-->

<!--//     // Update the totals-->
<!--//     $totalProcedureCharges += $procedureCharge;-->
<!--//     $totalDoctorShare += $doctorShare;-->
<!--//     $totalHospitalShare += $hospitalShare;-->
<!--// }-->

<!--// Display the results-->
<!--// echo "<h4>Procedure Charges Report</h4>";-->
<!--// echo "<table border='1' cellpadding='8' cellspacing='0' width='100%'>";-->
<!--// echo "<thead><tr><th>Procedure Charges</th><th>Doctor Share (50%)</th><th>Hospital Share (50%)</th></tr></thead>";-->
<!--// echo "<tbody>";-->

<!--// // Loop to display the individual rows-->
<!--// $srNo = 1;-->
<!--// foreach ($patients as $row) {-->
<!--//     $procedureCharge = $row['ConsultantCharges'] * 0.10;-->
<!--//     $doctorShare = $procedureCharge * 0.50;-->
<!--//     $hospitalShare = $procedureCharge * 0.50;-->

<!--//     echo "<tr>";-->
<!--//     echo "<td>" . number_format($procedureCharge, 2) . "</td>";-->
<!--//     echo "<td>" . number_format($doctorShare, 2) . "</td>";-->
<!--//     echo "<td>" . number_format($hospitalShare, 2) . "</td>";-->
<!--//     echo "</tr>";-->
<!--//     $srNo++;-->
<!--// }-->

<!--// echo "</tbody>";-->

<!--// // Display totals in footer-->
<!--// echo "<tfoot>";-->
<!--// echo "<tr><th>" . number_format($totalProcedureCharges, 2) . "</th><th>" . number_format($totalDoctorShare, 2) . "</th><th>" . number_format($totalHospitalShare, 2) . "</th></tr>";-->
<!--// echo "</tfoot>";-->
<!--// echo "</table>";-->

<!--?>-->
<?php
$doctors = [
    ['DoctorName' => 'DR ANIL SANGLI', 'Specialization' => 'NEURO SURGEON', 'Amount' => 500],
    ['DoctorName' => 'Dr Sachin Dharwadkar', 'Specialization' => 'Urology', 'Amount' => 450],
    ['DoctorName' => 'DR. KIRAN KUMAR SHETTY', 'Specialization' => 'UROLOGY', 'Amount' => 450],
    ['DoctorName' => 'DR.KISHORE', 'Specialization' => 'PSYCHIATRIST', 'Amount' => 500],
    ['DoctorName' => 'DR.LEELAVATHI', 'Specialization' => 'OBG', 'Amount' => 350],
    ['DoctorName' => 'DR.VIJAY KUMAR', 'Specialization' => 'UROLOGY', 'Amount' => 450],
    ['DoctorName' => 'DR.DILIP', 'Specialization' => 'ANESTHETIST', 'Amount' => 4000],
    ['DoctorName' => 'DR.SARVESH', 'Specialization' => 'ANESTHETIST', 'Amount' => 3000],
    ['DoctorName' => 'Dr Varadaraju', 'Specialization' => 'GENERAL SURGERY', 'Amount' => 0],
    ['DoctorName' => 'Dr Ankitha', 'Specialization' => 'Paediatrician', 'Amount' => 0],
    ['DoctorName' => 'DR.VINAY', 'Specialization' => 'PHYSICIAN', 'Amount' => 350],
    ['DoctorName' => 'Dr Shastara', 'Specialization' => 'Neurologist', 'Amount' => 0],
    ['DoctorName' => 'Dr Girish M S', 'Specialization' => 'Surgical Oncologist', 'Amount' => 0],
    ['DoctorName' => 'Dr Sheela Rao', 'Specialization' => 'Gynaecologist', 'Amount' => 0],
    ['DoctorName' => 'DR PRATHAP', 'Specialization' => 'OBG', 'Amount' => 0],
    ['DoctorName' => 'DR CHETHAN', 'Specialization' => 'Plastic Surgeon', 'Amount' => 0],
    // Add more here...
];

// Show charges only if form is submitted with Procedure Charges selected
$showProcedureCharges = isset($_POST['patientType']) && $_POST['patientType'] === 'Procedure Charges';

if ($showProcedureCharges) {
    $procedureStats = [];

    foreach ($doctors as $doc) {
        $charge = floatval($doc['Amount']);
        if ($charge <= 0) continue;

        $procedureCharge = $charge * 0.50;
        $doctorShare = $procedureCharge * 0.50;
        $hospitalShare = $procedureCharge * 0.50;

        $procedureStats[] = [
            'DoctorName' => $doc['DoctorName'],
            'Specialization' => $doc['Specialization'],
            'OriginalCharge' => $charge,
            'ProcedureCharge' => $procedureCharge,
            'DoctorShare' => $doctorShare,
            'HospitalShare' => $hospitalShare
        ];
    }
}
?>


<!--<!?php if ($showProcedureCharges): ?>-->
<!--    <h2 style="text-align:center;">Procedure Charges by Doctor</h2>-->
<!--    <table border="1" cellpadding="8" cellspacing="0" style="width:100%; border-collapse:collapse;">-->
<!--        <thead style="background-color:#f0f0f0;">-->
<!--            <tr>-->
<!--                <th>Doctor</th>-->
<!--                <th>Specialization</th>-->
<!--                <th>Original Amount</th>-->
<!--                <th>Procedure Charges (50%)</th>-->
<!--                <th>Doctor Share (50%)</th>-->
<!--                <th>Hospital Share (50%)</th>-->
<!--            </tr>-->
<!--        </thead>-->
<!--        <tbody>-->
<!--            <!?php-->
<!--            $grand = ['Original' => 0, 'Procedure' => 0, 'Doctor' => 0, 'Hospital' => 0];-->
<!--            foreach ($procedureStats as $row):-->
<!--                $grand['Original'] += $row['OriginalCharge'];-->
<!--                $grand['Procedure'] += $row['ProcedureCharge'];-->
<!--                $grand['Doctor'] += $row['DoctorShare'];-->
<!--                $grand['Hospital'] += $row['HospitalShare'];-->
<!--            ?>-->
<!--                <tr>-->
<!--                    <td><1?= htmlspecialchars($row['DoctorName']) ?></td>-->
<!--                    <td><1?= htmlspecialchars($row['Specialization']) ?></td>-->
<!--                    <td><1?= number_format($row['OriginalCharge'], 2) ?></td>-->
<!--                    <td><1?= number_format($row['ProcedureCharge'], 2) ?></td>-->
<!--                    <td><1?= number_format($row['DoctorShare'], 2) ?></td>-->
<!--                    <td><1?= number_format($row['HospitalShare'], 2) ?></td>-->
<!--                </tr>-->
<!--            <1?php endforeach; ?>-->
<!--        </tbody>-->
<!--        <tfoot style="font-weight:bold; background-color:#e0e0ff;">-->
<!--            <tr>-->
<!--                <td colspan="2">Grand Total</td>-->
<!--                <td><!?= number_format($grand['Original'], 2) ?></td>-->
<!--                <td><1?= number_format($grand['Procedure'], 2) ?></td>-->
<!--                <td><1?= number_format($grand['Doctor'], 2) ?></td>-->
<!--                <td><1?= number_format($grand['Hospital'], 2) ?></td>-->
<!--            </tr>-->
<!--        </tfoot>-->
<!--    </table>-->
<!--<1?php endif; ?>-->





                                <?php if ($displayOPDTable) : ?>
    <h4 style="margin-top: 30px;">OPD Patient Bills</h4>
   <div class="table-responsive">
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>Bill Date</th>
                <th>Bill No</th>
                <th>Patient Name</th>
                <th>Consultant</th>
                <th>Consultant Charges</th>
                <th>Doctor Share (70%)</th>
                <th>Hospital Share (30%)</th>
                <!--<th>Procedure Charges</th>-->
            </tr>
        </thead>
        <tbody
            <?php
            $total_opd_payable_amount = 0;
            $total_opd_doctor_share = 0;
            $total_opd_hospital_share = 0;
            $total_procedure_charges = 0;

            $reportToDisplayOPD = ($patientType == "OPD") ? $opdReport : array_filter($bothReport, function($item) {
                return $item['PatientType'] == 'OPD';
            });

            foreach ($reportToDisplayOPD as $row) :
                $procedureCharge = $row['PayableAmount'] * 0.10; // Calculated as 10% of PayableAmount

                $total_opd_payable_amount += $row['PayableAmount'];
                $total_opd_doctor_share += $row['DoctorShare'];
                $total_opd_hospital_share += $row['HospitalShare'];
                $total_procedure_charges += $procedureCharge;
            ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['BillDate']); ?></td>
                    <td><?php echo htmlspecialchars($row['BillNo']); ?></td>
                    <td><?php echo htmlspecialchars($row['PatientName']); ?></td>
                    <td><?php echo htmlspecialchars($row['Consultant']); ?></td>
                    <td><?php echo number_format($row['PayableAmount'], 2); ?></td>
                    <td><?php echo number_format($row['DoctorShare'], 2); ?></td>
                    <td><?php echo number_format($row['HospitalShare'], 2); ?></td>
                    <!--<td><!?php echo number_format($procedureCharge, 2); ?></td>-->
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="4" style="text-align:right;">Total OPD:</th>
                <th><?php echo number_format($total_opd_payable_amount, 2); ?></th>
                <th><?php echo number_format($total_opd_doctor_share, 2); ?></th>
                <th><?php echo number_format($total_opd_hospital_share, 2); ?></th>
                <!--<th style="font-weight:bold;background-color:#F2F2F2"><!?php echo number_format($total_procedure_charges, 2); ?></th>-->
            </tr>
        </tfoot>
    </table>
</div>

<?php endif; ?>
<?php if ($showProcedureCharges): ?>
    <!-- Your existing table code here -->
 <h2 style="text-align:center;">Procedure Charges by Doctor</h2>
    <table border="1" cellpadding="8" cellspacing="0" style="width:100%; border-collapse:collapse;">
        <thead style="background-color:#f0f0f0;">
            <tr>
                <th>Doctor</th>
                <th>Specialization</th>
                <th>Original Amount</th>
                <th>Procedure Charges (50%)</th>
                <th>Doctor Share (50%)</th>
                <th>Hospital Share (50%)</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $grand = ['Original' => 0, 'Procedure' => 0, 'Doctor' => 0, 'Hospital' => 0];
            foreach ($procedureStats as $row):
                $grand['Original'] += $row['OriginalCharge'];
                $grand['Procedure'] += $row['ProcedureCharge'];
                $grand['Doctor'] += $row['DoctorShare'];
                $grand['Hospital'] += $row['HospitalShare'];
            ?>
                <tr>
                    <td><?= htmlspecialchars($row['DoctorName']) ?></td>
                    <td><?= htmlspecialchars($row['Specialization']) ?></td>
                    <td><?= number_format($row['OriginalCharge'], 2) ?></td>
                    <td><?= number_format($row['ProcedureCharge'], 2) ?></td>
                    <td><?= number_format($row['DoctorShare'], 2) ?></td>
                    <td><?= number_format($row['HospitalShare'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot style="font-weight:bold; background-color:#e0e0ff;">
            <tr>
                <td colspan="2">Grand Total</td>
                <td><?= number_format($grand['Original'], 2) ?></td>
                <td><?= number_format($grand['Procedure'], 2) ?></td>
                <td><?= number_format($grand['Doctor'], 2) ?></td>
                <td><?= number_format($grand['Hospital'], 2) ?></td>
            </tr>
        </tfoot>
    </table>
<?php endif; ?>



                                <?php if ($displayIPDTable) : ?>
                                    <h4 style="margin-top: 30px;">IPD Patient Bills</h4>
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Bill Date</th>
                                                    <th>Bill No</th>
                                                    <th>Patient Name</th>
                                                    <th>Consultant</th>
                                                    <th>Payable Amount</th>
                                                    <th>Consultant Charge</th>
                                                    <th>Doctor Share</th>
                                                    <th>Hospital Share</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <!--<!?php-->
                                                <!--$total_ipd_payable_amount = 0;-->
                                                <!--$total_ipd_consultant_charge = 0;-->
                                                <!--$total_ipd_doctor_share = 0;-->
                                                <!--$total_ipd_hospital_share = 0;-->

                                                <!--$reportToDisplayIPD = ($patientType == "IPD") ? $ipdReport : array_filter($bothReport, function($item) { return $item['PatientType'] == 'IPD'; });-->

                                                <!--foreach ($reportToDisplayIPD as $row) :-->
                                                <!--    $total_ipd_payable_amount += $row['PayableAmount'];-->
                                                <!--    $total_ipd_consultant_charge += $row['ConsultantCharge'];-->
                                                    <!--// Use null coalescing operator ?? to handle potential nulls from the query when combining 'BOTH'-->
                                                <!--    $total_ipd_doctor_share += $row['DoctorShare'] ?? 0;-->
                                                <!--    $total_ipd_hospital_share += $row['HospitalShare'] ?? 0;-->
                                                <!--?>-->
                                                
                                                <?php
                            $total_ipd_payable_amount = 0.0; // Initialize as float
                            $total_ipd_consultant_charge = 0.0; // Initialize as float
                            $total_ipd_doctor_share = 0.0; // Initialize as float
                            $total_ipd_hospital_share = 0.0; // Initialize as float
                            
                            $reportToDisplayIPD = ($patientType == "IPD") ? $ipdReport : array_filter($bothReport, function($item) { return $item['PatientType'] == 'IPD'; });
                            
                            foreach ($reportToDisplayIPD as $row) :
                                // Explicitly cast to float for robust summation,
                                // and use null coalescing for safety if keys might be missing or null.
                                $total_ipd_payable_amount += (float) ($row['PayableAmount'] ?? 0);
                                $total_ipd_consultant_charge += (float) ($row['ConsultantCharge'] ?? 0);
                                $total_ipd_doctor_share += (float) ($row['DoctorShare'] ?? 0);
                                $total_ipd_hospital_share += (float) ($row['HospitalShare'] ?? 0);
                            endforeach; // End of foreach loop, assuming it was meant to be closed here
                            ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($row['BillDate']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['BillNo']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['PatientName']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['Consultant']); ?></td>
                                                        <td><?php echo number_format($row['PayableAmount'], 2); ?></td>
                                                       <td>
    <?php
    $consultantCharge = isset($row['ConsultantCharge']) ? (float) $row['ConsultantCharge'] : null;

    if ($consultantCharge !== null && is_numeric($consultantCharge)) {
        echo number_format($consultantCharge, 2);
    } else {
        echo 'N/A'; // Or 0.00, or leave blank, depending on your preference
    }
    ?>


</td>
                                                        <td><?php echo number_format($row['DoctorShare'], 2); ?></td>
                                                        <td><?php echo number_format($row['HospitalShare'], 2); ?></td>
                                                    </tr>
                                                <!--<!?php endforeach; ?>-->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <th colspan="4" style="text-align:right;">Total IPD:</th>
                                                    <th><?php echo number_format($total_ipd_payable_amount, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_consultant_charge, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_doctor_share, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_hospital_share, 2); ?></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                    <?php
                            $total_ipd_payable_amount = 0.0; // Initialize as float
                            $total_ipd_consultant_charge = 0.0; // Initialize as float
                            $total_ipd_doctor_share = 0.0; // Initialize as float
                            $total_ipd_hospital_share = 0.0; // Initialize as float
                            
                            // $reportToDisplayOPDPro = ($patientType == "Procedure Charges") ? $opdproReport : array_filter($bothReport, function($item) { return $item['PatientType'] == 'OPD'; });
                            $reportToDisplayOPDPro = ($patientType == "Procedure Charges") ? $opdproReport : [];

                            foreach ($reportToDisplayOPDPro as $row) :
                                // Explicitly cast to float for robust summation,
                                // and use null coalescing for safety if keys might be missing or null.
                                $total_ipd_payable_amount += (float) ($row['PayableAmount'] ?? 0);
                                $total_ipd_consultant_charge += (float) ($row['ConsultantCharge'] ?? 0);
                                $total_ipd_doctor_share += (float) ($row['DoctorShare'] ?? 0);
                                $total_ipd_hospital_share += (float) ($row['HospitalShare'] ?? 0);
                            endforeach; // End of foreach loop, assuming it was meant to be closed here
                            ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($row['BillDate']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['BillNo']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['PatientName']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['Consultant']); ?></td>
                                                        <td><?php echo number_format($row['PayableAmount'], 2); ?></td>
                                                       <td>
    <?php
    $consultantCharge = isset($row['ConsultantCharge']) ? (float) $row['ConsultantCharge'] : null;

    if ($consultantCharge !== null && is_numeric($consultantCharge)) {
        echo number_format($consultantCharge, 2);
    } else {
        echo 'N/A'; // Or 0.00, or leave blank, depending on your preference
    }
    
    $reportToDisplayIPD = ($patientType == "IPD") ? $ipdReport : array_filter($bothReport, function($item) { return $item['PatientType'] == 'IPD'; });
                            
                            foreach ($reportToDisplayIPD as $row) :
                                // Explicitly cast to float for robust summation,
                                // and use null coalescing for safety if keys might be missing or null.
                                $total_ipd_payable_amount += (float) ($row['PayableAmount'] ?? 0);
                                $total_ipd_consultant_charge += (float) ($row['ConsultantCharge'] ?? 0);
                                $total_ipd_doctor_share += (float) ($row['DoctorShare'] ?? 0);
                                $total_ipd_hospital_share += (float) ($row['HospitalShare'] ?? 0);
                            endforeach; // End of foreach loop, assuming it was meant to be closed here
                            ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($row['BillDate']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['BillNo']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['PatientName']); ?></td>
                                                        <td><?php echo htmlspecialchars($row['Consultant']); ?></td>
                                                        <td><?php echo number_format($row['PayableAmount'], 2); ?></td>
                                                       <td>
    <?php
    $consultantCharge = isset($row['ConsultantCharge']) ? (float) $row['ConsultantCharge'] : null;

    if ($consultantCharge !== null && is_numeric($consultantCharge)) {
        echo number_format($consultantCharge, 2);
    } else {
        echo 'N/A'; // Or 0.00, or leave blank, depending on your preference
    }
    ?>


</td>
                                                        <td><?php echo number_format($row['DoctorShare'], 2); ?></td>
                                                        <td><?php echo number_format($row['HospitalShare'], 2); ?></td>
                                                    </tr>
                                                <!--<!?php endforeach; ?>-->
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <th colspan="4" style="text-align:right;">Total IPD:</th>
                                                    <th><?php echo number_format($total_ipd_payable_amount, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_consultant_charge, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_doctor_share, 2); ?></th>
                                                    <th><?php echo number_format($total_ipd_hospital_share, 2); ?></th>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                <!--<!?php elseif ($patientType == "OPD + ProcedureCharges") : ?>-->
                                <?php elseif ($patientType == "ProcedureCharges") : ?>
                                <p class="no-data-message">No Procedure Charges Data Found</p>
                                
                                <?php elseif ($patientType == "IPD") : ?>
                                    <p class="no-data-message">No IPD data found for the selected criteria.</p>
                                <?php endif; ?>

                                <?php if ($patientType == "BOTH" && empty($opdReport) && empty($ipdReport)) : ?>
                                    <p class="no-data-message">No OPD or IPD data found for the selected criteria.</p>
                                <?php endif; ?>

                                <?php if ($data_found && ($opd_cardiology_total > 0 || $opd_radiology_total > 0 || $opd_laboratory_total > 0 || $ipd_cardiology_total > 0 || $ipd_radiology_total > 0 || $ipd_laboratory_total > 0)) : ?>
                                    <!--<h4 style="margin-top: 30px;">Examination Data Totals</h4>-->
                                    <!--<div class="table-responsive">-->
                                    <!--    <table class="table table-bordered table-hover">-->
                                    <!--        <thead>-->
                                    <!--            <tr>-->
                                    <!--                <th>Patient Type</th>-->
                                    <!--                <th>Cardiology Total</th>-->
                                    <!--                <th>Radiology Total</th>-->
                                    <!--                <th>Lab Test Total</th>-->
                                    <!--            </tr>-->
                                    <!--        </thead>-->
                                    <!--        <tbody>-->
                                    <!--            <tr>-->
                                    <!--                <td>OPD Examinations</td>-->
                                    <!--                <td><!?php echo number_format($opd_cardiology_total, 2); ?></td>-->
                                    <!--                <td><1?php echo number_format($opd_radiology_total, 2); ?></td>-->
                                    <!--                <td><1?php echo number_format($opd_laboratory_total, 2); ?></td>-->
                                    <!--            </tr>-->
                                    <!--            <tr>-->
                                    <!--                <td>IPD Examinations</td>-->
                                    <!--                <td><1?php echo number_format($ipd_cardiology_total, 2); ?></td>-->
                                    <!--                <td><1?php echo number_format($ipd_radiology_total, 2); ?></td>-->
                                    <!--                <td><1?php echo number_format($ipd_laboratory_total, 2); ?></td>-->
                                    <!--            </tr>-->
                                    <!--        </tbody>-->
                                    <!--        <tfoot>-->
                                    <!--            <tr>-->
                                    <!--                <th>Grand Total Examinations</th>-->
                                    <!--                <th><1?php echo number_format($opd_cardiology_total + $ipd_cardiology_total, 2); ?></th>-->
                                    <!--                <th><1?php echo number_format($opd_radiology_total + $ipd_radiology_total, 2); ?></th>-->
                                    <!--                <th><1?php echo number_format($opd_laboratory_total + $ipd_laboratory_total, 2); ?></th>-->
                                    <!--            </tr>-->
                                    <!--        </tfoot>-->
                                    <!--    </table>-->
                                    <!--</div>-->
                                <?php elseif (isset($_POST['datefrom']) && isset($_POST['dateto'])) : ?>
                                    <p class="no-data-message">No examination data found for the selected criteria.</p>
                                <?php endif; ?>

                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
document.getElementById('DownloadExcel').addEventListener('click', function () {
    // Select all tables to export
    const tables = document.querySelectorAll('.table-responsive table');

    if (tables.length === 0) {
        alert("No tables found to export.");
        return;
    }

    // Create a new workbook
    const wb = XLSX.utils.book_new();

    // Loop through all tables
    tables.forEach((table, index) => {
        const ws = XLSX.utils.table_to_sheet(table);
        const sheetName = `Sheet${index + 1}`;
        XLSX.utils.book_append_sheet(wb, ws, sheetName);
    });

    // Save the workbook as Excel file
    XLSX.writeFile(wb, 'Report_Data.xlsx');
});
</script>

    <!--<script>-->
    <!--    document.getElementById("DownloadExcel").addEventListener("click", function () {-->
    <!--        let table = document.getElementById("myTable");-->
    <!--        let tableHTML = table.outerHTML.replace(/ /g, '%20');-->

    <!--        let filename = 'table_data.xls';-->

    <!--        let downloadLink = document.createElement("a");-->
    <!--        document.body.appendChild(downloadLink);-->

    <!--        downloadLink.href = 'data:application/vnd.ms-excel,' + tableHTML;-->
    <!--        downloadLink.download = filename;-->
    <!--        downloadLink.click();-->

    <!--        document.body.removeChild(downloadLink);-->
    <!--    });-->
    <!--</script>-->
    <script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>
    <script type="text/javascript" src="../files/bower_components/jquery/js/jquery.min.js"></script>
    <script type="text/javascript" src="../files/bower_components/jquery-ui/js/jquery-ui.min.js"></script>
    <script type="text/javascript" src="../files/bower_components/popper.js/js/popper.min.js"></script>
    <script type="text/javascript" src="../files/bower_components/bootstrap/js/bootstrap.min.js"></script>
    <script src="../files/assets/pages/waves/js/waves.min.js"></script>
    <script type="text/javascript" src="../files/bower_components/jquery-slimscroll/js/jquery.slimscroll.js"></script>
    <script type="text/javascript" src="../files/bower_components/modernizr/js/modernizr.js"></script>
    <script type="text/javascript" src="../files/bower_components/chartist/js/chartist.js"></script>
    <script src="../files/assets/pages/widget/amchart/amcharts.js"></script>
    <script src="../files/assets/pages/widget/amchart/serial.js"></script>
    <script src="../files/assets/pages/widget/amchart/light.js"></script>
    <script src="../files/assets/js/pcoded.min.js"></script>
    <script src="../files/assets/js/vertical/vertical-layout.min.js"></script>
    <script type="text/javascript" src="../files/assets/pages/dashboard/custom-dashboard.min.js"></script>
    <script type="text/javascript" src="../files/assets/js/script.js"></script>
</body>

</html>