<?php
ini_set('display_errors', 1);
ini_set('display_errors', E_ALL);
ini_set('display_startup_errors', E_ALL);
error_reporting(E_ALL);

session_start();
include("dbconfig.php");
$data_found = false;

// Check if the user is logged in
if (isset($_SESSION['username']) && isset($_SESSION['password'])) {
    $username = $_SESSION['username'];
    $pass = $_SESSION['password'];
} else {
    echo '<META http-equiv="refresh" content="0;logout.php">';
    exit();
}

// Check if the form has been submitted
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'";
    // }
    if (isset($_POST['doctor']) && $_POST['doctor'] !== 'All') {
        $selectedDoctor = mysqli_real_escape_string($db, $_POST['doctor']);
        $doctorConditionOPD = "AND bp.consultant = '$selectedDoctor'";
        $doctorConditionIPD = "AND bp.consultant = '$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
        //                          ");
        $query1 = mysqli_query($db, "
                    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
                    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 bp.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
        //                         ");
        $query1 = mysqli_query($db, "
                    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
                    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 bp.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 lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<head>
    <title>VH-Admin</title>
    <link rel="icon" href="images/logo.png" type="image/x-icon" class="abc">
    <link rel="icon" type="image/icon" href="images/logo.png" />
    <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;
        }
    </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>

                            </a>
                            </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">Consaltant 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="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>Patient Name</th>
                                            <th>Bill Date</th>
                                            <th>Discount</th>
                                            <th>Consultant </th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $currentConsultant = null;
                                        $doctorTotalOPD = 0;
                                        $doctorTotalIPD = 0;

                                        // 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 there's a ConsultantShare value, use it; otherwise, set to 200.00 for OPD
                                            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 += floatval($consultantShare);
                                            } elseif (in_array($row, $ipdReport)) {
                                                $doctorTotalIPD += floatval($consultantShare);
                                            }

                                            // Display bill details
                                            echo "<tr>
                                                    <td>" . htmlspecialchars($row['PatientName'] ?? '') . "</td>
                                                    <td>" . htmlspecialchars(date("d/m/Y", strtotime($row['BillDate']))) . "</td>
                                                    <td>" . htmlspecialchars($row['Discount'] ?? '0.00') . "</td>
                                                    <td>" . htmlspecialchars(number_format((float)$consultantShare, 2)) . "</td>
                                                </tr>";
                                        endforeach;


                                        // Final totals for the last consultant
                                        if ($currentConsultant !== null) {
                                            if ($doctorTotalOPD > 0) {
                                                echo "<tr>
                                                        <td colspan='3'><strong>Total for OPD:</strong></td>
                                                        <td><strong>" . number_format($doctorTotalOPD, 2) . "</strong></td>
                                                    </tr>";
                                            }
                                            if ($doctorTotalIPD > 0) {
                                                echo "<tr>
                                                        <td colspan='3'><strong>Total for IPD:</strong></td>
                                                        <td><strong>" . number_format($doctorTotalIPD, 2) . "</strong></td>
                                                    </tr>";
                                            }
                                        }
                                        ?>
                                    </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>




                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/jquery/js/jquery.min.js"></script>
                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/jquery-ui/js/jquery-ui.min.js"></script>
                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/popper.js/js/popper.min.js"></script>
                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/bootstrap/js/bootstrap.min.js"></script>

                <script src="../files/assets/pages/waves/js/waves.min.js" type="a0935012553127c718007911-text/javascript"></script>

                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/jquery-slimscroll/js/jquery.slimscroll.js"></script>

                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/modernizr/js/modernizr.js"></script>
                <script type="a0935012553127c718007911-text/javascript" src="../files/bower_components/modernizr/js/css-scrollbars.js"></script>

                <script src="../files/assets/pages/waves/js/waves.min.js" type="a0935012553127c718007911-text/javascript"></script>

                <script src="../files/bower_components/datatables.net/js/jquery.dataTables.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-buttons/js/dataTables.buttons.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/pages/data-table/js/jszip.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/pages/data-table/js/pdfmake.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/pages/data-table/js/vfs_fonts.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-buttons/js/buttons.print.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-buttons/js/buttons.html5.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-bs4/js/dataTables.bootstrap4.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-responsive/js/dataTables.responsive.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/bower_components/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js" type="a0935012553127c718007911-text/javascript"></script>

                <script src="../files/assets/pages/data-table/js/data-table-custom.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/js/pcoded.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/js/vertical/vertical-layout.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script src="../files/assets/js/jquery.mCustomScrollbar.concat.min.js" type="a0935012553127c718007911-text/javascript"></script>
                <script type="a0935012553127c718007911-text/javascript" src="../files/assets/js/script.js"></script>

                <script async src="https://www.googletagmanager.com/gtag/js?id=UA-23581568-13" type="a0935012553127c718007911-text/javascript"></script>
                <script type="a0935012553127c718007911-text/javascript">
                    window.dataLayer = window.dataLayer || [];

                    function gtag() {
                        dataLayer.push(arguments);
                    }
                    gtag('js', new Date());

                    gtag('config', 'UA-23581568-13');
                </script>
                <script src="rocket-loader.min.js" data-cf-settings="a0935012553127c718007911-|49" defer=""></script>
</body>

</html>