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

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

if (!isset($_SESSION['username']) || !isset($_SESSION['password'])) {
    header("Location: logout.php");
    exit();
}

$username = $_SESSION['username'];
$pass = $_SESSION['password'];

if (isset($_GET['patid'])) {
    $patid = $_GET['patid'];
    $query1 = mysqli_query($db, "SELECT * FROM bill WHERE PatientId='$patid'");
    $query2 = mysqli_query($db, "SELECT * FROM finalbill WHERE PatientId='$patid'");
    $query3 = mysqli_query($db, "SELECT * FROM advance WHERE PatId='$patid'");
    $query4 = mysqli_query($db, "SELECT BillNo, PatId, BDate, BTime, SUM(Amount) AS TotalAmount 
                                    FROM examination 
                                    WHERE PatId='$patid' 
                                    GROUP BY BillNo, PatId, BDate, BTime
                                ");
    // Get total from consolidated bills
    $totalBillQuery = mysqli_query($db, "SELECT SUM(TotAmount) AS TotalBillAmount FROM bill WHERE PatientId='$patid'");
    if ($row = mysqli_fetch_assoc($totalBillQuery)) {
        $totalBillAmount += $row['TotalBillAmount'] ? $row['TotalBillAmount'] : 0;
    }

    // Get total from examination bills
    $examBillQuery = mysqli_query($db, "SELECT SUM(Amount) AS ExamAmount FROM examination WHERE PatId='$patid'");
    if ($row = mysqli_fetch_assoc($examBillQuery)) {
        // $totalBillAmount += $row['ExamAmount'] ? $row['ExamAmount'] : 0;
    }

    // Get total from discharge bills if needed
    $dischargeBillQuery = mysqli_query($db, "SELECT SUM(TotalAmount) AS DischargeAmount FROM finalbill WHERE PatientId='$patid'");
    if ($row = mysqli_fetch_assoc($dischargeBillQuery)) {
        // Only add this if it represents additional charges not included in other bills
        // $totalBillAmount += $row['DischargeAmount'] ? $row['DischargeAmount'] : 0;
    }

    // Get total advance payments
    $advanceQuery = mysqli_query($db, "SELECT SUM(Amount) AS AdvanceAmount FROM advance WHERE PatId='$patid'");
    if ($row = mysqli_fetch_assoc($advanceQuery)) {
        $totalAdvancePaid = $row['AdvanceAmount'] ? $row['AdvanceAmount'] : 0;
    }

    // Get total discounts from finalbill
    $discountQuery = mysqli_query($db, "SELECT SUM(DiscountAmount) AS TotalDiscount FROM finalbill WHERE PatientId='$patid'");
    if ($row = mysqli_fetch_assoc($discountQuery)) {
        $totalDiscount = $row['TotalDiscount'] ? $row['TotalDiscount'] : 0;
    }

    // Calculate final payable amount
    $finalPayableAmount = $totalBillAmount - $totalAdvancePaid - $totalDiscount;
}

$action = isset($_GET['action']) ? $_GET['action'] : 'view';
$billType = isset($_GET['billType']) ? $_GET['billType'] : '';
$billNo = isset($_GET['billNo']) ? $_GET['billNo'] : '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $action == 'edit') {
    // Handle form submission for editing bills
    $billNo = $_POST['billNo'];
    $payableAmount = $_POST['payableAmount'];
    // Add other fields as necessary

    if ($billType == 'advance') {
        $sql = "UPDATE advance SET PayableAmount='$payableAmount' WHERE BillNo='$billNo'";
    } elseif ($billType == 'examination') {
        $sql = "UPDATE examination SET PayableAmount='$payableAmount' WHERE BillNo='$billNo'";
    } elseif ($billType == 'consolidate') {
        $sql = "UPDATE bill SET PayableAmount='$payableAmount' WHERE BillNo='$billNo'";
    }

    if (mysqli_query($db, $sql)) {
        header("Location: PatientDetails.php?patid=$patid");
        exit();
    } else {
        echo "Error updating record: " . mysqli_error($db);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<head>
    <title>NPH-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;
        }

        .pcoded-inner-content {
            font-size: 13px;
        }
    </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">

                                        <li>

                                        </li>
                                        <li>

                                        </li>
                                        <li>

                                        </li>
                                    </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="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 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>Search Bills</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="#!">Search Bills</a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="pcoded-inner-content">
                            <?php if (mysqli_num_rows($query1) != 0 || mysqli_num_rows($query2) != 0 || mysqli_num_rows($query3) != 0 || mysqli_num_rows($query4) != 0): ?>
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5>Billing Summary</h5>
                                    </div>
                                    <div class="card-block">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="card bg-c-blue text-white">
                                                    <div class="card-block">
                                                        <h6 class="m-b-15">Total Bill Amount</h6>
                                                        <h4 class="text-right"><i class="fa fa-rupee m-r-10"></i><?php echo number_format($totalBillAmount, 2); ?></h4>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="card bg-c-green text-white">
                                                    <div class="card-block">
                                                        <h6 class="m-b-15">Advance Paid</h6>
                                                        <h4 class="text-right"><i class="fa fa-rupee m-r-10"></i><?php echo number_format($totalAdvancePaid, 2); ?></h4>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="card bg-c-yellow text-white">
                                                    <div class="card-block">
                                                        <h6 class="m-b-15">Discount</h6>
                                                        <h4 class="text-right"><i class="fa fa-rupee m-r-10"></i><?php echo number_format($totalDiscount, 2); ?></h4>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="card bg-c-red text-white">
                                                    <div class="card-block">
                                                        <h6 class="m-b-15">Payable Amount</h6>
                                                        <h4 class="text-right"><i class="fa fa-rupee m-r-10"></i><?php echo number_format($finalPayableAmount, 2); ?></h4>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <table class="table table-hover table-bordered">
                                    <thead>
                                        <th>Sl.No.</th>
                                        <th>PatientId</th>
                                        <th>Bill Type</th>
                                        <th>Bill No</th>
                                        <th>Bill Date/Time</th>
                                        <th>Payable amount</th>
                                        <th>Action</th>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $i = 1;
                                        $temptotal = 0;

                                        // Advance Bills
                                        while ($row = mysqli_fetch_assoc($query3)) {
                                            echo "<tr><td>$i</td>";
                                            echo "<td>" . $row['PatId'] . "</td>";
                                            echo "<td>Advance</td>";
                                            echo "<td>" . $row['BillNo'] . "</td>";
                                            echo "<td>" . $row['AdvanceDate'] . " ," . date('H:i A', strtotime($row['advanceTime'])) . "</td>";
                                            echo "<td>" . $row['Amount'] . "</td>";
                                            echo "<td><a href='ViewEditBill.php?patid=$patid&billType=advance&billNo=" . $row['BillNo'] . "&action=view'>View</a> | <a href='ViewEditBill.php?patid=$patid&billType=advance&billNo=" . $row['BillNo'] . "&action=edit'>Edit</a> | <a href='DeleteEntry.php?ABillNo=" . $row['BillNo'] . "'>Delete</a></td>";
                                            $i++;
                                        }

                                        // Examination Bills
                                        $amount = 0;
                                        while ($row = mysqli_fetch_assoc($query4)) {
                                            $amount += $row['TotalAmount'];
                                            echo "<tr><td>$i</td>";
                                            echo "<td>" . $row['PatId'] . "</td>";
                                            echo "<td>Examination</td>";
                                            echo "<td>" . $row['BillNo'] . "</td>";
                                            echo "<td>" . $row['BDate'] . " ," . date('H:i A', strtotime($row['BTime'])) . "</td>";
                                            echo "<td>" . $amount . "</td>";
                                            echo "<td><a href='ViewEditBill.php?patid=$patid&billType=examination&billNo=" . $row['BillNo'] . "&action=view'>View</a> | <a href='ViewEditBill.php?patid=$patid&billType=examination&billNo=" . $row['BillNo'] . "&action=edit'>Edit</a> | <a href='DeleteEntry.php?EBillNo=" . $row['BillNo'] . "'>Delete</a></td>";
                                            $i++;
                                        }

                                        // Consolidate Bills
                                        while ($row = mysqli_fetch_assoc($query1)) {
                                            echo "<tr><td>$i</td>";
                                            echo "<td>" . $row['PatientId'] . "</td>";
                                            echo "<td>Consolidate</td>";
                                            echo "<td>" . $row['BillNo'] . "</td>";
                                            echo "<td>" . $row['BDate'] . " ," . date('H:i A', strtotime($row['BTime'])) . "</td>";
                                            echo "<td>" . $row['PayableAmount'] . "</td>";
                                            echo "<td><a href='ViewEditBill.php?patid=$patid&billType=consolidate&billNo=" . $row['BillNo'] . "&action=view'>View</a> | <a href='ViewEditBill.php?patid=$patid&billType=consolidate&billNo=" . $row['BillNo'] . "&action=edit'>Edit</a> | <a href='DeleteEntry.php?CBillNo=" . $row['BillNo'] . "'>Delete</a></td>";
                                            $i++;
                                        }

                                        // Discharge Bills (View Only)
                                        while ($row = mysqli_fetch_assoc($query2)) {
                                            echo "<tr><td>$i</td>";
                                            echo "<td>" . $row['PatientId'] . "</td>";
                                            echo "<td>Discharge</td>";
                                            echo "<td>" . $row['FinalBillNo'] . "</td>";
                                            echo "<td>" . $row['DischargeDate'] . " ," . date('H:i A', strtotime($row['DischargeTime'])) . "</td>";
                                            echo "<td>" . $row['PayableAmount'] . "</td>";
                                            echo "<td><a href='ViewEditBill.php?patid=$patid&billType=discharge&billNo=" . $row['FinalBillNo'] . "&action=view'>View</a> | <a href='ViewEditBill.php?patid=$patid&billType=discharge&billNo=" . $row['FinalBillNo'] . "&action=edit'>Edit</a> | <a href='DeleteEntry.php?FBillNo=" . $row['FinalBillNo'] . "'>Delete</a></td>";
                                            $i++;
                                        }
                                        ?>

                                    </tbody>
                                </table>
                            <?php else: ?>
                                <h3 style="text-align:center">No Bills Generated!</h3>
                            <?php endif; ?>
                        </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>