<?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;

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 {
        // Combined query to fetch all types of transactions
        $query = mysqli_query($db, "
            SELECT 
                PatientId,
                PatientName,
                BillType,
                PaymentMode,
                BillNo,
                BillDate,
                PayableAmount
            FROM (
                SELECT 
                    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 
                LEFT JOIN patientdetails p ON a.PatId = p.PatId
                WHERE a.AdvanceDate BETWEEN '$from' AND '$to'

                UNION ALL

                SELECT 
                    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
                LEFT JOIN patientdetails p ON f.PatientId = p.PatId
                WHERE f.DischargeDate BETWEEN '$from' AND '$to'

                UNION ALL

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

                UNION ALL

                SELECT 
                    b.PatientId,
                    o.Name AS PatientName,
                    b.PatientType AS BillType,
                    b.PaymentMode,
                    b.BillNo,
                    b.BDate AS BillDate,
                    b.PayableAmount
                FROM bill b
                LEFT JOIN opdpatientregister o ON b.PatientId = o.PatientId
                WHERE b.BDate BETWEEN '$from' AND '$to' AND b.PatientType = 'OPD'
            ) AS combined_data
            ORDER BY PatientId, BillDate, BillType
        ");

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

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>
</head>

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

    <header id="header">
        <!-- Include your header content here -->
    </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="">
                        <h5>Enter Dates</h5>
                        <div class="row">
                            <div class="form-group col">
                                <label for="datefrom">From</label>
                                <input class="form-control" type="date" name="datefrom" id="datefrom" required>
                            </div>
                            <div class="form-group col">
                                <label for="dateto">To</label>
                                <input class="form-control" type="date" name="dateto" id="dateto" required>
                            </div>
                            <div class="col">
                                <button type="submit" class="btn btn-primary" id="viewbtn">View</button>
                            </div>
                        </div>
                    </form>

                    <?php if (isset($query) && mysqli_num_rows($query) != 0) : ?>
                        <button type="button" class="btn btn-primary" onclick="exportToExcel('tblexportData')">Export To Excel File</button><br><br>

                        <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>
                                <?php
                                $i = 1;
                                $total = 0;
                                $current_patient = '';
                                $current_date = '';

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

                                    // Only print if it's a new patient or a new date for the same patient
                                    if ($patient_id != $current_patient || $bill_date != $current_date) {
                                        $total += $row['PayableAmount'];
                                        calculatePaymentTotals($row['PaymentMode'], $row['PayableAmount'], $total_cash, $total_card, $total_upi, $total_other);
                                ?>
                                        <tr>
                                            <td><?php echo $i; ?></td>
                                            <td><?php echo $patient_id; ?></td>
                                            <td><?php echo $row['PatientName']; ?></td>
                                            <td><?php echo $row['BillType']; ?></td>
                                            <td><?php echo $row['PaymentMode']; ?></td>
                                            <td>
                                                <?php if ($row['BillType'] == 'OPD' || $row['BillType'] == 'Advance') : ?>
                                                    <a href="ViewTransBill.php?Billno=<?php echo $row['BillNo']; ?>&type=<?php echo $row['BillType']; ?>" target="_blank"><?php echo $row['BillNo']; ?></a>
                                                <?php else : ?>
                                                    <?php echo $row['BillNo']; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $bill_date; ?></td>
                                            <td><?php echo $row['PayableAmount']; ?></td>
                                        </tr>
                                <?php
                                        $i++;
                                        $current_patient = $patient_id;
                                        $current_date = $bill_date;
                                    }
                                }
                                ?>
                                <tr>
                                    <td colspan="7">Total Transaction</td>
                                    <td><?php echo $total; ?></td>
                                </tr>
                            </tbody>
                        </table>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="card text-white bg-success mb-3">
                                    <div class="card-header">Cash Total</div>
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo $total_cash; ?></h5>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-primary mb-3">
                                    <div class="card-header">Card Total</div>
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo $total_card; ?></h5>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-info mb-3">
                                    <div class="card-header">UPI Total</div>
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo $total_upi; ?></h5>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card text-white bg-secondary mb-3">
                                    <div class="card-header">Other Total</div>
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo $total_other; ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else : ?>
                        <h3>No records found for the selected date range.</h3>
                    <?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 type="text/javascript">
        function exportToExcel(tableID, filename = '') {
            var downloadurl;
            var dataFileType = 'application/vnd.ms-excel';
            var tableSelect = document.getElementById(tableID);
            var tableHTMLData = tableSelect.outerHTML.replace(/ /g, '%20');

            filename = filename ? filename + '.xls' : 'Transactions.xls';

            downloadurl = document.createElement("a");
            document.body.appendChild(downloadurl);

            if (navigator.msSaveOrOpenBlob) {
                var blob = new Blob(['\ufeff', tableHTMLData], {
                    type: dataFileType
                });
                navigator.msSaveOrOpenBlob(blob, filename);
            } else {
                downloadurl.href = 'data:' + dataFileType + ', ' + tableHTMLData;
                downloadurl.download = filename;
                downloadurl.click();
            }
        }
    </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>