<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 'On');
ob_start();
session_start();
include("dbconfig.php");

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

$patid = $_GET['patid'];
$billType = $_GET['billType'];
$billNo = $_GET['billNo'];
$action = $_GET['action'];

if ($billType == 'advance') {
    $query = mysqli_query($db, "SELECT *, PatId AS PatientId, BillNo, AdvanceDate AS BDate, advanceTime AS BTime FROM advance WHERE PatId='$patid' AND BillNo='$billNo'");
    $row = mysqli_fetch_assoc($query);
    $hasParticulars = false;
} elseif ($billType == 'examination') {
    // $query = mysqli_query($db, "SELECT *, SUM(Amount) AS Amount ,PatId AS PatientId FROM examination WHERE PatId='$patid' AND BillNo='$billNo'");
    $query = mysqli_query($db, "SELECT 
                                    PatId AS PatientId, 
                                    BillNo,
                                    BDate, 
                                    BTime, 
                                    PaymentMode,
                                    GROUP_CONCAT(Particulars ORDER BY SlNo SEPARATOR ', ') AS Particulars, 
                                    SUM(Amount) AS Amount
                                FROM examination 
                                WHERE PatId='$patid' AND BillNo='$billNo' 
                                GROUP BY PatId, BillNo, BDate, BTime, PaymentMode");

    $row = mysqli_fetch_assoc($query);
    $particularsQuery = mysqli_query($db, "SELECT * FROM examination WHERE PatId='$patid' AND BillNo='$billNo' ORDER BY SlNo");
    $particulars = mysqli_fetch_all($particularsQuery, MYSQLI_ASSOC);
    $hasParticulars = true;
} elseif ($billType == 'consolidate') {
    // Main bill query
    $billQuery = mysqli_query($db, "SELECT b.*, b.TotAmount AS Amount FROM bill b WHERE b.PatientId='$patid' AND b.BillNo='$billNo'");
    $row = mysqli_fetch_assoc($billQuery);

    // Particulars query
    $particularsQuery = mysqli_query($db, "SELECT * FROM billparticulars WHERE PatId='$patid' AND BillNo='$billNo' ORDER BY SlNo");
    $particulars = mysqli_fetch_all($particularsQuery, MYSQLI_ASSOC);
    $hasParticulars = true;
} elseif ($billType == 'discharge') {
    $query = mysqli_query($db, "SELECT *, FinalBillNo AS BillNo, DischargeDate AS BDate, DischargeTime AS BTime, TotalAmount AS Amount FROM finalbill WHERE PatientId='$patid' AND FinalBillNo='$billNo'");
    $row = mysqli_fetch_assoc($query);
    $hasParticulars = false;
}

// $row = mysqli_fetch_assoc($query);

if ($_SERVER['REQUEST_METHOD'] == 'POST' && $action == 'edit') {
    $payableAmount = $_POST['payableAmount'];
    $billNo = $_GET['billNo'];

    $paymentMode = $_POST['PaymentMode'];

    if ($billType == 'advance') {
        $advanceDateTime = $_POST['BDateTime'];

        // Splitting Date and Time
        $dateTimeParts = explode('T', $advanceDateTime);
        $advanceDate = $dateTimeParts[0];
        $advanceTime = $dateTimeParts[1] ?? '00:00';

        // Base SQL update for common fields
        $sql = "UPDATE advance SET Amount = ?, PaymentMode = ?, AdvanceDate = ?, advanceTime = ?";
        $params = [$payableAmount, $paymentMode, $advanceDate, $advanceTime];

        // Additional fields based on payment mode
        if ($paymentMode == 'Cash') {
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        } elseif ($paymentMode == 'Card') {
            $bank = $_POST['bank'] ?? '';
            $cardno = $_POST['cardno'] ?? '';
            $sql .= ", cash='', upi='',InsuranceName='', InsuranceNo='', cashamount='',cardamount='', upiid='',bank = ?, cardno = ?";
            $params[] = $bank;
            $params[] = $cardno;
        } elseif ($paymentMode == 'UPI') {
            $upiid = $_POST['upiid'] ?? '';
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ?";
            $params[] = $upiid;
        } elseif ($paymentMode == 'Insurance') {
            $InsuranceName = $_POST['InsuranceName'] ?? '';
            $InsuranceNo = $_POST['InsuranceNo'] ?? '';
            $sql .= ", InsuranceName= ?, InsuranceNo= ?, cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $InsuranceName;
            $params[] = $InsuranceNo;
        } elseif ($paymentMode == 'Cash and UPI') {
            $cash = $_POST['cash'] ?? '';
            $upi = $_POST['upi'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= ?, upi= ?,cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $cash;
            $params[] = $upi;
        } elseif ($paymentMode == 'Cash and Card') {
            $bank = $_POST['bank-a'] ?? '';
            $cardNo = $_POST['cardno-a'] ?? '';
            $cardAmount = $_POST['card-a'] ?? '';
            $cashAmount = $_POST['cash-a'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount=?,cardamount=?,bank=?,cardno=?,upiid = ''";
            $params[] = $cashAmount;
            $params[] = $cardAmount;
            $params[] = $bank;
            $params[] = $cardNo;
        } elseif ($paymentMode == 'ABRK') {
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        }


        $sql .= " WHERE BillNo = ?";
        $params[] = $billNo;

        // Prepare and bind parameters
        if ($stmt = mysqli_prepare($db, $sql)) {
            $types = str_repeat("s", count($params));
            mysqli_stmt_bind_param($stmt, $types, ...$params);

            if (mysqli_stmt_execute($stmt)) {
                ob_end_clean();
                header("Location: ViewMoreBill.php?patid=" . $_GET['patid']);
                exit();
            } else {
                echo "Error updating record: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "SQL Prepare Error: " . mysqli_error($db);
        }
    } elseif ($billType == 'examination') {
        // $sql = "UPDATE examination SET Amount='$payableAmount' WHERE BillNo='$billNo'";
        $advanceDateTime = $_POST['BDateTime'];

        // Splitting Date and Time
        $dateTimeParts = explode('T', $advanceDateTime);
        $advanceDate = $dateTimeParts[0];
        $advanceTime = $dateTimeParts[1] ?? '00:00';

        // Base SQL update for common fields
        $sql = "UPDATE examination SET PaymentMode = ?, BDate = ?, BTime = ?";
        $params = [$paymentMode, $advanceDate, $advanceTime];

        // Additional fields based on payment mode
        if ($paymentMode == 'Cash') {
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        } elseif ($paymentMode == 'Card') {
            $bank = $_POST['bank'] ?? '';
            $cardno = $_POST['cardno'] ?? '';
            $sql .= ", cash='', upi='',InsuranceName='', InsuranceNo='', cashamount='',cardamount='', upiid='',bank = ?, cardno = ?";
            $params[] = $bank;
            $params[] = $cardno;
        } elseif ($paymentMode == 'UPI') {
            $upiid = $_POST['upiid'] ?? '';
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ?";
            $params[] = $upiid;
        } elseif ($paymentMode == 'Insurance') {
            $InsuranceName = $_POST['InsuranceName'] ?? '';
            $InsuranceNo = $_POST['InsuranceNo'] ?? '';
            $sql .= ", InsuranceName= ?, InsuranceNo= ?, cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $InsuranceName;
            $params[] = $InsuranceNo;
        } elseif ($paymentMode == 'Cash and UPI') {
            $cash = $_POST['cash'] ?? '';
            $upi = $_POST['upi'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= ?, upi= ?,cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $cash;
            $params[] = $upi;
        } elseif ($paymentMode == 'Cash and Card') {
            $bank = $_POST['bank-a'] ?? '';
            $cardNo = $_POST['cardno-a'] ?? '';
            $cardAmount = $_POST['card-a'] ?? '';
            $cashAmount = $_POST['cash-a'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount=?,cardamount=?,bank=?,cardno=?,upiid = ''";
            $params[] = $cashAmount;
            $params[] = $cardAmount;
            $params[] = $bank;
            $params[] = $cardNo;
        } elseif ($paymentMode == 'ABRK') {
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        }

        $sql .= " WHERE BillNo = ?";
        $params[] = $billNo;

        // Prepare and bind parameters
        if ($stmt = mysqli_prepare($db, $sql)) {
            $types = str_repeat("s", count($params));
            mysqli_stmt_bind_param($stmt, $types, ...$params);

            if (mysqli_stmt_execute($stmt)) {
                ob_end_clean();
                header("Location: ViewMoreBill.php?patid=" . $_GET['patid']);
                exit();
            } else {
                echo "Error updating record: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "SQL Prepare Error: " . mysqli_error($db);
        }
    } elseif ($billType == 'consolidate') {
        // $sql = "UPDATE bill SET PayableAmount='$payableAmount' WHERE BillNo='$billNo'";
        $advanceDateTime = $_POST['BDateTime'];

        // Splitting Date and Time
        $dateTimeParts = explode('T', $advanceDateTime);
        $advanceDate = $dateTimeParts[0];
        $advanceTime = $dateTimeParts[1] ?? '00:00';

        // Base SQL update for common fields
        $sql = "UPDATE bill SET PayableAmount = ?, PaymentMode = ?, BDate = ?, BTime = ?";
        $params = [$payableAmount, $paymentMode, $advanceDate, $advanceTime];

        // Additional fields based on payment mode
        if ($paymentMode == 'Cash') {
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        } elseif ($paymentMode == 'Card') {
            $bank = $_POST['bank'] ?? '';
            $cardno = $_POST['cardno'] ?? '';
            $sql .= ", cash='', upi='',InsuranceName='', InsuranceNo='', cashamount='',cardamount='', upiid='',bank = ?, cardno = ?";
            $params[] = $bank;
            $params[] = $cardno;
        } elseif ($paymentMode == 'UPI') {
            $upiid = $_POST['upiid'] ?? '';
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ?";
            $params[] = $upiid;
        } elseif ($paymentMode == 'Insurance') {
            $InsuranceName = $_POST['InsuranceName'] ?? '';
            $InsuranceNo = $_POST['InsuranceNo'] ?? '';
            $sql .= ", InsuranceName= ?, InsuranceNo= ?, cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $InsuranceName;
            $params[] = $InsuranceNo;
        } elseif ($paymentMode == 'Cash and UPI') {
            $cash = $_POST['cash'] ?? '';
            $upi = $_POST['upi'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= ?, upi= ?,cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $cash;
            $params[] = $upi;
        } elseif ($paymentMode == 'Cash and Card') {
            $bank = $_POST['bank-a'] ?? '';
            $cardNo = $_POST['cardno-a'] ?? '';
            $cardAmount = $_POST['card-a'] ?? '';
            $cashAmount = $_POST['cash-a'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount=?,cardamount=?,bank=?,cardno=?,upiid = ''";
            $params[] = $cashAmount;
            $params[] = $cardAmount;
            $params[] = $bank;
            $params[] = $cardNo;
        } elseif ($paymentMode == 'ABRK') {
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        }


        $sql .= " WHERE BillNo = ?";
        $params[] = $billNo;

        // Prepare and bind parameters
        if ($stmt = mysqli_prepare($db, $sql)) {
            $types = str_repeat("s", count($params));
            mysqli_stmt_bind_param($stmt, $types, ...$params);

            if (mysqli_stmt_execute($stmt)) {
                ob_end_clean();
                header("Location: ViewMoreBill.php?patid=" . $_GET['patid']);
                exit();
            } else {
                echo "Error updating record: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "SQL Prepare Error: " . mysqli_error($db);
        }
    } elseif ($billType == 'discharge') {
        $advanceDateTime = $_POST['BDateTime'];

        // Splitting Date and Time
        $dateTimeParts = explode('T', $advanceDateTime);
        $advanceDate = $dateTimeParts[0];
        $advanceTime = $dateTimeParts[1] ?? '00:00';

        // Base SQL update for common fields
        $sql = "UPDATE finalbill SET PayableAmount = ?, PaymentMode = ?, DischargeDate = ?, DischargeTime = ?";
        $params = [$payableAmount, $paymentMode, $advanceDate, $advanceTime];

        // Additional fields based on payment mode
        if ($paymentMode == 'Cash') {
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        } elseif ($paymentMode == 'Card') {
            $bank = $_POST['bank'] ?? '';
            $cardno = $_POST['cardno'] ?? '';
            $sql .= ", cash='', upi='',InsuranceName='', InsuranceNo='', cashamount='',cardamount='', upiid='',bank = ?, cardno = ?";
            $params[] = $bank;
            $params[] = $cardno;
        } elseif ($paymentMode == 'UPI') {
            $upiid = $_POST['upiid'] ?? '';
            $sql .= ", InsuranceName='', InsuranceNo='', cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ?";
            $params[] = $upiid;
        } elseif ($paymentMode == 'Insurance') {
            $InsuranceName = $_POST['InsuranceName'] ?? '';
            $InsuranceNo = $_POST['InsuranceNo'] ?? '';
            $sql .= ", InsuranceName= ?, InsuranceNo= ?, cash='', upi='',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $InsuranceName;
            $params[] = $InsuranceNo;
        } elseif ($paymentMode == 'Cash and UPI') {
            $cash = $_POST['cash'] ?? '';
            $upi = $_POST['upi'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= ?, upi= ?,cashamount='',cardamount='',bank='',cardno='',upiid = ''";
            $params[] = $cash;
            $params[] = $upi;
        } elseif ($paymentMode == 'Cash and Card') {
            $bank = $_POST['bank-a'] ?? '';
            $cardNo = $_POST['cardno-a'] ?? '';
            $cardAmount = $_POST['card-a'] ?? '';
            $cashAmount = $_POST['cash-a'] ?? '';
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount=?,cardamount=?,bank=?,cardno=?,upiid = ''";
            $params[] = $cashAmount;
            $params[] = $cardAmount;
            $params[] = $bank;
            $params[] = $cardNo;
        } elseif ($paymentMode == 'ABRK') {
            $sql .= ", InsuranceName= '', InsuranceNo= '', cash= '', upi= '',cashamount='',cardamount='',bank='',cardno='',upiid = ''";
        }


        $sql .= " WHERE FinalBillNo = ?";
        $params[] = $billNo;

        // Prepare and bind parameters
        if ($stmt = mysqli_prepare($db, $sql)) {
            $types = str_repeat("s", count($params));
            mysqli_stmt_bind_param($stmt, $types, ...$params);

            if (mysqli_stmt_execute($stmt)) {
                ob_end_clean();
                header("Location: ViewMoreBill.php?patid=" . $_GET['patid']);
                exit();
            } else {
                echo "Error updating record: " . mysqli_stmt_error($stmt);
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "SQL Prepare Error: " . mysqli_error($db);
        }
    }

    if (mysqli_query($db, $sql)) {
        header("Location: PatientDetails.php?patid=$patid");
        exit();
    } else {
        echo "Error updating record: " . mysqli_error($db);
    }
}
ob_end_flush();
?>

<!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">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

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

        .bills {
            margin: 0 !important;
            margin-left: 150 !important;
        }
    </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-main-container bills">
                            <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><?php echo ucfirst($billType); ?> Bill</h5>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Bills -->
                                <div class="pcoded-inner-content">
                                    <form method="POST" action="ViewEditBill.php?patid=<?php echo $patid; ?>&billType=<?php echo $billType; ?>&billNo=<?php echo $billNo; ?>&action=edit">
                                        <table class="table table-hover table-bordered">
                                            <thead>
                                                <th>Field</th>
                                                <th>Value</th>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td>Patient ID</td>
                                                    <td><?php echo $row['PatientId']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td>Bill Type</td>
                                                    <td><?php echo ucfirst($billType); ?></td>
                                                </tr>
                                                <tr>
                                                    <td>Bill No</td>
                                                    <td><?php echo $row['BillNo']; ?></td>
                                                </tr>
                                                <tr>
                                                    <td>
                                                        <?php
                                                        if ($billType == 'advance') {
                                                            echo 'Advance Date/Time';
                                                        } elseif ($billType == 'discharge') {
                                                            echo 'Discharge Date/Time';
                                                        } else {
                                                            echo 'Bill Date/Time';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                        $BDate = $row['BDate'] ?? null;
                                                        $BTime = $row['BTime'] ?? null;

                                                        if (!empty($BDate) && $BDate != '0000-00-00' && !empty($BTime)) {
                                                            $dateTimeValue = date('d-m-Y', strtotime($BDate)) . " " . date('H:i A', strtotime($BTime));
                                                            $editDateTimeValue = date('Y-m-d\TH:i', strtotime($BDate . ' ' . $BTime));
                                                        } else {
                                                            $dateTimeValue = '';
                                                        }

                                                        ?>
                                                        <?php if ($action == 'edit'): ?>
                                                            <input type="datetime-local" name="BDateTime" value="<?php echo htmlspecialchars($editDateTimeValue); ?>" required>

                                                        <?php else: ?>
                                                            <?php echo htmlspecialchars($dateTimeValue); ?>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>

                                                <tr>
                                                    <td>Payment Mode</td>
                                                    <td>
                                                        <?php if ($action == 'edit'): ?>
                                                            <select class="form-control" name="PaymentMode" id="PaymentMode" required>
                                                                <option value="">Choose Option</option>
                                                                <option value="Cash" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'Cash') ? 'selected' : ''; ?>>Cash</option>
                                                                <option value="Cash and UPI" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'Cash and UPI') ? 'selected' : ''; ?>>Cash and UPI</option>
                                                                <option value="Card" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'Card') ? 'selected' : ''; ?>>Card</option>
                                                                <option value="UPI" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'UPI') ? 'selected' : ''; ?>>UPI</option>
                                                                <option value="Cash and Card" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'Cash and Card') ? 'selected' : ''; ?>>Cash and Card</option>
                                                                <option value="Insurance" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'Insurance') ? 'selected' : ''; ?>>Insurance</option>
                                                                <option value="ABRK" <?php echo (isset($row['PaymentMode']) && $row['PaymentMode'] == 'ABRK') ? 'selected' : ''; ?>>ABARK</option>
                                                            </select>
                                                        <?php else: ?>
                                                            <?php echo isset($row['PaymentMode']) ? htmlspecialchars($row['PaymentMode']) : ''; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>

                                                <tr>
                                                    <td>Payable Amount</td>
                                                    <td>
                                                        <?php if ($action == 'edit'): ?>
                                                            <?php if ($billType == 'consolidate' || $billType == 'examination' || $billType == 'discharge'): ?>
                                                                <input type="number" name="payableAmount" class="form-control" value="<?php echo $row['Amount']; ?>" readonly>
                                                            <?php else: ?>
                                                                <input type="number" name="payableAmount" class="form-control" value="<?php echo $row['Amount']; ?>">
                                                            <?php endif; ?>
                                                        <?php else: ?>
                                                            <?php echo $row['Amount']; ?>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>

                                                <!-- Payment Mode Specific Fields -->
                                                <tr id="InsDetails" style="display: none;">
                                                    <td>Insurance Details</td>
                                                    <td>
                                                        INSURANCE NAME<input class="form-control" type="text" name="InsuranceName" id="InsuranceName" placeholder="Insurance Name" value="<?php echo $row['InsuranceName'] ?? ''; ?>">
                                                        INSURANCE NO<input class="form-control" type="text" name="InsuranceNo" id="InsuranceNo" placeholder="Insurance No" value="<?php echo $row['InsuranceNo'] ?? ''; ?>">
                                                    </td>
                                                </tr>

                                                <tr id="cardDetails" style="display: none;">
                                                    <td>Card Details</td>
                                                    <td>
                                                        BANK NAME<input class="form-control" type="text" name="bank" placeholder="Bank Name" value="<?php echo $row['bank'] ?? ''; ?>">
                                                        CARD NO<input class="form-control" type="text" name="cardno" id="cardno" placeholder="Card No" value="<?php echo $row['cardno'] ?? ''; ?>">
                                                    </td>
                                                </tr>

                                                <tr id="upiCashDetails" style="display: none;">
                                                    <td>UPI & Cash Details</td>
                                                    <td>
                                                        UPI AMOUNT<input class="form-control" type="text" name="upi" placeholder="UPI Amount" value="<?php echo $row['upi'] ?? ''; ?>">
                                                        CASH AMOUNT<input class="form-control" type="text" name="cash" id="cash" placeholder="Cash Amount" value="<?php echo $row['cash'] ?? ''; ?>">
                                                    </td>
                                                </tr>

                                                <tr id="cardCashDetails" style="display: none;">
                                                    <td>Cash & Card Details</td>
                                                    <td>
                                                        BANK NAME<input class="form-control" type="text" name="bank-a" placeholder="Bank Name" value="<?php echo $row['bank'] ?? ''; ?>">
                                                        CARD NO<input class="form-control" type="text" name="cardno-a" placeholder="Card No" value="<?php echo $row['cardno'] ?? ''; ?>">
                                                        CARD AMOUNT<input class="form-control" type="text" name="card-a" placeholder="Card Amount" value="<?php echo $row['cardamount'] ?? ''; ?>">
                                                        CASH AMOUNT<input class="form-control" type="text" name="cash-a" id="cash-a" placeholder="Cash Amount" value="<?php echo $row['cashamount'] ?? ''; ?>">
                                                    </td>
                                                </tr>

                                                <tr id="upiDetails" style="display: none;">
                                                    <td>UPI Transaction</td>
                                                    <td>
                                                        UPI ID<input class="form-control" type="text" name="upiid" placeholder="UPI Transaction ID" value="<?php echo $row['upiid'] ?? ''; ?>">
                                                    </td>
                                                </tr>
                                                <!-- Bill Particulars Section -->
                                                <?php if ($hasParticulars && !empty($particulars)): ?>
                                                    <tr>
                                                        <td colspan="2">
                                                            <h4>Bill Particulars</h4>
                                                            <table class="table table-bordered">
                                                                <thead>
                                                                    <tr>
                                                                        <th>Sl No</th>
                                                                        <th>Particular</th>
                                                                        <th>Quantity</th>
                                                                        <th>Unit Price</th>
                                                                        <th>Amount</th>
                                                                        <?php if ($action == 'edit'): ?>
                                                                            <!-- <th>Action</th> -->
                                                                        <?php endif; ?>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <?php $i = 1;
                                                                    foreach ($particulars as $particular): ?>
                                                                        <tr>
                                                                            <td><?php echo $i++; ?></td>
                                                                            <td>
                                                                                <?php if ($action == 'edit'): ?>
                                                                                    <input type="text" name="particular[<?php echo $particular['SlNo']; ?>][name]"
                                                                                        value="<?php echo $particular['Particulars']; ?>" class="form-control" readonly>
                                                                                <?php else: ?>
                                                                                    <?php echo $particular['Particulars']; ?>
                                                                                <?php endif; ?>
                                                                            </td>
                                                                            <td>
                                                                                <?php if ($action == 'edit'): ?>
                                                                                    <input type="number" name="particular[<?php echo $particular['SlNo']; ?>][quantity]"
                                                                                        value="<?php echo $particular['Quantity']; ?>" class="form-control" readonly>
                                                                                <?php else: ?>
                                                                                    <?php echo $particular['Quantity']; ?>
                                                                                <?php endif; ?>
                                                                            </td>
                                                                            <td>
                                                                                <?php if ($action == 'edit'): ?>
                                                                                    <input type="number" step="0.01" name="particular[<?php echo $particular['SlNo']; ?>][unitprice]"
                                                                                        value="<?php echo $particular['UnitPrice']; ?>" class="form-control" readonly>
                                                                                <?php else: ?>
                                                                                    <?php echo $particular['UnitPrice']; ?>
                                                                                <?php endif; ?>
                                                                            </td>
                                                                            <td>
                                                                                <?php if ($action == 'edit'): ?>
                                                                                    <input type="number" step="0.01" name="particular[<?php echo $particular['SlNo']; ?>][amount]"
                                                                                        value="<?php echo $particular['Amount']; ?>" class="form-control" readonly>
                                                                                <?php else: ?>
                                                                                    <?php echo $particular['Amount']; ?>
                                                                                <?php endif; ?>
                                                                            </td>
                                                                            <?php if ($action == 'edit'): ?>
                                                                                <td>
                                                                                    <!-- <button type="button" class="btn btn-danger btn-sm" onclick="removeParticular(this)">Remove</button> -->
                                                                                </td>
                                                                            <?php endif; ?>
                                                                        </tr>
                                                                    <?php endforeach; ?>
                                                                </tbody>
                                                                <?php if ($action == 'edit'): ?>
                                                                    <tfoot>
                                                                        <tr>
                                                                            <td colspan="6">
                                                                                <!-- <button type="button" class="btn btn-success btn-sm" onclick="addParticular()">Add Particular</button> -->
                                                                            </td>
                                                                        </tr>
                                                                    </tfoot>
                                                                <?php endif; ?>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                                <?php if ($action == 'edit'): ?>
                                                    <tr>
                                                        <td colspan="2">
                                                            <button type="submit" class="btn btn-primary">Submit</button>
                                                            <a href="ViewMoreBill.php?patid=<?php echo $patid ?>" class="btn btn-danger">Back</a>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>

                                                <?php if ($action == 'view'): ?>
                                                    <tr>
                                                        <td colspan="2">
                                                            <a href="ViewMoreBill.php?patid=<?php echo $patid ?>" class="btn btn-danger">Back</a>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </form>
                                </div>

                            </div>
                        </div>
                        <script>
                            document.getElementById("paymentForm").addEventListener("submit", function(event) {
                                let payableAmount = parseFloat(document.getElementById("PayableAmount").value) || 0;
                                let paymentMode = document.getElementById("PaymentMode").value;

                                let cashAmount = parseFloat(document.getElementById("cashamount")?.value) || 0;
                                let cardAmount = parseFloat(document.getElementById("cardamount")?.value) || 0;
                                let upiAmount = parseFloat(document.getElementById("upiid")?.value) || 0;
                                let insuranceName = document.getElementById("InsuranceName")?.value.trim();
                                let insuranceNo = document.getElementById("InsuranceNo")?.value.trim();

                                let totalEntered = cashAmount + cardAmount + upiAmount;

                                // Tally Amount Validation
                                if (totalEntered !== payableAmount) {
                                    alert("Total entered payment must match Payable Amount!");
                                    event.preventDefault();
                                    return false;
                                }

                                // Required Fields Validation based on Payment Mode
                                if (paymentMode === "Cash" && cashAmount === 0) {
                                    alert("Cash amount is required!");
                                    event.preventDefault();
                                    return false;
                                }
                                if (paymentMode === "Card" && (cardAmount === 0 || !document.getElementById("bank").value || !document.getElementById("cardno").value)) {
                                    alert("Card details are required!");
                                    event.preventDefault();
                                    return false;
                                }
                                if (paymentMode === "UPI" && !document.getElementById("upiid").value.trim()) {
                                    alert("UPI ID is required!");
                                    event.preventDefault();
                                    return false;
                                }
                                if (paymentMode === "Insurance" && (!insuranceName || !insuranceNo)) {
                                    alert("Insurance Name and Number are required!");
                                    event.preventDefault();
                                    return false;
                                }
                                if (paymentMode === "Cash and UPI" && (cashAmount === 0 || upiAmount === 0)) {
                                    alert("Both Cash and UPI amounts are required!");
                                    event.preventDefault();
                                    return false;
                                }
                                if (paymentMode === "Cash and Card" && (cashAmount === 0 || cardAmount === 0 || !document.getElementById("bank-a").value || !document.getElementById("cardno-a").value)) {
                                    alert("Both Cash and Card details are required!");
                                    event.preventDefault();
                                    return false;
                                }

                                // If everything is valid, allow form submission
                            });

                            // Calculate amount when quantity or unit price changes
                            function calculateAmount(row) {
                                const quantity = parseFloat(row.querySelector('[name$="[quantity]"]').value) || 0;
                                const unitPrice = parseFloat(row.querySelector('[name$="[unitprice]"]').value) || 0;
                                row.querySelector('[name$="[amount]"]').value = (quantity * unitPrice).toFixed(2);
                            }

                            // Add new particular row
                            function addParticular() {
                                const tbody = document.querySelector('.table-bordered tbody');
                                const newRow = document.createElement('tr');
                                const slNo = tbody.children.length + 1;

                                newRow.innerHTML = `
                                                    <td>${slNo}</td>
                                                    <td><input type="text" name="particular[new_${slNo}][name]" class="form-control"></td>
                                                    <td><input type="number" name="particular[new_${slNo}][quantity]" class="form-control" onchange="calculateAmount(this.parentElement.parentElement)"></td>
                                                    <td><input type="number" step="0.01" name="particular[new_${slNo}][unitprice]" class="form-control" onchange="calculateAmount(this.parentElement.parentElement)"></td>
                                                    <td><input type="number" step="0.01" name="particular[new_${slNo}][amount]" class="form-control" readonly></td>
                                                    <td><button type="button" class="btn btn-danger btn-sm" onclick="removeParticular(this)">Remove</button></td>
                                                `;

                                tbody.appendChild(newRow);
                            }

                            // Remove particular row
                            function removeParticular(button) {
                                button.closest('tr').remove();
                            }

                            // Initialize calculation for existing rows
                            document.addEventListener('DOMContentLoaded', function() {
                                document.querySelectorAll('input[name$="[quantity]"], input[name$="[unitprice]"]').forEach(input => {
                                    input.addEventListener('change', function() {
                                        calculateAmount(this.closest('tr'));
                                    });
                                });
                            });
                        </script>
                        <script>
                            $(document).ready(function() {
                                // Function to update payment mode fields visibility
                                function updatePaymentMode() {
                                    var paymentMode;

                                    if ($("#PaymentMode").length) {
                                        paymentMode = $("#PaymentMode").val();
                                    } else {
                                        paymentMode = $("td:contains('Payment Mode')").next().text().trim();
                                    }
                                    var action = "<?php echo $action; ?>"; // Get the action value from PHP

                                    // Hide all sections first
                                    $('#InsDetails, #cardDetails, #upiCashDetails, #upiDetails, #cardCashDetails').hide();

                                    // Show the relevant section based on the selected payment mode
                                    if (paymentMode == "Insurance") {
                                        $('#InsDetails').show();
                                    } else if (paymentMode == "Card") {
                                        $('#cardDetails').show();
                                    } else if (paymentMode == "Cash and UPI") {
                                        $('#upiCashDetails').show();
                                    } else if (paymentMode == "Cash and Card") {
                                        $('#cardCashDetails').show();
                                    } else if (paymentMode == "UPI") {
                                        $('#upiDetails').show();
                                    }

                                    // If action is view, make all fields readonly
                                    if (action === "view") {
                                        $("input, select").prop("readonly", true).prop("disabled", true);
                                    }
                                }


                                // Call the function on page load to set the initial state
                                updatePaymentMode();

                                // Attach the function to the change event of the PaymentMode dropdown
                                $("#PaymentMode").change(updatePaymentMode);
                            });
                        </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>