<?php echo $__env->make('header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<div class="container-fluid flex-grow-1 container-p-y">
<style>
    .table th, .table td {
        padding: 5px;
        padding-left: 10px;
    }
    fieldset {
        border: 1px solid #3b6fa5;
        border-radius: 5px;
        padding: 15px;
        margin-bottom: 15px;
        position: relative;
        background: #f5f8fc;
    }
    fieldset legend {
        position: absolute;
        top: -12px;
        left: 15px;
        background: #f5f8fc;
        padding: 0 8px;
        font-size: 14px;
        color: #1d4b7f;
        font-weight: bold;
    }
    .form-control {
        height: 32px;
        font-size: 13px;
    }
</style>
    <h4 class="font-weight-bold py-3 mb-0">IPD BILL</h4>

    <form id="validation-form" novalidate="novalidate" method="POST" enctype="multipart/form-data" autocomplete="off"
        action="">

        <input type="hidden" name="actionvalue" value="Save">
        <input type="hidden" name="saveid" value="">
        <input type="hidden" name="Roll" value="<?php echo e($roll); ?>">
        <input type="hidden" id="BillId">
        <input type="hidden" name="chargesaction" id="action" value="Save">
        <input type="hidden" name="id" id="id" />
        <?php echo csrf_field(); ?>

        <!-- Bill Header Section -->
        <fieldset>
            <legend>Bill Header</legend>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Bill Header</label>
                        <select class="form-control" name="BillHeader" id="BillHeader">
                            <option value="">Select...</option>
                            <?php $__currentLoopData = $consultantList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $result): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($result->id); ?>"><?php echo e($result->Name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Bill No.</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="BillNo" id="Bill_No" 
                                value="<?php echo e($BillNo); ?>" readonly>
                            <div class="input-group-append">
                                <button class="btn btn-secondary" type="button" id="listBillNo" title="List">
                                    List
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Bill Date <span class="text-danger">*</span></label>
                        <input type="date" name="BillDate" id="BillDate" class="form-control" 
                            value="<?php echo e(date('Y-m-d')); ?>" required>
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- Patient Information Section -->
        <fieldset>
            <legend>Patient Information</legend>
            <div class="row">
                <div class="col-md-2">
                    <div class="form-group">
                        <label>IPD No. <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="IpdNo" name="IpdNo" placeholder="" required>
                            <div class="input-group-append">
                                <button class="btn btn-secondary" type="button" id="listIpdNo" title="List">
                                    List
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" id="PatientName" name="PatientName" placeholder="" readonly>
                    </div>
                </div>
                <div class="col-md-1">
                    <div class="form-group">
                        <label>Age</label>
                        <input type="text" class="form-control" id="Age" name="Age" placeholder="" readonly>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Gender</label>
                        <select class="form-control" id="Gender" name="Gender" readonly>
                            <option value="">Select...</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" class="form-control" id="Address" name="Address" placeholder="" readonly>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Mobile</label>
                        <input type="text" class="form-control" id="Mobile" name="Mobile" placeholder="" readonly>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Contact No.</label>
                        <input type="text" class="form-control" id="ContactNo" name="ContactNo" placeholder="" readonly>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>DOA <span class="text-danger">*</span></label>
                        <input type="date" name="AdmissionDate" id="AdmissionDate" class="form-control" 
                            value="<?php echo e(date('Y-m-d')); ?>" required>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>DOD</label>
                        <input type="date" id="DischargeDate" name="DischargeDate" class="form-control" 
                            value="<?php echo e(date('Y-m-d')); ?>">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Consultant <span class="text-danger">*</span></label>
                        <select class="form-control" name="Consultant" id="ConsultantId" required>
                            <option value="" selected disabled>-Select Consultant-</option>
                            <?php $__currentLoopData = $consultantList; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $result): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($result->id); ?>"><?php echo e($result->Name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                </div>
            </div>
            <input type="hidden" id="MrdNo" name="MrdNo">
            <input type="hidden" id="AgeGender" name="AgeGender">
        </fieldset>

        <!-- Procedure Entry Section -->
        <fieldset>
            <legend>Procedure Entry</legend>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Procedure <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select class="form-control" id="Procedure" name="Procedure" required>
                                <option value="">Select Procedure...</option>
                                <?php if(isset($procedures) && count($procedures) > 0): ?>
                                <?php $__currentLoopData = $procedures; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $result): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <?php if($result && isset($result->Name) && $result->Name != ''): ?>
                                <option value="<?php echo e($result->Name); ?>" data-amount="<?php echo e($result->Rate ?? 0); ?>"><?php echo e($result->Name); ?></option>
                                <?php endif; ?>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                <?php endif; ?>
                            </select>
                            <div class="input-group-append">
                                <button class="btn btn-success btn-sm" type="button" id="addProcedure" title="Add">
                                    <i class="feather icon-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Amount <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="Amount" name="Amount" placeholder="0" 
                            onKeyPress="return isNumberKey(event)" required>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Days <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="Days" name="Days" placeholder="0" 
                            onKeyPress="return isNumberKey(event)" required onchange="calculateFinalAmount()">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Final Amount <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="FinalAmount" name="FinalAmount" placeholder="0" 
                                readonly>
                            <div class="input-group-append">
                                <button class="btn btn-success btn-sm" type="button" id="addCharge" title="Add">
                                    <i class="feather icon-plus"></i>
                                </button>&nbsp;&nbsp;
                                <button class="btn btn-danger btn-sm" type="button" id="removeCharge" title="Remove">
                                    <i class="feather icon-minus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <input type="hidden" id="ChargesName" name="ChargesName">
            <input type="hidden" id="Rate" name="Rate">
            <input type="hidden" name="PackageName" id="PackageName" value="GENERAL">
            <input type="hidden" name="PackageAmt" id="PackageAmt" value="0">
        </fieldset>

        <!-- Charges Table Section -->
        <fieldset>
            <legend>Procedures/Charges</legend>
            <div id="please_wait" class="password-tog-info" style="text-align: center; padding-top: 70px; display:none;">
                Please Wait... <img src="<?php echo e(url('preload.gif')); ?>" style="width: 30px;height: 30px;">
            </div>
            <div class="table-responsive" id="custresult" style="max-height: 400px; overflow-y: auto;">
                <!-- Charges list will be loaded here -->
            </div>
        </fieldset>

        <!-- Summary Section -->
        <fieldset>
            <legend>Summary & Payment</legend>
            <div class="row">
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Sub. Total <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="SubTotal" name="SubTotal" placeholder="0" readonly>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Cash Adv. <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="CashAdv" name="CashAdv" placeholder="0" 
                            value="0" onKeyPress="return isNumberKey(event)" onchange="calculateTotalAdvance()">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Card/Neft Adv <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="CardNeftAdv" name="CardNeftAdv" placeholder="0" 
                            value="0" onKeyPress="return isNumberKey(event)" onchange="calculateTotalAdvance()">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Total Advance <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="TotalAdvance" name="TotalAdvance" placeholder="0" readonly>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Discount</label>
                        <input type="text" class="form-control" id="Discount" name="Discount" placeholder="0" 
                            value="0" onKeyPress="return isNumberKey(event)" onchange="calculateBalance()">
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Balance Amt <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="BalAmt" name="BalAmt" placeholder="0" readonly>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-2">
                    <div class="form-group">
                        <label>Paid Amt <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="PaidAmt" name="PaidAmt" placeholder="0" 
                            value="0" onKeyPress="return isNumberKey(event)" onchange="calculateBalance()">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label>Pay Mode</label>
                        <select class="form-control" id="PayMode" name="PayMode">
                            <option value="Cash">Cash</option>
                            <option value="Card">Card</option>
                            <option value="Mobile Payment">Mobile Payment</option>
                            <option value="Cheque">Cheque</option>
                        </select>
                    </div>
                </div>
            </div>
            <input type="hidden" id="GrossAmt" name="GrossAmt" value="0">
        </fieldset>

        <!-- Action Buttons -->
        <div class="row" style="margin-top: 20px; margin-bottom: 20px;">
            <div class="col-md-12">
                <div style="text-align: left; padding: 10px;">
                    <button class="btn btn-primary" type="submit" name="submit" id="submit_save">Save</button>
                    <button class="btn btn-info" type="button" onclick="refreshForm()">Refresh</button>
                    <button class="btn btn-success" type="button" onclick="printBill()" id="printbtn" disabled>Print Bill</button>
                    <button class="btn btn-warning" type="button" onclick="printReceipt()" id="receiptbtn" disabled>Receipt</button>
                    <button class="btn btn-secondary" type="button" onclick="window.close()" style="float: right;">Exit</button>
                </div>
            </div>
        </div>

            </div>
        </div>







    </form>


</div>

<?php echo $__env->make('ipd/incbillchargesmodal', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php echo $__env->make('footerscript', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<script>
    // Calculate Final Amount (Amount * Days)
    function calculateFinalAmount() {
        var amount = parseFloat($('#Amount').val()) || 0;
        var days = parseFloat($('#Days').val()) || 0;
        var finalAmount = amount * days;
        $('#FinalAmount').val(finalAmount.toFixed(2));
        $('#Rate').val(amount);
    }

    // Calculate Total Advance (Cash Adv + Card/Neft Adv)
    function calculateTotalAdvance() {
        var cashAdv = parseFloat($('#CashAdv').val()) || 0;
        var cardNeftAdv = parseFloat($('#CardNeftAdv').val()) || 0;
        var totalAdv = cashAdv + cardNeftAdv;
        $('#TotalAdvance').val(totalAdv.toFixed(2));
        calculateBalance();
    }

    // Calculate Balance Amount
    function calculateBalance() {
        var subTotal = parseFloat($('#SubTotal').val()) || 0;
        var discount = parseFloat($('#Discount').val()) || 0;
        var totalAdvance = parseFloat($('#TotalAdvance').val()) || 0;
        var paidAmt = parseFloat($('#PaidAmt').val()) || 0;
        
        var grossAmt = subTotal - discount;
        $('#GrossAmt').val(grossAmt.toFixed(2));
        
        var balanceAmt = grossAmt - totalAdvance - paidAmt;
        $('#BalAmt').val(balanceAmt.toFixed(2));
    }

    function refreshForm() {
        $('#validation-form')[0].reset();
        $('#actionvalue').val('Save');
        $('#saveid').val('');
        $('#BillId').val('');
        var CurrDate = '<?php echo e(date('Y-m-d')); ?>';
        $('#BillDate').val(CurrDate);
        $('#AdmissionDate').val(CurrDate);
        $('#DischargeDate').val(CurrDate);
        $('#CashAdv').val('0');
        $('#CardNeftAdv').val('0');
        $('#TotalAdvance').val('0');
        $('#Discount').val('0');
        $('#PaidAmt').val('0');
        $('#BalAmt').val('0');
        $('#SubTotal').val('0');
        $('#GrossAmt').val('0');
        $('#submit_save').text('Save');
        $('#printbtn').attr('disabled', true);
        $('#receiptbtn').attr('disabled', true);
        procedure_lists('GENERAL');
    }

    function printBill() {
        var BillId = $('#BillId').val();
        if(BillId) {
            setTimeout(function() {
                window.open(
                    '/<?php echo e(projectUrl()); ?>ipdBillPrint/' + BillId, 'popUpWindow3',
                    'height=1000,width=1000,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
                );
            }, 1);
        } else {
            alert('Please save the bill first');
        }
    }

    function printReceipt() {
        var BillId = $('#BillId').val();
        if(BillId) {
            // Add receipt print functionality here
            alert('Receipt print functionality to be implemented');
        } else {
            alert('Please save the bill first');
        }
    }

    function updateCharges(id,name){
        $('#Chargesid').val(id);
        $('#ChargesName').val(name);
        $('#modal-report656').modal("show");
    }

    function saveUpdateCharges(){
        var id =  $('#Chargesid').val();
        var name =  $('#ChargesName').val();
        var PackageName = $('#PackageName').val();
        $.ajax({
        url: "<?php echo e(url('saveUpdateCharges')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            id: id,
            name: name
        },
        success: function(data) {
            procedure_lists(PackageName);
            $('#modal-report656').modal("hide");
        }
    });

    }
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

function success_toast() {
    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
    $.growl.notice({
        title: 'Success',
        message: 'New Charges Added Successfully!',
        location: isRtl ? 'tl' : 'tr'
    });
}

function error_toast() {
    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
    $.growl.error({
        title: 'Error',
        message: 'Charges Already Exists',
        location: isRtl ? 'tl' : 'tr'
    });
}

function updateBill() {
    var BillId = $('#BillId').val();
    var SubTotal = $('#SubTotal').val();
    var Discount = $('#Discount').val();
    var GrossAmt = $('#GrossAmt').val();
    var PaidAmt = $('#PaidAmt').val();
    var BalAmt = $('#BalAmt').val();
    var PayMode = $('#PayMode').val();
    var Narration = $('#Narration').val();
    var BillDate = $('#BillDate').val();
    var AdmissionDate = $('#AdmissionDate').val();
    var OperationDate = $('#OperationDate').val();
    var DischargeDate = $('#DischargeDate').val();
    var ConsultantId = $('#ConsultantId').val();
    var PatientName = $('#PatientName').val();
    var AgeGender = $('#AgeGender').val();
    $.ajax({
        url: "<?php echo e(url('updateIpdBill')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            BillId: BillId,
            SubTotal: SubTotal,
            Discount: Discount,
            GrossAmt: GrossAmt,
            PaidAmt: PaidAmt,
            BalAmt: BalAmt,
            PayMode: PayMode,
            Narration: Narration,
            BillDate: BillDate,
            AdmissionDate: AdmissionDate,
            OperationDate: OperationDate,
            DischargeDate: DischargeDate,
            ConsultantId: ConsultantId,
            PatientName: PatientName,
            AgeGender: AgeGender
        },
        success: function(data) {
            setTimeout(function() {
                window.open(
                    '/<?php echo e(projectUrl()); ?>ipdBillPrint/' + BillId, 'popUpWindow3',
                    'height=1000,width=1000,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
                );
            }, 1);
        }
    });
}

// Handle Procedure selection - auto-fill Amount
$(document).on('change', '#Procedure', function() {
    var selectedOption = $(this).find('option:selected');
    var procedureName = selectedOption.text() || selectedOption.val();
    var amount = selectedOption.data('amount') || 0;
    $('#Amount').val(amount);
    $('#ChargesName').val(procedureName);
    $('#Rate').val(amount);
    if($('#Days').val() == '' || $('#Days').val() == '0') {
        $('#Days').val('1');
    }
    calculateFinalAmount();
});

// Handle Amount change - recalculate Final Amount
$(document).on('input', '#Amount', function() {
    calculateFinalAmount();
});

function getAmount(days, rate) {
    var Amount = Number(days) * Number(rate);
    $('#Amount').val(Amount);
    calculateFinalAmount();
}

function calCharges(){
    var PackageName = $('#PackageName').val();
    var PackageAmt = $('#PackageAmt').val();
    $.ajax({
        url: "<?php echo e(url('getBillPackageDetails2')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            PackageName: PackageName,
            PackageAmt: PackageAmt
        },
        beforeSend:function(){
            $('#please_wait').show();
        },
        success: function(data) {
            $('#please_wait').hide();
            calBalanceAmt(PackageName);
            totSumBills();
            procedure_lists(PackageName);
        }
    });
}

function getPackageDetails(val) {
    var PackageAmt = $('#PackageAmt').val();
    $.ajax({
        url: "<?php echo e(url('getBillPackageDetails')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            PackageName: val,
            PackageAmt: PackageAmt
        },
        dataType: "json",
        success: function(data) {
            console.log(data);
            if (val == 'Cashless') {
                // Handle cashless
            } else {
                $('#PackageAmt').val(data.PackageAmt);
            }
            procedure_lists(val);
            calBalanceAmt(val);
            totSumBills();
        }
    });
}

function calBalanceAmt(PackageName) {
    var PackageAmt = $('#PackageAmt').val();
    //alert(PackageName);
    $.ajax({
        url: "<?php echo e(url('calBillBalanceAmt')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            PackageName: PackageName,
            PackageAmt: PackageAmt
        },
        success: function(data) {
            //alert(data);
            //$('#BalanceAmt').val(data);
            if (data == 0) {
                $('#submit_save').attr('disabled', false);
                $('#error_msg').hide();
            } else {
                $('#submit_save').attr('disabled', false);
                $('#error_msg').hide();
            }
        }
    });
}

function totSumBills() {
    var Discount = $('#Discount').val();
    var GrossAmt = $('#GrossAmt').val();
    var PaidAmt = $('#PaidAmt').val();
    var BillNo = $('#Bill_No').val();
    $.ajax({
        url: "<?php echo e(url('totSumBills')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>'
        },
        success: function(data) {
            $('#SubTotal').val(data);
            netAmount(data, Discount, GrossAmt, PaidAmt);
            //balBillAmt();
        }
    });
}

function netAmount(SubTotal, Discount, GrossAmt, PaidAmt) {
    var grossAmt = Number(SubTotal) - Number(Discount);
    $('#GrossAmt').val(grossAmt.toFixed(2));
    if(!$('#PaidAmt').val() || $('#PaidAmt').val() == '0') {
        $('#PaidAmt').val(SubTotal);
    }
    calculateBalance();
}

function procedure_lists(PackageName) {
    var pkgName = PackageName || 'GENERAL';
    $.ajax({
        url: "<?php echo e(url('billChargesView2')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            PackageName: pkgName
        },
        beforeSend: function() {
            $('#please_wait').show();
        },
        success: function(data) {
            $('#please_wait').hide();
            $('#custresult').html(data);
        },
        error: function(xhr, status, error) {
            $('#please_wait').hide();
            console.error('Error loading charges:', status, error, xhr.responseText);
            $('#custresult').html('<div class="alert alert-warning">Error loading charges list. Please refresh the page.</div>');
        }
    });
}

// Add Procedure/Charge
$(document).on('click', '#addCharge, #addProcedure', function() {
    var procedure = $('#Procedure').val();
    var chargesName = $('#ChargesName').val() || procedure;
    var amount = $('#Amount').val();
    var days = $('#Days').val();
    var finalAmount = $('#FinalAmount').val();
    var rate = $('#Rate').val() || amount;

    if(!procedure || !amount || !days) {
        alert('Please fill all required fields (Procedure, Amount, Days)');
        return;
    }

    if(finalAmount == '' || finalAmount == '0') {
        alert('Final Amount cannot be zero. Please check Amount and Days.');
        return;
    }

    var action = $('#action').val();
    var id = $('#id').val();
    var PackageName = $('#PackageName').val() || 'GENERAL';
    var PackageAmt = $('#PackageAmt').val() || '0';
    var BillNo = $('#Bill_No').val() || '';
    var MrdNo = $('#MrdNo').val() || '';

    $.ajax({
        url: "<?php echo e(url('saveTempBills')); ?>",
        method: "POST",
        dataType: "json",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            action: action,
            id: id,
            PackageName: PackageName,
            PackageAmt: PackageAmt,
            BalanceAmt: 0,
            ChargesName: chargesName,
            Amount: finalAmount,
            Days: days,
            Rate: rate,
            BillNo: BillNo,
            MrdNo: MrdNo
        },
        beforeSend: function() {
            $('#addCharge, #addProcedure').attr('disabled', 'disabled');
        },
        success: function(data) {
            console.log('Save response:', data, 'PackageName:', PackageName);
            // Handle JSON response
            if (typeof data === 'object' && data !== null) {
                if (data.success === true || data.success === 'true') {
                    if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.notice({
                            title: 'Success',
                            message: data.message || 'Procedure added successfully!',
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert(data.message || 'Procedure added successfully!');
                    }
                    // Refresh the charges list after a small delay to ensure DB save is complete
                    setTimeout(function() {
                        console.log('Refreshing charges list with PackageName:', PackageName);
                        procedure_lists(PackageName);
                        calBalanceAmt(PackageName);
                        totSumBills();
                    }, 200);
                    // Clear form
                    $('#Procedure').val('');
                    $('#ChargesName').val('');
                    $('#Amount').val('');
                    $('#Days').val('1');
                    $('#FinalAmount').val('0');
                    $('#Rate').val('');
                    $('#action').val('Save');
                    $('#id').val('');
                } else {
                    var errorMsg = data.error || 'Failed to add procedure';
                    console.error('Error response:', errorMsg);
                    if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.error({
                            title: 'Error',
                            message: errorMsg,
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert('Error: ' + errorMsg);
                    }
                }
            } 
            // Handle numeric response (legacy format)
            else if (data == 1 || data == '1' || data === 1) {
                if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
                    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                    $.growl.notice({
                        title: 'Success',
                        message: 'Procedure added successfully!',
                        location: isRtl ? 'tl' : 'tr'
                    });
                } else {
                    alert('Procedure added successfully!');
                }
                // Refresh the charges list after a small delay to ensure DB save is complete
                setTimeout(function() {
                    console.log('Refreshing charges list with PackageName:', PackageName);
                    procedure_lists(PackageName);
                    calBalanceAmt(PackageName);
                    totSumBills();
                }, 200);
                // Clear form
                $('#Procedure').val('');
                $('#ChargesName').val('');
                $('#Amount').val('');
                $('#Days').val('1');
                $('#FinalAmount').val('0');
                $('#Rate').val('');
                $('#action').val('Save');
                $('#id').val('');
            } else {
                console.error('Unexpected response:', data);
                if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                    $.growl.error({
                        title: 'Error',
                        message: 'Failed to add procedure. Response: ' + JSON.stringify(data),
                        location: isRtl ? 'tl' : 'tr'
                    });
                } else {
                    alert('Failed to add procedure. Response: ' + JSON.stringify(data));
                }
            }
            $('#addCharge, #addProcedure').attr('disabled', false);
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', status, error, xhr.responseText);
            var errorMessage = 'An error occurred while adding procedure';
            
            // Try to parse JSON error response
            try {
                if (xhr.responseJSON) {
                    errorMessage = xhr.responseJSON.error || xhr.responseJSON.message || errorMessage;
                } else if (xhr.responseText) {
                    var errorResponse = JSON.parse(xhr.responseText);
                    errorMessage = errorResponse.error || errorResponse.message || errorMessage;
                }
            } catch (e) {
                // If not JSON, use the response text or default message
                if (xhr.responseText && xhr.responseText.length < 200) {
                    errorMessage = xhr.responseText;
                } else {
                    errorMessage = error || 'Internal Server Error';
                }
            }
            
            if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                $.growl.error({
                    title: 'Error',
                    message: errorMessage,
                    location: isRtl ? 'tl' : 'tr'
                });
            } else {
                alert('Error: ' + errorMessage);
            }
            $('#addCharge, #addProcedure').attr('disabled', false);
        }
    });
});

function saveBills() {
    var action = $('#action').val();
    var id = $('#id').val();
    var PackageName = $('#PackageName').val();
    var PackageAmt = $('#PackageAmt').val();
    var BalanceAmt = $('#BalanceAmt').val();
    var ChargesName = $('#ChargesName').val();
    var Amount = $('#FinalAmount').val() || $('#Amount').val();
    var Days = $('#Days').val();
    var Rate = $('#Rate').val() || $('#Amount').val();
    var BillNo = $('#Bill_No').val();
    var MrdNo = $('#MrdNo').val();
    $.ajax({
        url: "<?php echo e(url('saveTempBills')); ?>",
        method: "POST",
        dataType: "json",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            action: action,
            id: id,
            PackageName: PackageName,
            PackageAmt: PackageAmt,
            BalanceAmt: BalanceAmt,
            ChargesName: ChargesName,
            Amount: Amount,
            Days: Days,
            Rate: Rate,
            BillNo: BillNo,
            MrdNo: MrdNo
        },
        beforeSend: function() {
            $('#addCharge').attr('disabled', 'disabled');
        },
        success: function(data) {
            // Handle JSON response
            if (typeof data === 'object' && data !== null) {
                if (data.success === true || data.success === 'true') {
                    if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.notice({
                            title: 'Success',
                            message: data.message || 'Charge added successfully!',
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert(data.message || 'Charge added successfully!');
                    }
                    procedure_lists(PackageName);
                    calBalanceAmt(PackageName);
                    totSumBills();
                    $('#Procedure').val('');
                    $('#ChargesName').val('');
                    $('#Amount').val('');
                    $('#Days').val('1');
                    $('#FinalAmount').val('0');
                    $('#Rate').val('');
                    $('#action').val('Save');
                    $('#id').val('');
                } else {
                    var errorMsg = data.error || 'Failed to add charge';
                    if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.error({
                            title: 'Error',
                            message: errorMsg,
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert('Error: ' + errorMsg);
                    }
                }
            } 
            // Handle legacy numeric response (for backward compatibility)
            else if (data == 1 || data == '1' || data === 1) {
                if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
                    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                    $.growl.notice({
                        title: 'Success',
                        message: 'Charge added successfully!',
                        location: isRtl ? 'tl' : 'tr'
                    });
                } else {
                    alert('Charge added successfully!');
                }
                procedure_lists(PackageName);
                calBalanceAmt(PackageName);
                totSumBills();
                $('#Procedure').val('');
                $('#ChargesName').val('');
                $('#Amount').val('');
                $('#Days').val('1');
                $('#FinalAmount').val('0');
                $('#Rate').val('');
                $('#action').val('Save');
                $('#id').val('');
            } else {
                if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                    var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                    $.growl.error({
                        title: 'Error',
                        message: 'Failed to add charge',
                        location: isRtl ? 'tl' : 'tr'
                    });
                } else {
                    alert('Failed to add charge');
                }
            }
            $('#addCharge').attr('disabled', false);
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', status, error);
            var errorMsg = 'An error occurred while adding charge';
            if (xhr.responseJSON && xhr.responseJSON.error) {
                errorMsg = xhr.responseJSON.error;
            } else if (xhr.responseText) {
                try {
                    var errorData = JSON.parse(xhr.responseText);
                    if (errorData.error) {
                        errorMsg = errorData.error;
                    } else if (errorData.message) {
                        errorMsg = errorData.message;
                    }
                } catch (e) {
                    errorMsg = xhr.responseText.substring(0, 100);
                }
            }
            if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                $.growl.error({
                    title: 'Error',
                    message: errorMsg,
                    location: isRtl ? 'tl' : 'tr'
                });
            } else {
                alert('Error: ' + errorMsg);
            }
            $('#addCharge').attr('disabled', false);
        }
    });
}

function print() {
    var BillId = $('#BillId').val();
    setTimeout(function() {
        window.open(
            '/<?php echo e(projectUrl()); ?>ipdBillPrint/' + BillId, 'popUpWindow3',
            'height=1000,width=1000,left=0,top=0,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=no'
        );
    }, 1);
}

function getBillCharges(billno) {
    $.ajax({
        url: "<?php echo e(url('getBillCharges')); ?>",
        method: "POST",
        data: {
            _token: '<?php echo e(csrf_token()); ?>',
            billno: billno
        },
        success: function(data) {
            console.log(data);
            $('#custresult').html(data);
        }
    });
}
$(document).ready(function() {
    var PackageName = $('#PackageName').val();
    getPackageDetails(PackageName);

    $(document).on("change", "#BillType", function(event) {
        var val = this.value;
        if (val == 'Cashless') {
            $('#PackageName').attr("selected", true).val('Cashless');
            getPackageDetails(val)
        }
        else{
            $('#PackageName').attr("selected", true).val('M1');
            getPackageDetails('M1')
        }
    });

    $(document).on("change", "#BillNo", function(event) {
        var val = this.value;

        $.ajax({
            url: "<?php echo e(url('getBillDetails')); ?>",
            method: "POST",
            data: {
                _token: '<?php echo e(csrf_token()); ?>',
                id: val
            },
            dataType: "json",
            success: function(data) {
                //console.log(data);
                $('#BillId').val(data.id);
                $('#Bill_No').val(data.BillNo);
                $('#MrdNo').val(data.MrdNo);
                $('#BillType').val(data.BillType).attr("selected", true);
                $('#PatientName').val(data.PatientName);
                $('#AgeGender').val(data.AgeGender);
                $('#BillDate').val(data.BillDate);
                $('#AdmissionDate').val(data.AdmissionDate);
                $('#OperationDate').val(data.OperationDate);
                $('#DischargeDate').val(data.DischargeDate);
                $('#ConsultantId').val(data.Consultant).attr("selected", true);
                $('#PackageName').val(data.PackageName);
                $('#PackageAmt').val(data.PackageAmt);
                $('#SubTotal').val(data.SubTotal);
                $('#Discount').val(data.Discount);
                $('#GrossAmt').val(data.GrossAmt);
                $('#PaidAmt').val(data.PaidAmt);
                $('#BalAmt').val(data.BalAmt);
                $('#PayMode').val(data.PayMode).attr("selected", true);
                $('#Narration').val(data.Narration);
                getBillCharges(data.BillNo);
            }
        });
    });
    $(document).on("change", "#PatientId", function(event) {
        var val = this.value;
        $.ajax({
            url: "<?php echo e(url('getIpdPatientDetails')); ?>",
            method: "POST",
            data: {
                _token: '<?php echo e(csrf_token()); ?>',
                id: val
            },
            dataType: "json",
            success: function(data) {
                //console.log(data);
                var AgeGender = data.Age + "/" + data.Gender;
                $('#IpdNo').val(data.IpdNo);
                $('#MrdNo').val(data.MrdNo);
                $('#PatientName').val(data.PatientName);
                $('#AgeGender').val(data.AgeGender);
                $('#AdmissionDate').val(data.AdmissionDate);
                $('#DischargeDate').val(data.DischargeDate);
                $('#ConsultantId').val(data.Consultant).attr("selected", true);
                $('#Diagnosis').val(data.Diagnosis);
            }
        });

    });

    $(document).on("click", ".update", function(event) {
        event.preventDefault();
        event.stopPropagation();
        var id = $(this).attr("data-id");

        $.ajax({
            url: "<?php echo e(url('fetchBillChargesRecord')); ?>",
            method: "POST",
            data: {
                _token: '<?php echo e(csrf_token()); ?>',
                id: id
            },
            dataType: "json",
            success: function(data) {
                if (!data) {
                    alert('No data found for this charge');
                    return;
                }
                
                $('#Procedure').val(data.Name || '');
                $('#ChargesName').val(data.Name || '');
                $('#Days').val(data.Days || '1');
                $('#Rate').val(data.Rate || '0');
                $('#Amount').val(data.Rate || '0');
                $('#FinalAmount').val(data.Amount || '0');
                $('#action').val('Edit');
                $('#id').val(id);
                
                // Scroll to procedure entry section
                $('html, body').animate({
                    scrollTop: $('#Procedure').offset().top - 100
                }, 500);
            },
            error: function(xhr, status, error) {
                console.error('Error fetching charge record:', status, error, xhr.responseText);
                alert('Error loading charge record. Please try again.');
            }
        });
    });



    $(document).on("click", ".delete", function(event) {
        event.preventDefault();
        var id = $(this).attr("data-id");
        var action = "delete";
        var PackageName = $('#PackageName').val();
        var BillNo = $('#Bill_No').val();
        //alert(id);
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this Charges!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, delete",
            cancelButtonText: "No, cancel",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function(isConfirm) {
            if (isConfirm) {
                $.ajax({
                    url: "<?php echo e(url('deleteBillChargesRecord')); ?>",
                    method: "POST",
                    data: {
                        _token: '<?php echo e(csrf_token()); ?>',
                        id: id
                    },

                    success: function(data) {
                        //console.log(data);
                        swal("Deleted!", "Charges has been deleted.", "success");

                        procedure_lists(PackageName);
                        calBalanceAmt(PackageName);
                        totSumBills();

                    }
                });

            } else {
                swal("Cancelled", "Charges is safe :)", "error");
            }
        });
    });


    $(document).on("change", "#CounId", function(event) {
        var val = this.value;
        $.ajax({
            url: "<?php echo e(url('checkOtPatient')); ?>",
            method: "POST",
            data: {
                _token: '<?php echo e(csrf_token()); ?>',
                id: val
            },
            success: function(data) {
                //console.log(data);
                var res = JSON.parse(data);
                var result = res.result;
                var AgeGender = result.Age + "/" + result.Gender;

                $('#MrdNo').val(result.MrdNo);
                $('#PatientName').val(result.PatientName);
                $('#AgeGender').val(AgeGender);
                $('#PackageName').val(result.Package);
                $('#PackageAmt').val(result.PkgAmt);
                $('#Diagnosis').val(result.Diagnosis);
                getPackageDetails(result.Package);
            }
        });
    });


    $('#validation-form').on('submit', function(e) {
        e.preventDefault();
        var form = document.getElementById('validation-form');
        if(form.checkValidity()) {
            // Calculate final values before submit
            calculateBalance();
            
            $.ajax({
                url: "<?php echo e(url('saveIpdBill')); ?>",
                method: "POST",
                data: new FormData(this),
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('#submit_save').attr('disabled', 'disabled');
                    $('#submit_save').text('Please Wait...');
                },
                success: function(data) {
                    $('#saveid').val(data);
                    $('#BillId').val(data);
                    $('#printbtn').attr("disabled", false);
                    $('#receiptbtn').attr("disabled", false);
                    $('#submit_save').attr('disabled', false);
                    $('#submit_save').text('Save');
                    
                    if (typeof $.growl !== 'undefined' && typeof $.growl.notice !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.notice({
                            title: 'Success',
                            message: 'IPD Bill saved successfully!',
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert('IPD Bill saved successfully!');
                    }
                },
                error: function(xhr, status, error) {
                    var errorMsg = xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : 'Failed to save bill';
                    if (typeof $.growl !== 'undefined' && typeof $.growl.error !== 'undefined') {
                        var isRtl = $('body').attr('dir') === 'rtl' || $('html').attr('dir') === 'rtl';
                        $.growl.error({
                            title: 'Error',
                            message: errorMsg,
                            location: isRtl ? 'tl' : 'tr'
                        });
                    } else {
                        alert('Error: ' + errorMsg);
                    }
                    $('#submit_save').attr('disabled', false);
                    $('#submit_save').text('Save');
                }
            });
        } else {
            form.reportValidity();
        }
    });

    // Handle IPD No input - fetch patient details
    $(document).on("input", "#IpdNo", function(event) {
        var val = this.value.trim();
        clearTimeout(window.ipdTimer);
        
        if(!val) {
            clearPatientFields();
            return;
        }
        
        window.ipdTimer = setTimeout(function() {
            $.ajax({
                url: "<?php echo e(url('getIpdPatientDetails')); ?>",
                method: "POST",
                data: {
                    _token: '<?php echo e(csrf_token()); ?>',
                    id: val
                },
                dataType: "json",
                success: function(data) {
                    if(data) {
                        $('#IpdNo').val(data.IpdNo);
                        $('#MrdNo').val(data.MrdNo);
                        $('#PatientName').val(data.PatientName);
                        $('#Age').val(data.Age);
                        $('#Gender').val(data.Gender);
                        $('#AgeGender').val(data.Age + "/" + data.Gender);
                        $('#Address').val(data.Address || '');
                        $('#Mobile').val(data.Phone || '');
                        $('#ContactNo').val(data.Phone || '');
                        $('#AdmissionDate').val(data.AdmissionDate);
                        $('#DischargeDate').val(data.DischargeDate);
                        if(data.Consultant) {
                            $('#ConsultantId').val(data.Consultant).attr("selected", true);
                        }
                        if(data.Diagnosis) {
                            $('#Diagnosis').val(data.Diagnosis);
                        }
                    }
                },
                error: function() {
                    // IPD No not found
                }
            });
        }, 400);
    });

    // Handle MRD No input - fetch patient details
    $(document).on("input", "#MrdNo", function(event) {
        var val = this.value.trim();
        clearTimeout(window.mrdTimer);
        
        if(!val) {
            clearPatientFields();
            return;
        }
        
        window.mrdTimer = setTimeout(function() {
            $.ajax({
                url: "<?php echo e(url('getPatientDetails')); ?>",
                method: "POST",
                data: {
                    _token: '<?php echo e(csrf_token()); ?>',
                    id: val
                },
                dataType: "json",
                success: function(data) {
                    if(data) {
                        $('#MrdNo').val(data.MrdNo);
                        $('#PatientName').val(data.PatientName);
                        $('#Age').val(data.Age);
                        $('#Gender').val(data.Gender);
                        $('#AgeGender').val(data.Age + "/" + data.Gender);
                        $('#Address').val(data.Address || '');
                        $('#Mobile').val(data.Phone || '');
                        $('#ContactNo').val(data.Phone || '');
                    }
                }
            });
        }, 400);
    });

    function clearPatientFields() {
        $('#PatientName').val('');
        $('#Age').val('');
        $('#Gender').val('');
        $('#AgeGender').val('');
        $('#Address').val('');
        $('#Mobile').val('');
        $('#ContactNo').val('');
    }

    // Handle Bill No List button
    $('#listBillNo').on('click', function() {
        // Show list of bills - can implement modal or dropdown
        alert('Bill list functionality');
    });

    // Handle IPD No List button
    $('#listIpdNo').on('click', function() {
        // Show list of IPD patients - can implement modal or dropdown
        alert('IPD list functionality');
    });

});
</script><?php /**PATH C:\laragon\www\parijathosp\resources\views//ipd/add-ipd-bill.blade.php ENDPATH**/ ?>