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

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// 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 {
        $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
                                ) AS combined_data
                                ORDER BY PatientId, BillDate, BillType;
                    ");

        $examinationQuery = mysqli_query($db, "SELECT optionlab, SUM(Amount) AS TotalAmount 
                                                FROM examination 
                                                WHERE created_at >= '$from 00:00:00' AND created_at <= '$to 23:59:59' 
                                                GROUP BY optionlab;
                                                ");

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

        // Process the examination totals
        $cardiology_total = $radiology_total = $laboratory_total = 0;

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

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

            {
            padding-left: 10px;
            font-size: 20px;
        }
    </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">
                                        <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 active pcoded-trigger">
                                        <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>Daily Transactions</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="#!">Daily Transactions</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>
                            <!--<h1 style="color:red">Under Construction</h1>-->

                            <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" 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 ($query && mysqli_num_rows($query) > 0) : ?>
                        <!--<button type="button" class="btn btn-primary" onclick="exportToExcel('tblexportData')">Export To Excel File</button><br><br>-->
                        <button type="button" class="btn btn-primary" onclick="exportTableToCSV('tblexportData')">Export To CSV File</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>
                                <?php
                                $i = 1;
                                $total = 0;
                                $current_patient = '';
                                $current_date = '';

                                while ($row = mysqli_fetch_assoc($query)) {

                                    $patient_id = $row['PatientId'];
                                    $bill_date = $row['BillDate'];

                                    $total += $row['PayableAmount'];
                                    calculatePaymentTotals($row['PaymentMode'], $row['PayableAmount'], $total_cash, $total_card, $total_upi, $total_other);

                                    if ($row['BillType'] == 'OPD') {
                                        $total_opd += $row['PayableAmount'];
                                    } else {
                                        $total_ipd += $row['PayableAmount'];
                                    }
                                ?>
                                    <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>
                                            <a href="<?php echo ($row['BillType'] == 'OPD') ? "ViewTransBill.php?Billno={$row['BillNo']}&type={$row['BillType']}" : (($row['BillType'] == 'Advance') ? "ViewTransBill1.php?Billno={$row['BillNo']}&PatId={$row['PatientId']}&type=Advance" : '#'); ?>" target="_blank"><?php echo $row['BillNo']; ?></a>
                                        </td>
                                        <td><?php echo date('d-m-Y', strtotime($bill_date)); ?></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>
                            <tfoot>
                                <tr>
                                    <th colspan="8" class="summary-title">Distribution Of total Amounts IN IPD or OPD</th>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">IPD Total</td>
                                    <td class="summary-value"><?php echo $total_ipd; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">OPD Total</td>
                                    <td class="summary-value"><?php echo $total_opd; ?></td>
                                </tr>

                                <tr>
                                    <th colspan="8" class="summary-title">Summary</th>
                                </tr>

                                <tr class="summary-row">
                                    <td colspan="7">Cash Total</td>
                                    <td class="summary-value"><?php echo $total_cash; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">Card Total</td>
                                    <td class="summary-value"><?php echo $total_card; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">UPI Total</td>
                                    <td class="summary-value"><?php echo $total_upi; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">Other Total</td>
                                    <td class="summary-value"><?php echo $total_other; ?></td>
                                </tr>
                                <tr>
                                    <th colspan="8" class="summary-title">Examinations Total</th>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">Cardiology Total</td>
                                    <td class="summary-value"><?php echo $cardiology_total; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">Radiology Total</td>
                                    <td class="summary-value"><?php echo $radiology_total; ?></td>
                                </tr>
                                <tr class="summary-row">
                                    <td colspan="7">Lab Test Total</td>
                                    <td class="summary-value"><?php echo $laboratory_total; ?></td>
                                </tr>
                            </tfoot>
                        </table>

                    <?php else : ?>
                        <p>No data available for the selected date range.</p>
                    <?php endif; ?>
                    <br>  
                </div>



                <script>
                    function exportToExcel(tableID) {
                        var filename = "daily_transactions.xlsx";

                        if (fromDate && toDate) {
                            filename = `daily_transactions_${fromDate}_to_${toDate}.xlsx`;
                        }

                        var table = document.getElementById(tableID);

                        var wb = XLSX.utils.table_to_book(table, {
                            sheet: "Sheet1"
                        });

                        XLSX.writeFile(wb, filename);
                    }
                </script>

                <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>

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