<?php
session_start();
include("dbConfig.php");

// Check if session variables are set
if (!isset($_SESSION['username']) || !isset($_SESSION['name'])) {
    echo '<META http-equiv="refresh" content="0;logout.php">';
    exit();
}

$username = $_SESSION['username'];
$name = $_SESSION['name'];

// Initialize query variable and totals
$query = null;
$total_cash = $total_card = $total_upi = $total_other = 0;
$total_ipd = $total_opd = 0; // Initialize IPD and OPD totals
$cardiology_total = $radiology_total = $laboratory_total = 0; // Initialize totals for categories

if (isset($_POST['datefrom']) && isset($_POST['dateto'])) {
    $from = $_POST['datefrom'];
    $to = $_POST['dateto'];

    if ($from > $to) {
        echo "<h3>Invalid date range. 'From' date cannot be greater than 'To' date.</h3>";
    } else {
        $db->query("SET SESSION sql_mode = (SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''))");

        $query = mysqli_query($db, "
                                    SELECT 
                                        PatientId,
                                        PatientName,
                                        BillType,
                                        PaymentMode,
                                        BillNo,
                                        BillDate,
                                        PayableAmount
                                    FROM (
                                    SELECT DISTINCT
                                        a.PatId AS PatientId,
                                        p.Name AS PatientName,
                                        'Advance' AS BillType,
                                        a.PaymentMode,
                                        a.BillNo,
                                        a.AdvanceDate AS BillDate,
                                        a.Amount AS PayableAmount
                                    FROM advance a 
                                    INNER JOIN patientdetails p ON a.PatId = p.PatId
                                    WHERE a.AdvanceDate BETWEEN '$from' AND '$to'
                                    AND a.Amount > 0

                                    UNION ALL

                                    SELECT DISTINCT
                                        f.PatientId,
                                        p.Name AS PatientName,
                                        'Discharge' AS BillType,
                                        f.PaymentMode,
                                        f.FinalBillNo AS BillNo,
                                        f.DischargeDate AS BillDate,
                                        CASE WHEN f.PaymentMode = 'Insurance' THEN f.TotalAmount ELSE f.PayableAmount END AS PayableAmount
                                    FROM finalbill f
                                    INNER JOIN patientdetails p ON f.PatientId = p.PatId
                                    WHERE f.DischargeDate BETWEEN '$from' AND '$to'

                                    UNION ALL

                                    SELECT DISTINCT
                                        i.PatientId,
                                        o.Name AS PatientName,
                                        'Investigation' AS BillType,
                                        i.PaymentMode,
                                        i.BillNo,
                                        i.BDate AS BillDate,
                                        i.PayableAmount
                                    FROM inbill i
                                    INNER JOIN opdpatientregister o ON i.PatientId = o.PatientId
                                    WHERE i.BDate BETWEEN '$from' AND '$to'
                                    AND i.PayableAmount > 0

                                    UNION ALL

                                    SELECT DISTINCT
                                        b.PatientId,
                                        o.Name AS PatientName,
                                        b.PatientType AS BillType,
                                        b.PaymentMode,
                                        b.BillNo,
                                        b.BDate AS BillDate,
                                        b.PayableAmount
                                    FROM bill b
                                    INNER JOIN opdpatientregister o ON b.PatientId = o.PatientId
                                    WHERE b.BDate BETWEEN '$from' AND '$to' 
                                    AND b.PatientType = 'OPD'
                                    AND b.PayableAmount > 0

                                    UNION ALL

                                    SELECT
                                        b.PatientId,
                                        p.Name AS PatientName,
                                        'IPD Consolidate' AS BillType,
                                        b.PaymentMode AS PaymentMode, -- Combine all payment modes
                                        b.BillNo AS BillNo,          -- Combine all bill numbers
                                        b.BDate AS BillDate,                  -- Use the latest bill date
                                        b.PayableAmount AS PayableAmount      -- Sum up all payable amounts
                                    FROM bill b
                                    LEFT JOIN patientdetails p ON b.PatientId = p.PatId
                                    WHERE b.BDate BETWEEN '$from' AND '$to'
                                    AND b.PatientType IN ('IPD')         -- Consider both IPD and OPD types
                                    AND b.PayableAmount > 0
                                    AND b.PatientId NOT IN (SELECT PatientId FROM finalbill WHERE DischargeDate BETWEEN '$from' AND '$to')
                                ) AS combined_data
                                ORDER BY BillNo, BillDate, BillType;
                                ");
                                
                                // 

        $examinationQuery = mysqli_query($db, "
            SELECT optionlab, SUM(Amount) AS TotalAmount 
            FROM examination 
            WHERE DATE(created_at) BETWEEN '$from' AND '$to' 
            GROUP BY optionlab
            ");

        // Billparticulars totals query
        $billparticularsQuery = mysqli_query($db, "
            SELECT optionlab, SUM(Amount) AS TotalAmount 
            FROM billparticulars
            INNER JOIN bill b ON billparticulars.BillNo = b.BillNo
            WHERE DATE(b.BDate) BETWEEN '$from' AND '$to'
            GROUP BY optionlab
            ");

        if (!$examinationQuery || !$billparticularsQuery) {
            echo "Error executing query: " . mysqli_error($db);
            exit();
        }

        // Initialize totals
        $cardiology_total = 0;
        $radiology_total = 0;
        $laboratory_total = 0;
// 

        // Process examination totals
        while ($row = $examinationQuery->fetch_assoc()) {
            switch ($row['optionlab']) {
                case 'Cardiology':
                    $cardiology_total += $row['TotalAmount'];
                    break;
                case 'Radiology':
                    $radiology_total += $row['TotalAmount'];
                    break;
                case 'Lab Test':
                    $laboratory_total += $row['TotalAmount'];
                    break;
            }
        }

        // Process billparticulars totals
        while ($row = $billparticularsQuery->fetch_assoc()) {
            switch ($row['optionlab']) {
                case 'Cardiology':
                    $cardiology_total += $row['TotalAmount'];
                    break;
                case 'Radiology':
                    $radiology_total += $row['TotalAmount'];
                    break;
                case 'Lab Test':
                    $laboratory_total += $row['TotalAmount'];
                    break;
            }
        }
        
        // 
        $examinationPaymentQuery = mysqli_query($db, "
    SELECT 
        SUM(cash) AS TotalCash,
        SUM(cardno) AS TotalCard,
        SUM(upi) AS TotalUPI,
        SUM(bank) AS TotalOtherBank,
        SUM(InsuranceName) AS TotalInsurance,
        SUM(upiid) AS TotalUPIID
    FROM examination 
    WHERE DATE(created_at) BETWEEN '$from' AND '$to'
");

if (!$examinationPaymentQuery) {
    echo "Error executing query for examination payment mode: " . mysqli_error($db);
    exit();
}

// Initialize payment mode totals to 0
$total_cash1 = 0;
$total_card1 = 0;
$total_upi1 = 0;
$total_other1 = 0;

// Fetch and distribute the amounts
if ($row = $examinationPaymentQuery->fetch_assoc()) {
    $total_cash1 = $row['TotalCash'] ?? 0;
    $total_card1 = $row['TotalCard'] ?? 0;
    $total_upi1 = $row['TotalUPI'] ?? 0;
    
    // Add all components to calculate the total for 'Other' payment mode
    $total_other1 = ($row['TotalOtherBank'] ?? 0) + 
                   ($row['TotalInsurance'] ?? 0) + 
                   ($row['TotalUPIID'] ?? 0);
}
    }
}

function calculatePaymentTotals($mode, $amount, &$total_cash, &$total_card, &$total_upi, &$total_other)
{
    switch ($mode) {
        case 'Cash':
            $total_cash += $amount;
            break;
        case 'Card':
            $total_card += $amount;
            break;
        case 'UPI':
            $total_upi += $amount;
            break;
        default:
            $total_other += $amount;
            break;
    }
}
?>
<!DOCTYPE html>
<html>

<head>
    <title>Daily Transactions</title>
    <meta charset="UTF-8">
    <link href="assets/img/favicon.png" rel="icon">
    <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">
    <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
    <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css'>
    <link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Raleway:300,400,500,700,800|Montserrat:300,400,700" rel="stylesheet">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
    <style type="text/css">
        .nav-menu a {
            padding: 3px 3px;
        }

        .hide {
            display: none;
        }

        h4 {
            padding-top: 5px;
            padding-bottom: 0px;
            color: #1abfbf;
            font-weight: bold;
        }

        hr {
            background-color: #1abfbf;
        }

        .footer {
            position: fixed;
            left: 0;
            bottom: 0;
            width: 100%;
            background-color: #efe8e8;
            color: black;
            text-align: center;
            padding: 4px;
            font-size: 12px;
        }

        .footer a {
            font-weight: bold;
            color: #0c0c67;
        }
    </style>
    <style>
        /* Styles for the summary section */
        .summary-table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }

        .summary-table th,
        .summary-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .summary-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .summary-row {
            background-color: #e7f3fe;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .summary-title {
            font-weight: bold;
            color: #004085;
            /* Dark blue */
        }

        .summary-value {
            font-weight: bold;
            color: #155724;
            /* Dark green */
        }
    </style>
</head>

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

    <header id="header">
        <div class="container">
            <nav id="nav-menu-container">
                <ul class="nav-menu">
                    <li class="menu-active">
                        <a class="nav-link" style="padding:2;font-size:14px" href="index.php">Home</a>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">IPD Patients</a>
                        <ul>
                            <li><a href="AddPatient.php">IPD Patient Registration</a></li>
                            <li><a href="AddAdvance.php">IPD add Advance</a></li>
                            <li><a href="UpdateWard.php">Update Ward</a></li>
                            <li><a href="IPDPatients.php">View IPD Patients</a></li>

                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">OPD Patients</a>
                        <ul>
                            <li><a href="OPDRegistration.php">OPD Patient Registration</a></li>
                            <li><a href="OPDPatients.php">View OPD Patients</a></li>
                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">Staff</a>
                        <ul>
                            <li><a href="AddStaff.php">Add Staff</a></li>
                            <li><a href="StaffList.php">Staff List</a></li>
                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">Billing</a>
                        <ul>
                            <li><a href="billingId.php">Generate Consolidate Bill</a></li>
                            <li><a href="InvestigationId.php">Generate Investigation Bill</a></li>
                            <li><a href="FinaleBillId.php">Generate Discharge Bill</a></li>
                            <li><a href="SearchBill.php">Search Bill</a></li>
                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">Particular</a>
                        <ul>
                            <li><a href="AddParticulars.php">Add Particulars</a></li>
                            <li><a href="ViewParticulars.php">View Particulars</a></li>
                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#">Report</a>
                        <ul>
                            <li><a href="UploadReport.php">Upload Patient Report</a></li>
                            <li><a href="DailyTrans.php">Transactions</a></li>
                            <li><a href="userTrans.php">User Transactions</a></li>
                            <li><a href="ViewReport.php">View Patient Reports</a></li>
                        </ul>
                    </li>
                    <li class="menu-has-children">
                        <a class="nav-link" style="padding:2;font-size:14px" href="#" style="font-size:15px"><? echo $name ?></a>
                        <ul>
                            <li><a href="logout.php">Logout</a></li>
                            <li><a href="ResetPassword.php">Reset Password</a></li>
                        </ul>
                    </li>
                </ul>
            </nav><!-- #nav-menu-container -->
        </div>
    </header>

    <section>
        <div class="row">
            <div class="col-md-1"></div>
            <div class="col-md-10">
                <div class="shadow p-3 mb-5 bg-light rounded">
                    <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 $_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 $_POST['dateto'] ?? ''; ?>" required>
                            </div>
                            <div class="col">
                                <button type="submit" class="btn btn-primary" id="viewbtn">View</button>
                            </div>
                        </div>
                    </form>

                    <?php if ($query && mysqli_num_rows($query) > 0) : ?>
                        <?php
                        $fromDate = $_POST['datefrom'] ?? '';
                        $toDate = $_POST['dateto'] ?? '';
                        ?>
                        <script>
                            var fromDate = "<?php echo $fromDate; ?>";
                            var toDate = "<?php echo $toDate; ?>";
                        </script>

                        <button class="btn btn-primary" onclick="exportTableToCSV('tblexportData', fromDate, toDate)">Export to CSV</button>

                        <table border="1" id="tblexportData" class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Sl.No.</th>
                                    <th>Patient Id</th>
                                    <th>Patient Name</th>
                                    <th>Bill Type</th>
                                    <th>Mode Of Payment</th>
                                    <th>Bill No</th>
                                    <th>Bill Date</th>
                                    <th>Payable Amount</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <th colspan="8" style="text-align:center;">OPD Transactions</th>
                                </tr>
                                <?php
                                $opd_counter = 1;
                                $ipd_counter = 1;
                                $advance_counter = 1;
                                $total_opd = 0;
                                $total_ipd = 0;
                                $total_cash = $total_card = $total_upi = $total_other = 0;

                                // Loop through query results
                                while ($row = mysqli_fetch_assoc($query)) {
                                    $patient_id = $row['PatientId'];
                                    $bill_date = $row['BillDate'];
                                    $bill_type = $row['BillType'];
                                    $payable_amount = $row['PayableAmount'];

                                    // Calculate totals
                                    calculatePaymentTotals($row['PaymentMode'], $payable_amount, $total_cash, $total_card, $total_upi, $total_other);

                                    if ($bill_type == 'OPD') {
                                        $total_opd += $payable_amount;
                                        ?>
                                        <tr class="summary-row">
                                            <td><?php echo $opd_counter++; ?></td>
                                            <td><?php echo $patient_id; ?></td>
                                            <td><?php echo $row['PatientName']; ?></td>
                                            <td><?php echo $bill_type; ?></td>
                                            <td><?php echo $row['PaymentMode']; ?></td>
                                            <td>
                                                <a href="ViewTransBill.php?Billno=<?php echo $row['BillNo']; ?>&type=<?php echo $bill_type; ?>" target="_blank">
                                                    <?php echo $row['BillNo']; ?>
                                                </a>
                                            </td>
                                            <td><?php echo date('d-m-Y', strtotime($bill_date)); ?></td>
                                            <td><?php echo $payable_amount; ?></td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>
                                <tr>
                                    <td colspan="7"><strong>Total OPD Transaction Amount</strong></td>
                                    <td><strong><?php echo $total_opd; ?></strong></td>
                                </tr>
                                <tr>
                                    <th colspan="8" style="text-align:center;">IPD Advance Transactions</th>
                                </tr>
                                <?php
                                // Reset the query result pointer if required or re-fetch results for IPD
                                mysqli_data_seek($query, 0); // Reset query pointer if needed

                                while ($row = mysqli_fetch_assoc($query)) {
                                    $patient_id = $row['PatientId'];
                                    $bill_date = $row['BillDate'];
                                    $bill_type = $row['BillType'];
                                    $payable_amount = $row['PayableAmount'];

                                    if ($bill_type == 'Advance') {
                                        $total_ad += $payable_amount;
                                        ?>
                                        <tr class="summary-row">
                                            <td><?php echo $advance_counter++; ?></td>
                                            <td><?php echo $patient_id; ?></td>
                                            <td><?php echo $row['PatientName']; ?></td>
                                            <td><?php echo $bill_type; ?></td>
                                            <td><?php echo $row['PaymentMode']; ?></td>
                                            <td>
                                                <a href="<?php echo ($bill_type == 'Advance') ? "ViewTransBill1.php?Billno={$row['BillNo']}&PatId={$patient_id}&type=Advance" : '#'; ?>" target="_blank">
                                                    <?php echo $row['BillNo']; ?>
                                                </a>
                                            </td>
                                            <td><?php echo date('d-m-Y', strtotime($bill_date)); ?></td>
                                            <td><?php echo $payable_amount; ?></td>
                                        </tr>
                                        <?php
                                    }
                                }
                                ?>
                                <tr>
                                    <td colspan="7"><strong>Total IPD Advance Transaction Amount</strong></td>
                                    <td><strong><?php echo $total_ad; ?></strong></td>
                                </tr>
                                <tr>
                                    <th colspan="8" style="text-align:center;">IPD Transactions</th>
                                </tr>
                                <?php
                                    // Reset the query result pointer if required or re-fetch results for IPD
                                    mysqli_data_seek($query, 0); // Reset query pointer if needed

                                    while ($row = mysqli_fetch_assoc($query)) {
                                        $patient_id = $row['PatientId'];
                                        $bill_date = $row['BillDate'];
                                        $bill_type = $row['BillType'];
                                        $payable_amount = $row['PayableAmount'];
                                        $bill_nos = explode(', ', $row['BillNo']); // Split multiple bill numbers

                                        if ($bill_type != 'OPD' && $bill_type != 'Advance') {
                                            $total_ipd += $payable_amount;
                                            ?>
                                            <tr class="summary-row">
                                                <td><?php echo $ipd_counter++; ?></td>
                                                <td><?php echo $patient_id; ?></td>
                                                <td><?php echo $row['PatientName']; ?></td>
                                                <td><?php echo $bill_type; ?></td>
                                                <td><?php echo $row['PaymentMode']; ?></td>
                                                <td>
                                                    <?php 
                                                    // Loop through each BillNo and generate a hyperlink for it
                                                    foreach ($bill_nos as $bill_no) {
                                                        $url = ($bill_type !== 'Discharge') 
                                                            ? "ViewTransBill.php?Billno=$bill_no&PatId=$patient_id&type=IPD" 
                                                            : "disprint.php?Billno=$bill_no";
                                                        
                                                        // Display each bill number in a new line with its href
                                                        echo '<a href="' . $url . '" target="_blank">' . $bill_no . '</a><br>';
                                                    } 
                                                    ?>
                                                </td>
                                                <td><?php echo date('d-m-Y', strtotime($bill_date)); ?></td>
                                                <td><?php echo $payable_amount; ?></td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>

                                <tr>
                                    <td colspan="7"><strong>Total IPD Transaction Amount</strong></td>
                                    <td><strong><?php echo $total_ipd; ?></strong></td>
                                </tr>
                                
                                <!---->
                               <tr>
    <th colspan="8" style="text-align:center;">Examination Transactions</th>
</tr>
<?php
$exam_counter = 1;
$total_exam = 0; // Initialize total for examination transactions

// Fetch examination details, grouping by BillNo
$examinationDetailsQuery = mysqli_query($db, "
    SELECT 
        e.`BillNo`, e.`PatId`, e.`Particulars`, SUM(e.`Amount`) AS TotalAmount, 
        MAX(e.`created_at`) AS created_at, e.`cash`, e.`cardno`, e.`upi`, e.`upiid`, e.`InsuranceName`,
        p.`Name` AS PatientName, p.`Contact` AS PatientContact
    FROM `examination` e
    LEFT JOIN `patientdetails` p ON e.`PatId` = p.`PatId`
    WHERE DATE(e.`BDate`) BETWEEN '$from' AND '$to'
    GROUP BY e.`BillNo`
");

if (!$examinationDetailsQuery) {
    echo "Error executing examination details query: " . mysqli_error($db);
    exit();
}

while ($row = mysqli_fetch_assoc($examinationDetailsQuery)) {
    $amount = $row['TotalAmount'];
    $total_exam += $amount; // Add to total examination amount
    ?>
    <tr class="summary-row">
        <td><?php echo $exam_counter++; ?></td>
        <td><?php echo $row['PatId']; ?></td>
        <td><?php echo $row['PatientName']; ?></td>
        <td><?php echo $row['PatientContact']; ?></td>
        <td>Examination</td>
       
        <td>
            <a href="ViewExaminationBill.php?Billno=<?php echo $row['BillNo']; ?>" target="_blank">
                <?php echo $row['BillNo']; ?>
            </a>
        </td>
        <td><?php echo date('d-m-Y', strtotime($row['created_at'])); ?></td>
        <td><?php echo $amount; ?></td>
    </tr>
    <?php
}
?>
<tr>
    <td colspan="7"><strong>Total Examination Amount</strong></td>
    <td><strong><?php echo $total_exam; ?></strong></td>
</tr>



                            </tbody>
                            <tfoot>
                               
                               <?php $total = $total_ipd + $total_opd + $total_ad + $cardiology_total + $radiology_total + $laboratory_total; ?>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Grand Total Amount</b></td>
                                    <td><b><?php echo number_format($total, 2); ?></b></td>
                                </tr>
                             </tfoot>
                             
                             </table>
                            <table border="1" id="tblexportData" class="table table-hover">
                             
                                <tr>
                                    <th colspan="8" class="summary-title">Distrubtion Of Total Amount</th>
                                </tr>
                                <tr class="summary-row">
                                        <?php $ipdtotal = $total_ipd + $total_ad ; ?>
                                    <td colspan="7"><b>IPD Total</b></td>
                                    <td class="summary-value"><?php echo $ipdtotal; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>OPD Total</b></td>
                                    <td class="summary-value"><?php echo $total_opd; ?></td>
                                </tr>
                               
                                <tr class="summary-row">
                                    <td colspan="7"><b>Cardiology Total</b></td>
                                    <td class="summary-value"><?php echo $cardiology_total; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Radiology Total</b></td>
                                    <td class="summary-value"><?php echo $radiology_total; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Lab Test Total</b></td>
                                    <td class="summary-value"><?php echo $laboratory_total; ?></b></td>
                                </tr>
                                
  
                                <tr>
                                    <th colspan="8" class="summary-title">Summary of Payment Modes</th>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Cash Total</b></td>
                                   <td><?php echo number_format($total_cash1 + $total_cash, 2); ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Card Total</b></td>
                                    <td><?php echo number_format($total_card1 + $total_card, 2); ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>UPI Total</b></td>
                                    <td><?php echo number_format($total_upi1 + $total_upi, 2); ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7"><b>Other Total</b></td>
                                    <td><?php echo number_format($total_other1 + $total_other, 2); ?></td>
                                </tr>
                                
                            </tfoot>
                        </table>

                    <?php else : ?>
                        <p>No data available for the selected date range.</p>
                    <?php endif; ?>
                    <br>
                    <button type="button" class="btn btn-danger" onclick="history.back()">Back</button><br><br>
                </div>
            </div>
            <div class="col-md-1"></div>
        </div>
    </section>

    <script>
        function exportTableToCSV(tableID, fromDate, toDate) {
            var table = document.getElementById(tableID);
            var rows = table.querySelectorAll('tr');
            var csvContent = [];

            // Build CSV content
            rows.forEach((row, index) => {
                var cols = row.querySelectorAll('td, th');
                var csvRow = [];
                cols.forEach(col => {
                    var cellText = col.innerText.trim();

                    // Remove any unwanted line breaks
                    cellText = cellText.replace(/\n/g, " ");

                    // For headers, apply formatting for CSV
                    if (row.parentElement.tagName === 'THEAD' || index === 0) {
                        cellText = `**${cellText}**`; // Make it bold for CSV viewers that support Markdown
                    }
                    csvRow.push(cellText);
                });
                csvContent.push(csvRow.join(","));
            });

            // Generate dynamic filename
            var filename = `${fromDate}_${toDate}_dailytransactions.csv`;

            // Create a downloadable CSV file
            var csvFile = new Blob([csvContent.join("\n")], { type: 'text/csv' });
            var downloadLink = document.createElement("a");
            downloadLink.href = URL.createObjectURL(csvFile);
            downloadLink.download = filename;

            // Trigger the download
            document.body.appendChild(downloadLink); // Append to DOM for Firefox compatibility
            downloadLink.click();
            document.body.removeChild(downloadLink); // Clean up
        }
    </script>

    <div class="footer">
        &copy; Copyright 2024 All Rights Reserved <strong>Vidyaranya Hospital PVt LTD.</strong>. | Designed by <a href="http://www.vatsinsoft.in/">Vatsin Soft</a>
    </div>

    <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/main.js"></script>
</body>

</html> 