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

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

// Session check
if (!isset($_SESSION['username']) || !isset($_SESSION['password'])) {
    echo '<META http-equiv="refresh" content="0;logout.php">';
    exit;
}

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

if (isset($_GET['patid'])) {
    $patientId = $_GET['patid'];
    $isOPD = strpos($patientId, 'OPD') !== false;

    // Fetch patient details based on type
    if ($isOPD) {
        $query = mysqli_query($db, "SELECT * FROM opdpatientregister WHERE PatientId='$patientId'");

        if (mysqli_num_rows($query) != 0) {
            $row = $query->fetch_assoc();
            // Assign OPD patient details
            $patid = $row['PatientId'];
            $Pname = $row['Name'];
            $fhname = $row['FHN'];
            $contact1 = $row['Contact'];
            $email = $row['Email'];
            $age = $row['Age'];
            $gender = $row['Gender'];
            $Address = $row['Address'];
            $Consultant = $row['Consultant'];
            $AdmitDate = $row['admitDate'];
            $AdmitTime = $row['AdmitTime'];
            $PatientType = 'OPD';
        }
    } else {
        $query = mysqli_query($db, "SELECT * FROM patientdetails WHERE PatId='$patientId'");

        if (mysqli_num_rows($query) != 0) {
            $row = $query->fetch_assoc();
            // Assign regular patient details
            $patid = $row['PatId'];
            $Pname = $row['Name'];
            $fhname = $row['FHName'];
            $contact1 = $row['Contact'];
            $contact2 = $row['EmContact'];
            $email = $row['Email'];
            $dob = $row['Dob'];
            $age = $row['Age'];
            $gender = $row['Gender'];
            $blood = $row['BloodGroup'];
            $wt = $row['BodyWeight'];
            $height = $row['Height'];
            $Aadhaar = $row['AadhaarNo'];
            $Address = $row['Address'];
            $Mark = $row['Mark'];
            $Consultant = $row['Consultant'];
            $PatientType = $row['PatientType'];
            $AdmitDate = $row['AdmitDate'];
            $AdmitTime = $row['AdmitTime'];
            $Photo = $row['Photo'];
            $CaseType = $row['CaseType'];
            $advance = $row['AdvanceAmount'];
            $paymentmode = $row['PaymentMode'];
            $bank = $row['bank'];
            $cardNo = $row['cardno'];
            $upiAmount = $row['upi'];
            $cash = $row['cash'];
            $cashAAmount = $row['cashamount'];
            $cardAAmount = $row['cardamount'];
            $upiId = $row['upiid'];
            $insuranceName = $row['InsuranceName'];
            $insuranceNo = $row['InsuranceNo'];
        }
    }

    // Handle form submission
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if ($isOPD) {
            // Update OPD patient
            $updateQuery = "UPDATE opdpatientregister SET 
                            Name='" . $_POST['name'] . "',
                            FHN='" . $_POST['fhname'] . "',
                            Contact='" . $_POST['contact1'] . "',
                            Email='" . $_POST['email'] . "',
                            Age='" . $_POST['age'] . "',
                            Gender='" . $_POST['gender'] . "',
                            Address='" . $_POST['Address'] . "',
                            Consultant='" . $_POST['Consultant'] . "',
                            admitDate='" . $_POST['AdmitDate'] . "',
                            AdmitTime='" . $_POST['AdmitTime'] . "'
                            WHERE PatientId='$patientId'";

            if (mysqli_query($db, $updateQuery)) {
                echo "<script>alert('OPD patient details updated successfully!');</script>";
                echo '<META http-equiv="refresh" content="0">';
            } else {
                echo "<script>alert('Error updating OPD details: " . mysqli_error($db) . "');</script>";
            }
        } else {
            // Update regular patient
            $updateQuery = "UPDATE patientdetails SET 
                            Name='" . $_POST['name'] . "',
                            FHName='" . $_POST['fhname'] . "',
                            Contact='" . $_POST['contact1'] . "',
                            EmContact='" . $_POST['contact2'] . "',
                            Email='" . $_POST['email'] . "',
                            Dob='" . $_POST['dob'] . "',
                            Age='" . $_POST['age'] . "',
                            Gender='" . $_POST['gender'] . "',
                            BloodGroup='" . $_POST['blood'] . "',
                            BodyWeight='" . $_POST['wt'] . "',
                            Height='" . $_POST['height'] . "',
                            AadhaarNo='" . $_POST['Aadhaar'] . "',
                            Address='" . $_POST['Address'] . "',
                            Mark='" . $_POST['Mark'] . "',
                            Consultant='" . $_POST['Consultant'] . "',
                            PatientType='" . $_POST['PatientType'] . "',
                            CaseType='" . $_POST['CaseType'] . "',
                            AdmitDate='" . $_POST['AdmitDate'] . "',
                            AdmitTime='" . $_POST['AdmitTime'] . "',
                            AdvanceAmount='" . $_POST['AdvanceAmount'] . "',
                            PaymentMode='" . $_POST['PaymentMode'] . "'";

            // Add payment-specific fields only for regular patients
            if ($_POST['PaymentMode'] === 'UPI') {
                $updateQuery .= ", upiid='" . $_POST['upiid'] . "'";
            } elseif ($_POST['PaymentMode'] === 'Card') {
                $updateQuery .= ", bank='" . $_POST['bank'] . "', cardno='" . $_POST['cardno'] . "'";
            } elseif ($_POST['PaymentMode'] === 'Cash and Card') {
                $updateQuery .= ", bank='" . $_POST['bank-a'] . "', cardno='" . $_POST['cardno-a'] . "', 
                                 cashamount='" . $_POST['cash-a'] . "', cardamount='" . $_POST['card-a'] . "'";
            } elseif ($_POST['PaymentMode'] === 'Cash and UPI') {
                $updateQuery .= ", cash='" . $_POST['cash'] . "', upi='" . $_POST['upi'] . "'";
            } elseif ($_POST['PaymentMode'] === 'Insurance') {
                $updateQuery .= ", InsuranceName='" . $_POST['InsuranceName'] . "', 
                                 InsuranceNo='" . $_POST['InsuranceNo'] . "'";
            }

            $updateQuery .= " WHERE PatId='$patientId'";

            if (mysqli_query($db, $updateQuery)) {
                // Update advance table for regular patients
                handleAdvanceUpdate($db, $patientId, $_POST);
                echo "<script>alert('Patient details updated successfully!');</script>";
                echo '<META http-equiv="refresh" content="0">';
            } else {
                echo "<script>alert('Error updating details: " . mysqli_error($db) . "');</script>";
            }
        }
    }
}

// Helper function to handle advance table updates
function handleAdvanceUpdate($db, $patientId, $postData)
{
    $advanceQuery = "SELECT * FROM advance WHERE PatId='$patientId' AND AdvanceDate='" . $postData['AdmitDate'] . "' LIMIT 1";
    $advanceResult = mysqli_query($db, $advanceQuery);

    $advanceData = [
        'Amount' => $postData['AdvanceAmount'],
        'AdvanceDate' => $postData['AdmitDate'],
        'AdvanceTime' => $postData['AdmitTime'],
        'PaymentMode' => $postData['PaymentMode']
    ];

    // Add payment-specific fields
    if ($postData['PaymentMode'] === 'UPI') {
        $advanceData['upiid'] = $postData['upiid'];
    } elseif ($postData['PaymentMode'] === 'Card') {
        $advanceData['bank'] = $postData['bank'];
        $advanceData['cardno'] = $postData['cardno'];
    } elseif ($postData['PaymentMode'] === 'Cash and Card') {
        $advanceData['bank'] = $postData['bank-a'];
        $advanceData['cardno'] = $postData['cardno-a'];
        $advanceData['cashamount'] = $postData['cash-a'];
        $advanceData['cardamount'] = $postData['card-a'];
    } elseif ($postData['PaymentMode'] === 'Insurance') {
        $advanceData['InsuranceName'] = $postData['InsuranceName'];
        $advanceData['InsuranceNo'] = $postData['InsuranceNo'];
    }

    if (mysqli_num_rows($advanceResult) > 0) {
        // Update existing advance record
        $advanceRow = mysqli_fetch_assoc($advanceResult);
        $advanceId = $advanceRow['BillNo'];

        $updateFields = [];
        foreach ($advanceData as $key => $value) {
            $updateFields[] = "$key='$value'";
        }

        $updateAdvanceQuery = "UPDATE advance SET " . implode(', ', $updateFields) . " WHERE BillNo='$advanceId'";
        mysqli_query($db, $updateAdvanceQuery);
    } else {
        // Insert new advance record
        $columns = implode(', ', array_keys($advanceData));
        $values = "'" . implode("', '", array_values($advanceData)) . "'";

        $insertAdvanceQuery = "INSERT INTO advance (PatId, $columns) VALUES ('$patientId', $values)";
        mysqli_query($db, $insertAdvanceQuery);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

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

        .pad {
            padding-left: 10px;
            font-size: 20px;
        }

        #upiDetails,
        #cardDetails,
        #upiCashDetails,
        #cardCashDetails,
        #InsDetails {
            width: 100%;
        }

        #upiDetails input,
        #cardDetails input,
        #upiCashDetails input,
        #cardCashDetails input,
        #InsDetails input {
            display: block;
            width: 100%;
            margin-bottom: 10px;
            visibility: visible !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 Patient Details</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="#!">Staff Details</a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="pcoded-inner-content">

                            <h2>Patient Information</h2>
                            <form method="POST">
                                <input type="hidden" name="patid" value="<?php echo $patid; ?>">

                                <table class="table table-striped table-hover">
                                    <tr>
                                        <td>Patient ID</td>
                                        <td><?php echo $patid; ?></td>
                                    </tr>
                                    <tr>
                                        <td>Name</td>
                                        <td><input type="text" name="name" value="<?php echo $Pname; ?>" class="form-control"></td>
                                    </tr>
                                    <tr>
                                        <td>Father/Husband Name</td>
                                        <td><input type="text" name="fhname" value="<?php echo $fhname; ?>" class="form-control"></td>
                                    </tr>
                                    <tr>
                                        <td>Contact No.</td>
                                        <td><input type="text" name="contact1" value="<?php echo $contact1; ?>" class="form-control"></td>
                                    </tr>
                                    <?php if (!$isOPD): ?>
                                        <tr>
                                            <td>Emergency Contact No.</td>
                                            <td><input type="text" name="contact2" value="<?php echo $contact2; ?>" class="form-control"></td>
                                        </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <td>Email Id</td>
                                        <td><input type="email" name="email" value="<?php echo $email; ?>" class="form-control"></td>
                                    </tr>
                                    <?php if (!$isOPD): ?>

                                        <tr>
                                            <td>Date of Birth</td>
                                            <td><input type="date" name="dob" value="<?php echo $dob; ?>" class="form-control"></td>
                                        </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <td>Age</td>
                                        <td><input type="number" name="age" value="<?php echo $age; ?>" class="form-control"></td>
                                    </tr>
                                    <tr>
                                        <td>Gender</td>
                                        <td>
                                            <select name="gender" class="form-control">
                                                <option value="Male" <?php if ($gender == 'Male') echo 'selected'; ?>>Male</option>
                                                <option value="Female" <?php if ($gender == 'Female') echo 'selected'; ?>>Female</option>
                                                <option value="Other" <?php if ($gender == 'Other') echo 'selected'; ?>>Other</option>
                                            </select>
                                        </td>
                                    </tr>
                                    <?php if (!$isOPD): ?>

                                        <tr>
                                            <td>Blood Group</td>
                                            <td><input type="text" name="blood" value="<?php echo $blood; ?>" class="form-control"></td>
                                        </tr>
                                        <tr>
                                            <td>Body Weight</td>
                                            <td><input type="text" name="wt" value="<?php echo $wt; ?>" class="form-control"></td>
                                        </tr>
                                        <tr>
                                            <td>Height</td>
                                            <td><input type="text" name="height" value="<?php echo $height; ?>" class="form-control"></td>
                                        </tr>
                                        <tr>
                                            <td>Aadhaar ID</td>
                                            <td><input type="text" name="Aadhaar" value="<?php echo $Aadhaar; ?>" class="form-control"></td>
                                        </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <td>Address</td>
                                        <td><textarea name="Address" class="form-control"><?php echo $Address; ?></textarea></td>
                                    </tr>
                                    <?php if (!$isOPD): ?>
                                        <tr>
                                            <td>Identification Mark</td>
                                            <td><input type="text" name="Mark" value="<?php echo $Mark; ?>" class="form-control"></td>
                                        </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <td>Consultant</td>
                                        <td><select class="form-control" name="Consultant" id="Consultant">
                                                <option value="">Select</option>
                                                <?php
                                                $Consultant = isset($Consultant) ? trim($Consultant) : ''; // Ensure $Consultant is set and trimmed
                                                echo "<!-- Debug: Consultant Value = '{$Consultant}' -->"; // Debug Consultant Value
                                                $docList = mysqli_query($conn, "SELECT doc_id, doc_name, doc_specialization FROM docotorslist");

                                                if (!$docList) {
                                                    echo "Error: " . mysqli_error($conn);
                                                } else {
                                                    while ($data = mysqli_fetch_array($docList)) {
                                                        $doc_name_trimmed = trim($data['doc_name']); // Trim doc_name from DB
                                                        $selected = ($doc_name_trimmed == $Consultant) ? "selected" : "";
                                                        var_dump("$doc_name_trimmed");
                                                        echo "<option value='{$doc_name_trimmed}' $selected>{$doc_name_trimmed}</option>";
                                                    }
                                                }
                                                ?>
                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>Patient Type</td>
                                        <td><input type="text" name="PatientType" value="<?php echo $PatientType; ?>" class="form-control" readonly></td>
                                    </tr>
                                    <?php if (!$isOPD): ?>
                                        <tr>
                                            <td>Case Type</td>
                                            <td><input type="text" name="CaseType" value="<?php echo $CaseType; ?>" class="form-control"></td>
                                        </tr>
                                    <?php endif; ?>
                                    <tr>
                                        <td>Admit Date</td>
                                        <td><input type="date" name="AdmitDate" value="<?php echo $AdmitDate; ?>" class="form-control"></td>
                                    </tr>
                                    <tr>
                                        <td>Admit Time</td>
                                        <td><input type="time" name="AdmitTime" value="<?php echo $AdmitTime; ?>" class="form-control"></td>
                                    </tr>
                                    <?php if (!$isOPD): ?>
                                        <tr>
                                            <td>Advance Amount</td>
                                            <td><input type="number" name="AdvanceAmount" value="<?php echo $advance; ?>" class="form-control"></td>
                                        </tr>
                                        <tr>
                                            <td>Payment Mode</td>
                                            <td>
                                                <select class="form-control" name="PaymentMode" id="PaymentMode" required>
                                                    <option value="">Choose Option</option>
                                                    <?php
                                                    $paymentmode = isset($paymentmode) ? trim($paymentmode) : ''; // Ensure it's set and trimmed
                                                    $options = ["Cash", "Card", "UPI", "Cash and UPI", "Cash and Card", "Insurance", "ABRK"];

                                                    foreach ($options as $option) {
                                                        $selected = ($option == $paymentmode) ? "selected" : "";
                                                        echo "<option value='$option' $selected>$option</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </td>
                                        </tr>
                                        <!-- Insurance Details-->
                                        <tr id="InsDetails" style="display: none;">
                                            <td colspan="2">
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="InsuranceName">Insurance Name<span>*</span></label>
                                                        <input class="form-control" type="text" name="InsuranceName" id="InsuranceName" value="<?php echo $insuranceName; ?>">
                                                    </div>
                                                    <div class="form-group col">
                                                        <label for="InsuranceNo">Insurance No<span>*</span></label>
                                                        <input class="form-control" type="text" name="InsuranceNo" id="InsuranceNo" value="<?php echo $insuranceNo; ?>">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Card Details -->
                                        <tr id="cardDetails" style="display: none;">
                                            <td colspan="2">
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="bank">Bank Name<span>*</span></label>
                                                        <input class="form-control" type="text" name="bank" value="<?php echo $bank; ?>">
                                                    </div>
                                                    <div class="form-group col">
                                                        <label for="cardno">Card No<span>*</span></label>
                                                        <input class="form-control" type="text" name="cardno" value="<?php echo $cardNo; ?>">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Cash and UPI Details -->
                                        <tr id="upiCashDetails" style="display: none;">
                                            <td colspan="2">
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="cash">Cash Amount</label>
                                                        <input class="form-control" type="text" name="cash" value="<?php echo $cash; ?>">
                                                    </div>
                                                    <div class="form-group col">
                                                        <label for="upi">UPI Amount</label>
                                                        <input class="form-control" type="text" name="upi" value="<?php echo $upiAmount; ?>">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- Cash and Card Details -->
                                        <tr id="cardCashDetails" style="display: none;">
                                            <td colspan="2">
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="bank-a">Bank Name<span>*</span></label>
                                                        <input class="form-control" type="text" name="bank-a" value="<?php echo $bank; ?>">
                                                    </div>
                                                    <div class="form-group col">
                                                        <label for="cardno-a">Card No<span>*</span></label>
                                                        <input class="form-control" type="text" name="cardno-a" value="<?php echo $cardNo; ?>">
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="card-a">Card Amount<span>*</span></label>
                                                        <input class="form-control" type="text" name="card-a" value="<?php echo $cardAAmount; ?>">
                                                    </div>
                                                    <div class="form-group col">
                                                        <label for="cash-a">Cash Amount<span>*</span></label>
                                                        <input class="form-control" type="text" name="cash-a" value="<?php echo $cashAAmount; ?>">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>

                                        <!-- UPI Details -->
                                        <tr id="upiDetails" style="display: none;">
                                            <td colspan="2">
                                                <div class="row">
                                                    <div class="form-group col">
                                                        <label for="upiid">UPI Transaction ID<span>*</span></label>
                                                        <input class="form-control" type="text" name="upiid" value="<?php echo $upiId; ?>">
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </table>
                                <button type="submit" class="btn btn-primary">Update Details</button>
                            </form>

                            <script>
                                document.addEventListener('DOMContentLoaded', function() {
                                    // Get DOM elements
                                    const paymentMode = document.getElementById('PaymentMode');
                                    const advanceAmountInput = document.querySelector('input[name="AdvanceAmount"]');
                                    const form = document.querySelector('form');

                                    // Payment detail sections
                                    const sections = {
                                        'UPI': {
                                            element: document.getElementById('upiDetails'),
                                            fields: ['upiid']
                                        },
                                        'Card': {
                                            element: document.getElementById('cardDetails'),
                                            fields: ['bank', 'cardno']
                                        },
                                        'Cash and UPI': {
                                            element: document.getElementById('upiCashDetails'),
                                            fields: ['cash', 'upi']
                                        },
                                        'Cash and Card': {
                                            element: document.getElementById('cardCashDetails'),
                                            fields: ['bank-a', 'cardno-a', 'cash-a', 'card-a']
                                        },
                                        'Insurance': {
                                            element: document.getElementById('InsDetails'),
                                            fields: ['InsuranceName', 'InsuranceNo']
                                        }
                                    };

                                    // Show initial payment fields based on selected payment mode
                                    function initializePaymentFields() {
                                        const selectedMode = paymentMode.value;
                                        hideAllSections();
                                        if (sections[selectedMode]) {
                                            sections[selectedMode].element.style.display = 'table-row';
                                            const fields = sections[selectedMode].fields;
                                            fields.forEach(field => {
                                                const input = document.querySelector(`input[name="${field}"]`);
                                                if (input) {
                                                    input.required = true;
                                                    // Set initial values from PHP if available
                                                    const phpValue = input.getAttribute('data-value');
                                                    if (phpValue) {
                                                        input.value = phpValue;
                                                    }
                                                }
                                            });
                                        }
                                    }

                                    // Hide all payment sections
                                    function hideAllSections() {
                                        Object.values(sections).forEach(section => {
                                            section.element.style.display = 'none';
                                            section.fields.forEach(field => {
                                                const input = document.querySelector(`input[name="${field}"]`);
                                                if (input) {
                                                    input.required = false;
                                                }
                                            });
                                        });
                                    }

                                    // Handle payment mode changes
                                    function handlePaymentModeChange() {
                                        const selectedMode = paymentMode.value;
                                        hideAllSections();

                                        if (sections[selectedMode]) {
                                            sections[selectedMode].element.style.display = 'table-row';
                                            // Make fields required and visible
                                            sections[selectedMode].fields.forEach(field => {
                                                const input = document.querySelector(`input[name="${field}"]`);
                                                if (input) {
                                                    input.required = true;
                                                    input.style.display = 'block';
                                                }
                                            });
                                        }
                                    }

                                    // Validate payment amounts
                                    function validateAmounts() {
                                        const advanceAmount = parseFloat(advanceAmountInput.value) || 0;
                                        const selectedMode = paymentMode.value;

                                        if (selectedMode === 'Cash and Card') {
                                            const cashAmount = parseFloat(document.querySelector('input[name="cash-a"]').value) || 0;
                                            const cardAmount = parseFloat(document.querySelector('input[name="card-a"]').value) || 0;
                                            if (cashAmount + cardAmount > advanceAmount) {
                                                alert(`Total amount (${cashAmount + cardAmount}) cannot exceed the Advance Amount (${advanceAmount})`);
                                                return false;
                                            }
                                        } else if (selectedMode === 'Cash and UPI') {
                                            const cashAmount = parseFloat(document.querySelector('input[name="cash"]').value) || 0;
                                            const upiAmount = parseFloat(document.querySelector('input[name="upi"]').value) || 0;
                                            if (cashAmount + upiAmount > advanceAmount) {
                                                alert(`Total amount (${cashAmount + upiAmount}) cannot exceed the Advance Amount (${advanceAmount})`);
                                                return false;
                                            }
                                        }
                                        return true;
                                    }

                                    // Event listeners
                                    paymentMode.addEventListener('change', handlePaymentModeChange);
                                    form.addEventListener('submit', function(event) {
                                        if (!validateAmounts()) {
                                            event.preventDefault();
                                        }
                                    });

                                    // Initialize on page load
                                    initializePaymentFields();
                                });
                            </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>