@extends('layouts.app')
@section('title', 'Add Fcs Data')
@section('content')
<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> -->
<meta name="csrf-token" content="{{ csrf_token() }}">

<section class="content">
  <div class="row">       
    <div class="col-lg-12 col-12">
      <div class="box">

        <form method="post">
          @csrf
          <div class="box-body"><!--bg-lightest-->

            <h4 class="box-title text-info mb-0"><i class="fa fa-plus"></i> FCS for Lead id {{$lead_id}}</h4>
            <!-- <button class="btn btn-primary" id="btn_add_tab"style="float:right;">
            <span class="hidden-xs-down">Add one more</span>
        </button> -->
        <input type="hidden"value="{{$lead_id}}"id="lead_id">
        <a id="btn_add_tab"style="float: right;margin-right:10px;" href="" type="button" class="btn btn-primary btn-sm mb-5"><i class="fa fa-plus"></i> Add one more</a>          
            <hr class="my-15">

            <div class="row">
            <div class="col-12 ">
        
        <div class="nav-tabs-custom">
        <div class="text-align:right;margin:10px;">
       
</div> 
                    <ul class="nav nav-tabs" role="tablist"id="tabList">

                        <li class="nav-item"> <a class="nav-link active"  data-bs-toggle="tab" href="#usertimeline" role="tab" aria-controls="home5" aria-expanded="true"><span class="hidden-sm-up"><i class="ion-home"></i></span> <span class="hidden-xs-down">Bank 1({{ isset($fcs_data[0]) ? $fcs_data[0]->bank_name : '' }})</span></a> </li>      
                         
                    </ul>
  
             
        <div class="tab-content "id="tabContent" style="padding: 0.50rem !important;min-height: unset !important;background: unset !important;">

        <div class=" active tab-pane" role="tabpanel" id="usertimeline">
          <div class="col-md-12">
                            <div class="jarviswidget jarviswidget-sortable" role="widget">
                                <!-- Existing fields for Fcs Data -->
                                <form method="post" action="">
                                @csrf
                                <div class="col-md-3">
    <div class="form-group @error('last_name') has-error @enderror">
        
            <label class="form-label">Bank Name</label>
            <div class="input-group mb-3">
                <input type="text" class="form-control" name="bank_name" value="{{ isset($fcs_data[0]) ? $fcs_data[0]->bank_name : '' }}"id="bank_name">
           
            </div>
       
    </div>
</div>

              </div>
                  <div class="table-responsive">
                  <table id="#editTable1" class="mainTable table editable-table table-bordered mb-0">
    <thead>
        <tr>
            <th>Month</th>
            <th class="deposit1">Deposits</th>
            <th class="adjustment">Adjustment</th>
            <th>Revenue</th>
            <th class="adb">ADB</th>
            <th class="deposit2">No of Deposits</th>
            <th class="nsfs">NSFs</th>
            <th class="negatives">Negatives</th>
            <th class="ending-balance">Ending Balance</th>
        </tr>
    </thead>
    <tbody>

        
        <input type="hidden"name="bank_id"id=""value="1">
        <!-- Define an array of months -->
        @php
            $months = [
                'January', 'February', 'March', 'April', 'May', 'June',
                'July', 'August', 'September', 'October', 'November', 'December'
            ];
            $selectedBankId = 1;
        @endphp

        @foreach ($months as $month)
            @php
                // Check if any bank record exists for the current month
                $record = null;
                $fcs_data = collect($fcs_data); // Convert to Collection if it's an array     
                // Check if fcs_data is not empty
        if ($fcs_data->isNotEmpty()) {
            // Filter by bank_id first and then by month
            $record = $fcs_data->filter(function ($bank) use ($selectedBankId, $month) {
                // Ensure bank_id is not null and matches the selectedBankId
                return !empty($bank->records) && collect($bank->records)->contains(function ($data) use ($selectedBankId, $month) {
                    return isset($data->bank_id) && $data->bank_id == $selectedBankId && $data->month === $month;
                });
            })->flatMap(function ($bank) use ($month, $selectedBankId) {
                // Now filter by both bank_id and month
                return collect($bank->records)->filter(function ($data) use ($selectedBankId, $month) {
                    return isset($data->bank_id) && $data->bank_id == $selectedBankId && $data->month === $month;
                });
            })->first();
        }
            @endphp

            <tr>
                <td>{{ $month }}</td>
                <td class="deposit1" contenteditable="true" data-name="deposit1[{{ $month }}]">{{ $record ? $record->deposits : '' }}</td>
                <td class="adjustment" contenteditable="true" data-name="adjustment[{{ $month }}]">{{ $record ? $record->adjustment : '' }}</td>
                <td class="revenue" data-name="revenue[{{ $month }}]">{{ $record ? $record->revenue : '' }}</td>
                <td class="adb" contenteditable="true" data-name="adb[{{ $month }}]">{{ $record ? $record->adb : '' }}</td>
                <td class="deposit2" contenteditable="true" data-name="deposit2[{{ $month }}]">{{ $record ? $record->deposits2 : '' }}</td>
                <td class="nsfs" contenteditable="true" data-name="nsfs[{{ $month }}]">{{ $record ? $record->nsfs : '' }}</td>
                <td class="negatives" contenteditable="true" data-name="negatives[{{ $month }}]">{{ $record ? $record->negatives : '' }}</td>
                <td class="ending-balance" contenteditable="true" data-name="ending-balance[{{ $month }}]">{{ $record ? $record->ending_balance : '' }}</td>
            </tr>
        @endforeach
   
</tbody>

    <tfoot>
        <tr>
            <th><strong>Totals</strong></th>
            <th id="totalDeposits1">0.00</th>
            <th id="totalAdjustment">0.00</th>
            <th id="totalRevenue">0.00</th>
            <th id="totalADB">0.00</th>
            <th id="totalDeposits2">0.00</th>
            <th id="totalNSFs">0.00</th>
            <th id="totalNegatives">0.00</th>
            <th id="totalEndingBalance">0.00</th>
        </tr>
        <tr>
            <th><strong>Averages</strong></th>
            <th id="avgDeposits1">0.00</th>
            <th id="avgAdjustment">0.00</th>
            <th id="avgRevenue">0.00</th>
            <th id="avgADB">0.00</th>
            <th id="avgDeposits2">0.00</th>
            <th id="avgNSFs">0.00</th>
            <th id="avgNegatives">0.00</th>
            <th id="avgEndingBalance">0.00</th>
        </tr>
    </tfoot>
</table>
<br>
<!-- <div class="col-md-3">
<div class="form-group @error('last_name') has-error @enderror">
        
        <label class="form-label">Bank Name</label>
        <div class="input-group mb-3">
            <input type="text" class="form-control" name="bank_name" value="{{ isset($fcs_data[0]) ? $fcs_data[0]->bank_name : '' }}">
            <div class="input-group-append">
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div> -->
   
</div>
<a target="_blank" href="{{ route('eligible-lender', ['lead_id'=>$lead_id,'bank_id' => $selectedBankId]) }}" class="btn btn-primary" type="button" style="float:right;margin-left:10px;">Find Eligible Lender</a>
<button id=""class="saveDataBtn btn btn-primary"style="float:right;">Save Data</button>
@foreach ($months as $month)
        <input type="hidden" name="deposit1[{{ $month }}]" id="deposit1[{{ $month }}]">
        <input type="hidden" name="adjustment[{{ $month }}]" id="adjustment[{{ $month }}]">
        <input type="hidden" name="revenue[{{ $month }}]" id="revenue[{{ $month }}]">
        <input type="hidden" name="adb[{{ $month }}]" id="adb[{{ $month }}]">
        <input type="hidden" name="deposit2[{{ $month }}]" id="deposit2[{{ $month }}]">
        <input type="hidden" name="nsfs[{{ $month }}]" id="nsfs[{{ $month }}]">
        <input type="hidden" name="negatives[{{ $month }}]" id="negatives[{{ $month }}]">
        <input type="hidden" name="ending-balance[{{ $month }}]" id="ending-balance[{{ $month }}]">
    @endforeach
</form>
<br><br>

                  </div>

          </div>
        </div>
       
</div>
@php

    // Initialize average revenue
    $averageBankRevenue = 0;

    // Find the bank data that matches the selected bank ID
    foreach ($fcs_data as $bankData) {
        // Get records for the matched bank
        $records = $bankData->records;

        // Check if there are any records and calculate the average revenue
        if (!empty($records)) {
            $totalRevenue = 0;
            $count = 0;

            // Loop through each record to check for a matching bank_id
            foreach ($records as $record) {
                // Check if the bank_id of the record matches the selected bank ID
                if ($record->bank_id == $selectedBankId) {
                    // Only add to total revenue if revenue is not null
                    if ($record->revenue !== null) {
                        $totalRevenue += $record->revenue; // Sum up the revenue
                        $count++; // Count the number of valid records
                    }
                }
            }

            // Calculate average revenue only if there are valid records
            $averageBankRevenue = $count > 0 ? $totalRevenue / $count : 0;
            break; // Exit loop once the average is calculated
        }
    }

    // Debugging: Output the average revenue
    //dd($averageBankRevenue);
@endphp




<form method="post" action="{{ url('lender-matrix/' . $lead_id . '/' . $selectedBankId) }}">
@csrf
<table class="table table-bordered mb-0" id="lenderTable">
    <thead>
      
            <tr>
                <th>Lender</th>
                <th>Funding Date</th>
                <th>Net</th>
                <th>Funding</th>
                <th>Funding Factor</th>
                <th>Payback</th>
                <th>Weekly</th>
                <th>Daily</th>
                <th>Balance</th>
                <th>Days</th>
                <th>Withhold</th>
                <th>End Date</th>
                <th>Transfer Accounts</th>
                <th>Notes</th>
            </tr>
        </form>
    </thead>
    <tbody id="tableBody">
          @foreach($lender_data as $event)
          @if($event->bank_id == $selectedBankId) 
                <tr>
                    <td contenteditable="true" class="lender-column" data-name="lender_name">{{ $event->lender_name }}</td>
                    <td contenteditable="true" class="date-column" data-name="funding_date">{{ $event->funding_date }}</td>
                    <td contenteditable="true" class="number-column" data-name="net">{{ $event->net }}</td>
                    <td contenteditable="true" class="number-column" data-name="funding">{{ $event->funding }}</td>
                    <td contenteditable="true" class="number-column" data-name="funding_factor">{{ $event->funding_factor }}</td>
                    <td contenteditable="true" class="number-column" data-name="payback"></td>
                    <td contenteditable="true" class="number-column" data-name="weekly">{{ $event->weekly }}</td>
                    <td contenteditable="true" class="number-column daily-column" data-name="daily">{{ $event->daily }}</td>
                    <td contenteditable="true" class="number-column" data-name="balance">{{ $event->balance }}</td>
                    <td contenteditable="true" class="number-column" data-name="days">{{ $event->days }}</td>
                    <td contenteditable="true" class="number-column" data-name="withhold">{{ $event->withhold }}</td>
                    <td contenteditable="true" class="date-column" data-name="end_date">{{ $event->end_date }}</td>
                    <td contenteditable="true" class="date-column" data-name="transfer_accounts">{{ $event->transfer_accounts }}</td>
                    <td contenteditable="true" class="number-column" data-name="notes">{{ $event->notes }}</td>
                </tr>
                @endif
            @endforeach
        <tr id="templateRow" style="display: none;">
            <td contenteditable="true"class="lender-column" data-name="lender_name"></td>
            <td contenteditable="true" class="date-column" data-name="funding_date"></td>
            <td contenteditable="true" class="number-column" data-name="net"></td>
            <td contenteditable="true" class="number-column" data-name="funding"></td>
            <td contenteditable="true" class="number-column" data-name="funding_factor"></td>
            <td contenteditable="true" class="number-column" data-name="payback"></td>
            <td contenteditable="true" class="number-column" data-name="weekly"></td>
            <td contenteditable="true" class="number-column daily-column" data-name="daily"></td>
            <td contenteditable="true" class="number-column" data-name="balance"></td>
            <td contenteditable="true" class="number-column" data-name="days"></td>
            <td contenteditable="true" class="number-column" data-name="withhold"></td>
            <td contenteditable="true" class="date-column" data-name="end_date"></td>
            <td contenteditable="true" class="date-column" data-name="transfer_accounts"></td>
            <td contenteditable="true" class="number-column" data-name="notes"></td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2"><strong>Daily Payment Total</strong></td>
            <td id="dailyPaymentTotal"></td>
        </tr>
        <tr>
            <td colspan="2"><strong>Monthly Payment</strong></td>
            <td id="monthlyPaymentTotal"></td>
            <td><strong>Withhold</strong></td>
            <td id="totalwithhold"></td>
            <td colspan="2"><strong>Total Balance</strong></td>
            <td id="totalBalance">0</td>
        </tr>
    </tfoot>
</table>
<br>
<button id="savedatabtnLender" class="btn btn-primary" style="float: right;">Save Data</button>
<button id="addMoreBtnLender" class="btn btn-primary" style="float: right;margin-right:10px;">Add Row</button>

    </form>     
          
              <!-- Add your existing FCS data fields here -->

            </div> <!-- End of Fcs Data Row -->

   


       
          </div>  


      </div>
    </div>  
  </div>
  <!-- jQuery -->

</section>
<!-- Plugin Scripts -->
<script src="{{ asset('assets/vendor_components/tiny-editable/mindmup-editabletable.js') }}"></script>
<script src="{{ asset('assets/vendor_components/tiny-editable/numeric-input-example.js') }}"></script>

<!-- Initialization Scripts -->
<script src="{{ asset('assets/js/pages/editable-tables.js') }}"></script>

<!-- Other Scripts -->
<script src="{{ asset('assets/js/vendors.min.js') }}"></script>
<script src="{{ asset('assets/js/template.js') }}"></script>
<script>
    // Pass the calculated average to JavaScript
    const averageBankRevenue = {{ $averageBankRevenue }};
    //alert(averageBankRevenue);
</script>
<!-- <script>
document.addEventListener("input", function() {
    // Variables to hold totals
    let dailyPaymentTotal = 0;
    let monthlyPaymentTotal = 0;
    let totalBalance = 0;
    let totalWithhold = 0; // Declare a variable to accumulate total withhold

    // Loop through each row in the table to calculate totals
    document.querySelectorAll("#tableBody tr").forEach(row => {
        const daily = parseFloat(row.querySelector('[data-name="daily"]').innerText) || 0;
        const funding = parseFloat(row.querySelector('[data-name="funding"]').innerText) || 0;
        const fundingFactor = parseFloat(row.querySelector('[data-name="funding_factor"]').innerText) || 0;

        // Calculate daily and monthly payments
        dailyPaymentTotal += daily;
        const monthlyPayment = daily * 16;

        // Calculate total balance for this row and add to total balance
        totalBalance += (funding * fundingFactor) - monthlyPayment;

        // Calculate withhold percentage based on averageBankRevenue
        const withhold = averageBankRevenue ? (monthlyPayment / averageBankRevenue) * 100 : 0;

        // Update the withhold column in the row
        const withholdCell = row.querySelector('[data-name="withhold"]');
        if (withholdCell) {
            withholdCell.innerText = withhold.toFixed(2); // Ensure you're setting the inner text to the calculated value
        } else {
            console.error("Withhold cell not found in row:", row);
        }

        // Accumulate total withhold
        totalWithhold += withhold; // Add the current row's withhold to totalWithhold

        // Debugging: log values to check their correctness
        console.log(`Daily: ${daily}, Funding: ${funding}, Funding Factor: ${fundingFactor}, Monthly Payment: ${monthlyPayment}, Withhold: ${withhold}`);
    });

    // Calculate monthly payment total as daily total * 16 (for display purposes)
    monthlyPaymentTotal = dailyPaymentTotal * 16;

    // Set the calculated totals in the footer
    document.getElementById("dailyPaymentTotal").innerText = dailyPaymentTotal.toFixed(2);
    document.getElementById("monthlyPaymentTotal").innerText = monthlyPaymentTotal.toFixed(2);
    document.getElementById("totalBalance").innerText = totalBalance.toFixed(2);
    document.getElementById("totalwithhold").innerText = totalWithhold.toFixed(2); // Use totalWithhold here
});

</script> -->
<script>
document.querySelectorAll("#tableBody tr").forEach(row => {
    row.addEventListener("input", function() {
        // Variables to hold totals
        let dailyPaymentTotal = 0;
        let monthlyPaymentTotal = 0;
        let totalBalance = 0; // Total balance across all rows
        let totalWithhold = 0; // Total withhold percentage across all rows

        // Loop through each row in the table to calculate totals
        document.querySelectorAll("#tableBody tr").forEach(row => {
            const dailyCell = row.querySelector('[data-name="daily"]');
            const weekly = parseFloat(row.querySelector('[data-name="weekly"]').innerText) || 0;
            const funding = parseFloat(row.querySelector('[data-name="funding"]').innerText) || 0;
            const fundingFactor = parseFloat(row.querySelector('[data-name="funding_factor"]').innerText) || 0;
        // Update the daily column if weekly has a value
        if (weekly > 0 && dailyCell) {
                dailyCell.innerText = (weekly / 5).toFixed(2); // Weekly divided by 5
            }

            // Get updated daily value
            const daily = parseFloat(dailyCell ? dailyCell.innerText : 0) || 0;
            // Calculate daily and monthly payments
            dailyPaymentTotal += daily;
            const monthlyPayment = weekly * 4.2; // Assuming a monthly calculation based on daily input

            // Calculate total balance for this row
            const calculatedBalance = (funding * fundingFactor) - monthlyPayment;
            totalBalance += calculatedBalance; // Sum of balances for all rows

            // Set the calculated balance in the row
            const balanceCell = row.querySelector('[data-name="balance"]');
            if (balanceCell) {
                balanceCell.innerText = calculatedBalance.toFixed(2); // Format the balance to 2 decimal places
            }
            // Calculate Payback
            const payback = funding * fundingFactor;

            // Update the Payback column in the row
            const paybackCell = row.querySelector('[data-name="payback"]');
            if (paybackCell) {
                paybackCell.innerText = payback.toFixed(2); // Update Payback in the cell
            }
             // Update the Payback column in the row
 
            
            // Calculate withhold percentage based on averageBankRevenue
            const withhold = averageBankRevenue ? (monthlyPayment / averageBankRevenue) * 100 : 0;

            // Update the withhold column in the row
            const withholdCell = row.querySelector('[data-name="withhold"]');
            if (withholdCell) {
                withholdCell.innerText = withhold.toFixed(2); // Update withhold in the cell
                totalWithhold += withhold; // Accumulate total withhold
            } else {
                console.error("Withhold cell not found in row:", row);
            }
                     // Calculate total days
                     let totalDays = 0;
            if (funding > 0 && fundingFactor > 0 && daily > 0) {
                totalDays = Math.ceil((funding * fundingFactor) / daily);
            }
           // Handle the start date
           const startDateText = row.querySelector('[data-name="funding_date"]').innerText;
            let startDate = new Date(startDateText);
            if (isNaN(startDate)) {
                console.error("Invalid Start Date:", startDateText);
                startDate = null; // Mark as invalid
            }

            // Calculate and update the end date
            if (startDate && totalDays > 0) {
                const endDate = new Date(startDate);
                endDate.setDate(startDate.getDate() + totalDays);
                const endDateCell = row.querySelector('[data-name="end_date"]');
                if (endDateCell) {
                    endDateCell.innerText = endDate.toISOString().split("T")[0]; // Format as YYYY-MM-DD
                }
            } else {
                console.error("Cannot calculate end date due to invalid inputs.");
            }
                        // Update the days name column
            const daysNameCell = row.querySelector('[data-name="days"]');
            if (daysNameCell) {
                if (totalDays > 0) {
                    daysNameCell.innerText = ` ${totalDays}`; // Assign the days name
                } else {
                    daysNameCell.innerText = "Invalid Days"; // Handle invalid cases
                }
            }

            // Debugging: log values to check their correctness
            console.log(`Daily: ${daily}, Funding: ${funding}, Funding Factor: ${fundingFactor}, Monthly Payment: ${monthlyPayment}, Withhold: ${withhold.toFixed(2)}, Calculated Balance: ${calculatedBalance},totalDays: ${totalDays}`);
        });

        // Calculate monthly payment total as daily total * 16 (for display purposes)
        monthlyPaymentTotal = dailyPaymentTotal * 21;

        // Set the calculated totals in the footer
        document.getElementById("dailyPaymentTotal").innerText = dailyPaymentTotal.toFixed(2);
        document.getElementById("monthlyPaymentTotal").innerText = monthlyPaymentTotal.toFixed(2);
        document.getElementById("totalBalance").innerText = totalBalance.toFixed(2); // Total balance
        document.getElementById("totalwithhold").innerText = totalWithhold.toFixed(2); // Total withhold
    });
});
</script>




<script>
    // Function to enable editing on the cell
    function enableEditing(cell) {
        cell.setAttribute('contenteditable', 'true');
        cell.focus(); // Focus the cell to start editing
    }

    // Allow only letters in the Lender column
    document.querySelectorAll('#lenderTable .lender-column').forEach(cell => {
        cell.addEventListener('click', function() {
            enableEditing(cell); // Set contenteditable on click
        });

        cell.addEventListener('input', function() {
            const originalValue = cell.textContent; // Get the current content of the cell
            
            // Use regex to clean the text
            const cleanedText = originalValue.replace(/[^A-Za-z\s]/g, ''); // Allow only letters and spaces
            
            // Update the cell content if it has changed
            if (cleanedText !== originalValue) {
                cell.textContent = cleanedText; // Update the cell content
                placeCaretAtEnd(cell); // Place cursor at the end after modification
            }
        });

        // Disable contenteditable when losing focus
        cell.addEventListener('blur', function() {
            cell.removeAttribute('contenteditable'); // Remove contenteditable on blur
        });
    });

    // Function to place the cursor at the end of the contentEditable element
    function placeCaretAtEnd(el) {
        const range = document.createRange();
        const sel = window.getSelection();
        range.selectNodeContents(el);
        range.collapse(false);
        sel.removeAllRanges();
        sel.addRange(range);
        el.focus();
    }
</script>

<script>
    document.getElementById('addMoreBtnLender').addEventListener('click', function() {
        // Clone the template row
        event.preventDefault();

        var templateRow = document.getElementById('templateRow');
        var newRow = templateRow.cloneNode(true);
        
        // Remove id from cloned row and display it
        newRow.removeAttribute('id');
        newRow.style.display = '';
        
        // Append the new row to the table body
        document.getElementById('tableBody').appendChild(newRow);
    });
</script>
<meta name="csrf-token" content="{{ csrf_token() }}">

<script>
document.getElementById("savedatabtnLender").addEventListener("click", function(event) {
    event.preventDefault();

    // Define the URL for form submission
    const formUrl = "{{ url('lender-matrix/' . $lead_id . '/' . $selectedBankId) }}";

    // Clear existing hidden inputs to avoid duplicate data
    document.querySelectorAll("input[type='hidden']").forEach(input => input.remove());

    // Get all rows in the table body
    const rows = document.querySelectorAll("#tableBody tr:not(#templateRow)");

    rows.forEach((row, index) => {
        // Extract cell content for each column
        const lenderName = row.querySelector('.lender-column[data-name="lender_name"]').innerText;
        const fundingDate = row.querySelector('.date-column[data-name="funding_date"]').innerText;
        const net = row.querySelector('.number-column[data-name="net"]').innerText;
        const funding = row.querySelector('.number-column[data-name="funding"]').innerText;
        const fundingFactor = row.querySelector('.number-column[data-name="funding_factor"]').innerText;
        const payback = row.querySelector('.number-column[data-name="payback"]').innerText;
        const weekly = row.querySelector('.number-column[data-name="weekly"]').innerText;
        const daily = row.querySelector('.number-column[data-name="daily"]').innerText;
        const balance = row.querySelector('.number-column[data-name="balance"]').innerText;
        const days = row.querySelector('.number-column[data-name="days"]').innerText;
        const withhold = row.querySelector('.number-column[data-name="withhold"]').innerText;
        const endDate = row.querySelector('.date-column[data-name="end_date"]').innerText;
        const transferAccounts = row.querySelector('.date-column[data-name="transfer_accounts"]').innerText;
        const notes = row.querySelector('.number-column[data-name="notes"]').innerText;

        // Create hidden inputs for each data field
        const fields = { lender_name: lenderName, funding_date: fundingDate,net: net, funding, funding_factor: fundingFactor, weekly, daily, balance, days, withhold, end_date: endDate, transfer_accounts: transferAccounts, notes };
        
        for (const [name, value] of Object.entries(fields)) {
            const input = document.createElement("input");
            input.type = "hidden";
            input.name = `${name}[${index}]`; // Use array-like naming for multiple rows
            input.value = value;
            document.querySelector("form").appendChild(input);
        }
    });

    // Set the form's action to the specified URL
    const form = document.querySelector("form");
    form.action = formUrl;

    // Add CSRF token to headers (if needed for AJAX) or ensure it's already in the form
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    const csrfInput = document.createElement("input");
    csrfInput.type = "hidden";
    csrfInput.name = "_token";
    csrfInput.value = csrfToken;
    form.appendChild(csrfInput);

    // Submit the form after adding all hidden inputs
    form.submit();
});
</script>






<script>
    const leadId = "{{ $lead_id }}"; // Pass the lead_id to a JavaScript variable
</script>
<script>
    // Add an event listener to the Save Data button
    document.querySelector('.saveDataBtn').addEventListener('click', function() {
        // Loop through each row to get values from contenteditable cells
        event.preventDefault();
        const bankName = document.getElementById('bank_name').value.trim();

// Check if the bank name is empty
if (!bankName) {
    toastr.error("Bank name should not be null.");
    return; // Prevent form submission if bank name is empty
}
        const months = @json($months);
        
        months.forEach(month => {
            document.getElementById(`deposit1[${month}]`).value = document.querySelector(`.deposit1[data-name="deposit1[${month}]"]`).innerText;
            document.getElementById(`adjustment[${month}]`).value = document.querySelector(`.adjustment[data-name="adjustment[${month}]"]`).innerText;
            document.getElementById(`revenue[${month}]`).value = document.querySelector(`.revenue[data-name="revenue[${month}]"]`).innerText;
            document.getElementById(`adb[${month}]`).value = document.querySelector(`.adb[data-name="adb[${month}]"]`).innerText;
            document.getElementById(`deposit2[${month}]`).value = document.querySelector(`.deposit2[data-name="deposit2[${month}]"]`).innerText;
            document.getElementById(`nsfs[${month}]`).value = document.querySelector(`.nsfs[data-name="nsfs[${month}]"]`).innerText;
            document.getElementById(`negatives[${month}]`).value = document.querySelector(`.negatives[data-name="negatives[${month}]"]`).innerText;
            document.getElementById(`ending-balance[${month}]`).value = document.querySelector(`.ending-balance[data-name="ending-balance[${month}]"]`).innerText;

        });
  // Get the value of the bank_name input field
//   const bank_name = document.getElementById('bank_name').value;

    // Submit the form
    document.querySelector('form').submit();
        // Submit the form
    });
</script>

<script>
    const records = @json($fcs_data);
    console.log(records);
    //alert(records);
</script>

<script>
    let tabCount = 1; // Start counting from 1 since you already have one tab.
    function initializeTabs() {
    const tabList = document.getElementById('tabList');
    const tabContent = document.getElementById('tabContent');

    if (records && records.length > 0) {
        let firstTabAdded = false; // Track if the first tab has been activated

        // Loop through the entire records array, starting from index 1 to skip the first bank
        records.forEach((bank, index) => {
            if (index === 0) return; // Skip the first bank (index 0)

            // Check if the current bank has records
            if (bank.records && bank.records.length > 0) {
                const tabId = bank.records[0].bank_id; // Get tab ID from the first record's bank_id
                const bankName = bank.bank_name || ""; // Get bank name or empty string
                const newTabContentId = `content${tabId}`;

                // Check if the tab already exists to prevent duplication
                if (!document.getElementById(newTabContentId)) {
                    // Create new tab and content
                    const newTab = createTab(tabId, newTabContentId, bankName);
                    tabList.appendChild(newTab);

                    const newTabContent = createTabContent(tabId, newTabContentId, bankName);
                    tabContent.appendChild(newTabContent);

                    // Attach event listeners to the newly added table cells
                    attachEditableListeners(tabId);

                    // Attach click event listener to the new save button
                    const saveButton = document.getElementById(`saveButton_${tabId}`);
                    if (saveButton) {
                        saveButton.addEventListener('click', function () {
                            saveTabData(tabId);
                        });
                    }

                    // Activate the first tab and its content, but only once
                    if (!firstTabAdded) {
                        newTab.querySelector('a').classList.add(); // Make the first dynamic tab active
                        firstTabAdded = true; // Mark that the first dynamic tab has been activated
                    }
                    
                }
            }
        });
    }
}


    document.addEventListener('DOMContentLoaded', function () {
         // Function to check if a tab has data and create tabs automatically on page load
  
        // Function to add a new tab with table
        document.getElementById('btn_add_tab').addEventListener('click', function (event) {
            event.preventDefault(); // Prevent default behavior
           // Check if the tab already exists
     
           let tabAlreadyExists = true;

// Continue incrementing tabCount until a new, non-existing tab is found
while (tabAlreadyExists) {
    const newTabContentId = `content${tabCount + 1}`; // Increment tab count to check the next tab
    const existingTab = document.getElementById(newTabContentId); // Check if the tab already exists
    
    // If the tab doesn't exist, stop the loop and allow creating a new tab
    if (!existingTab) {
        tabAlreadyExists = false;
        tabCount++; // Increment tabCount for the new tab
    } else {
        tabCount++; // Increment tabCount to skip the already existing tab
    }
}
            // Create new tab and content IDs
            const newTabContentId = `content${tabCount}`;
            const bankRecord = records.find(bank => bank.records.some(record => record.bank_id === tabCount));

// If a matching bankRecord is found, get the respective bank name
if (bankRecord) {
    const bankName = bankRecord.bank_name;
    console.log(`Bank Name for Tab ${tabCount}: ${bankName}`);
} else {
    console.log(`Invalid records format or missing records for tab number: ${tabCount}`);
}
            const bankName = bankRecord ? bankRecord.bank_name : ""; // Get bank name or default to empty string  const bankRecord = records[1]?.records.find(record => record.bank_id === tabCount);
            //console.log(bankRecord);
            // Create new tab list item
            const newTab = createTab(tabCount, newTabContentId,bankName);
            document.getElementById('tabList').appendChild(newTab);
   // Use the bank name from records for the first record or default
   
 
  // alert(bankName);
            // Create new tab content with the table
            const newTabContent = createTabContent(tabCount, newTabContentId,bankName);
            document.getElementById('tabContent').appendChild(newTabContent);


            // Attach event listeners to the newly added table cells
            attachEditableListeners(tabCount);

            // Attach click event listener to the new save button
            const saveButton = document.getElementById(`saveButton_${tabCount}`);
            saveButton.addEventListener('click', function () {
                saveTabData(tabCount);
            });
            
        });

        // Attach listeners to the first tab
        attachEditableListeners(tabCount);
        
    });
    // Function to check if the newly added table contains data


    function createTab(tabNumber, newTabContentId,bankName) {
        const newTab = document.createElement('li');
        newTab.classList.add('nav-item');
        newTab.innerHTML = `
            <a class="nav-link" data-bs-toggle="tab" href="#${newTabContentId}" role="tab" aria-controls="${newTabContentId}">
                <span class="hidden-sm-up"><i class="ion-document"></i></span>
                <span class="hidden-xs-down">Bank ${tabNumber}(${bankName})</span>
            </a>
        `;
        return newTab;
    }

    function createTabContent(tabNumber, newTabContentId,bankName) {
        const newTabContent = document.createElement('div');
        newTabContent.classList.add('tab-pane', 'fade');
        newTabContent.id = newTabContentId;
        newTabContent.role = 'tabpanel';
        newTabContent.innerHTML = createTableContent(tabNumber,bankName);
        return newTabContent;
    }

    // Initialize tabs with data on page load
    initializeTabs();
    
    // Function to create table content for each tab
    function createTableContent(tabNumber,bankName) {
        const lead_id = document.getElementById('lead_id').value;// Blade variable embedded correctly
        //console.log(lead_id);
        return `
                            <form method="post" action="">
                        @csrf
            <div class="col-md-3">
                <div class="form-group">

                        <label class="form-label">Bank Name</label>
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" name="bank_name" value="${bankName}"id="bank_name_${tabNumber}">
                         
                        </div>
                 
                </div>
            </div>
            <div class="table-responsive">
                <table id="editable-table${tabNumber}"class="editTable mainTable table editable-table table-bordered mb-0">
                    <thead>
                        <tr>
                            <th>Month</th>
                            <th class="deposit1">Deposits</th>
                            <th class="adjustment">Adjustment</th>
                            <th>Revenue</th>
                            <th class="adb">ADB</th>
                            <th class="deposit2">No of Deposits</th>
                            <th class="nsfs">NSFs</th>
                            <th class="negatives">Negatives</th>
                            <th class="ending-balance">Ending Balance</th>
                        </tr>
                    </thead>
                    <tbody id="table-body-tab${tabNumber}">
                        ${generateTableRows(tabNumber)}
                    </tbody>
                    <tfoot>
                        <tr>
                            <th><strong>Totals</strong></th>
                            <th id="totalDeposits1_${tabNumber}">0.00</th>
                            <th id="totalAdjustment_${tabNumber}">0.00</th>
                            <th id="totalRevenue_${tabNumber}">0.00</th>
                            <th id="totalADB_${tabNumber}">0.00</th>
                            <th id="totalDeposits2_${tabNumber}">0.00</th>
                            <th id="totalNSFs_${tabNumber}">0.00</th>
                            <th id="totalNegatives_${tabNumber}">0.00</th>
                            <th id="totalEndingBalance_${tabNumber}">0.00</th>
                        </tr>
                        <tr>
                            <th><strong>Averages</strong></th>
                            <th id="avgDeposits1_${tabNumber}">0.00</th>
                            <th id="avgAdjustment_${tabNumber}">0.00</th>
                            <th id="avgRevenue_${tabNumber}">0.00</th>
                            <th id="avgADB_${tabNumber}">0.00</th>
                            <th id="avgDeposits2_${tabNumber}">0.00</th>
                            <th id="avgNSFs_${tabNumber}">0.00</th>
                            <th id="avgNegatives_${tabNumber}">0.00</th>
                            <th id="avgEndingBalance_${tabNumber}">0.00</th>
                        </tr>
                    </tfoot>
                </table>
                <br>
<a target="_blank" href="/eligible-lender/${lead_id}/${tabNumber}" class="btn btn-primary" type="button" style="float:right;margin-left:10px;">Find Eligible Lender</a>


                <button id="saveButton_${tabNumber}" type="button" class="saveDynamic btn btn-primary" style="float:right;">Save Data</button>
            </div>
        `;
    }

    function generateTableRows(tabNumber) {
    const months = [
        'January', 'February', 'March', 'April', 'May', 'June', 
        'July', 'August', 'September', 'October', 'November', 'December'
    ];

    // Log records to check its structure
    console.log('Records:', records);
    console.log('Type of records:', typeof records);

    // Validate that records is an array
    if (!Array.isArray(records)) {
        console.error('Invalid records format: records should be an array.', records);
        return months.map(month => generateEmptyRow(month, tabNumber)).join('');
    }

    // Find the bank object that contains records with the matching bank_id
    const bankObj = records.find(bank => 
        Array.isArray(bank.records) && bank.records.some(record => record.bank_id === tabNumber)
    );

    if (!bankObj) {
        console.error(`Invalid records format or missing records for tab number: ${tabNumber}`, records);
        return months.map(month => generateEmptyRow(month, tabNumber)).join('');
    }

    // Extract and filter records for the specific bank_id
    const recordsArray = bankObj.records.filter(record => record.bank_id === tabNumber);

    console.log(`Records Array for Tab ${tabNumber}:`, recordsArray);

    // Create a mapping of records by month name for easy access
    const recordsMap = {};
    recordsArray.forEach(record => {
        if (!record.month) {
            console.warn('Skipping record due to null or undefined month:', record);
            return; // Skip records without a valid month
        }

        // Validate the month name
        if (!months.includes(record.month)) {
            console.error(`Invalid month name: ${record.month} in record:`, record);
            return; // Skip records with invalid month names
        }

        // Map the record by its month
        recordsMap[record.month] = record;
    });

    // Generate table rows for all months, using existing data or empty values
    return months.map(month => {
        const record = recordsMap[month] || {}; // Get the record for the current month or an empty object

        // Log the record data for debugging
        console.log(`Tab: ${tabNumber}, Month: ${month}, Record:`, record);

        return `
            <tr>
                <td>${month}</td>

                <td class="deposit1" contenteditable="true" data-month="${month}">
                    ${record.deposits || ''}
                </td>
                <input type="hidden" name="deposit1[${tabNumber}][${month}]" id="deposit1_${tabNumber}_${month}" value="${record.deposits || ''}" />

                <td class="adjustment" contenteditable="true" data-month="${month}">
                    ${record.adjustment || ''}
                </td>
                <input type="hidden" name="adjustment[${tabNumber}][${month}]" id="adjustment_${tabNumber}_${month}" value="${record.adjustment || ''}" />

                <td class="revenue" data-month="${month}">
                    ${record.revenue || ''}
                </td>
                <input type="hidden" name="revenue[${tabNumber}][${month}]" id="revenue_${tabNumber}_${month}" value="${record.revenue || ''}" />

                <td class="adb" contenteditable="true" data-month="${month}">
                    ${record.adb || ''}
                </td>
                <input type="hidden" name="adb[${tabNumber}][${month}]" id="adb_${tabNumber}_${month}" value="${record.adb || ''}" />

                <td class="deposit2" contenteditable="true" data-month="${month}">
                    ${record.deposit2 || ''}
                </td>
                <input type="hidden" name="deposit2[${tabNumber}][${month}]" id="deposit2_${tabNumber}_${month}" value="${record.deposit2 || ''}" />

                <td class="nsfs" contenteditable="true" data-month="${month}">
                    ${record.nsfs || ''}
                </td>
                <input type="hidden" name="nsfs[${tabNumber}][${month}]" id="nsfs_${tabNumber}_${month}" value="${record.nsfs || ''}" />

                <td class="negatives" contenteditable="true" data-month="${month}">
                    ${record.negatives || ''}
                </td>
                <input type="hidden" name="negatives[${tabNumber}][${month}]" id="negatives_${tabNumber}_${month}" value="${record.negatives || ''}" />

                <td class="ending-balance" contenteditable="true" data-month="${month}">
                    ${record.ending_balance || ''}
                </td>
                <input type="hidden" name="ending_balance[${tabNumber}][${month}]" id="ending_balance_${tabNumber}_${month}" value="${record.ending_balance || ''}" />
            </tr>
        `;
    }).join('');
}

// Example implementation of generateEmptyRow (you should adjust this as per your requirements)
function generateEmptyRow(month, tabNumber) {
    return `
        <tr>
            <td>${month}</td>
            <td class="deposit1" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="deposit1[${tabNumber}][${month}]" id="deposit1_${tabNumber}_${month}" value="" />

            <td class="adjustment" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="adjustment[${tabNumber}][${month}]" id="adjustment_${tabNumber}_${month}" value="" />

            <td class="revenue" data-month="${month}"></td>
            <input type="hidden" name="revenue[${tabNumber}][${month}]" id="revenue_${tabNumber}_${month}" value="" />

            <td class="adb" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="adb[${tabNumber}][${month}]" id="adb_${tabNumber}_${month}" value="" />

            <td class="deposit2" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="deposit2[${tabNumber}][${month}]" id="deposit2_${tabNumber}_${month}" value="" />

            <td class="nsfs" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="nsfs[${tabNumber}][${month}]" id="nsfs_${tabNumber}_${month}" value="" />

            <td class="negatives" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="negatives[${tabNumber}][${month}]" id="negatives_${tabNumber}_${month}" value="" />

            <td class="ending-balance" contenteditable="true" data-month="${month}"></td>
            <input type="hidden" name="ending_balance[${tabNumber}][${month}]" id="ending_balance_${tabNumber}_${month}" value="" />
        </tr>
    `;
}
// Helper function to generate an empty row


    function attachEditableListeners(tabNumber) {
        const tabContent = document.getElementById(`content${tabNumber}`);
        const editableCells = tabContent.querySelectorAll('[contenteditable="true"]');
        
        editableCells.forEach(cell => {
            cell.addEventListener('input', function () {
                const originalValue = cell.textContent;

// Allow only numbers and decimal points
const numericValue = originalValue.replace(/[^0-9.-]/g, ''); 

// If the modified value is different from the original, update the cell content
if (numericValue !== originalValue) {
    cell.textContent = numericValue;

    // Optionally, provide feedback by highlighting the invalid input
    cell.style.backgroundColor = ''; // Red background for invalid input
} else {
    cell.style.backgroundColor = ''; // Reset background color if input is valid
}
                calculateTotalsAndAverages(tabNumber);
            });
        });
    }

    function calculateTotalsAndAverages(tabNumber) {
    const tabContent = document.getElementById(`content${tabNumber}`);
    const rows = tabContent.querySelectorAll('tbody tr');

    let totalDeposits1 = 0, totalAdjustment = 0, totalRevenue = 0, totalADB = 0;
    let totalDeposits2 = 0, totalNSFs = 0, totalNegatives = 0, totalEndingBalance = 0;

    let validDeposits1Count = 0, validAdjustmentCount = 0, validRevenueCount = 0, validADBCount = 0;
    let validDeposits2Count = 0, validNSFsCount = 0, validNegativesCount = 0, validEndingBalanceCount = 0;

    // Iterate over each row and sum up the values
    rows.forEach(row => {
        const deposit1 = parseFloat(row.querySelector('.deposit1').textContent) || 0;
        const adjustment = parseFloat(row.querySelector('.adjustment').textContent) || 0;
        const adb = parseFloat(row.querySelector('.adb').textContent) || 0;
        const deposit2 = parseFloat(row.querySelector('.deposit2').textContent) || 0;
        const nsfs = parseFloat(row.querySelector('.nsfs').textContent) || 0;
        const negatives = parseFloat(row.querySelector('.negatives').textContent) || 0;
        const endingBalance = parseFloat(row.querySelector('.ending-balance').textContent) || 0;
        
        // Calculate revenue (if necessary)
        const revenue = deposit1 - adjustment;
        row.querySelector('.revenue').textContent = revenue.toFixed(2);

        // Only count non-zero values for averaging purposes
        if (deposit1 !== 0) validDeposits1Count++;
        if (adjustment !== 0) validAdjustmentCount++;
        if (revenue !== 0) validRevenueCount++;
        if (adb !== 0) validADBCount++;
        if (deposit2 !== 0) validDeposits2Count++;
        if (nsfs !== 0) validNSFsCount++;
        if (negatives !== 0) validNegativesCount++;
        if (endingBalance !== 0) validEndingBalanceCount++;

        totalDeposits1 += deposit1;
        totalAdjustment += adjustment;
        totalRevenue += revenue;
        totalADB += adb;
        totalDeposits2 += deposit2;
        totalNSFs += nsfs;
        totalNegatives += negatives;
        totalEndingBalance += endingBalance;
    });

    // Update totals and averages using valid counts
    updateTotals(tabNumber, totalDeposits1, totalAdjustment, totalRevenue, totalADB, totalDeposits2, totalNSFs, totalNegatives, totalEndingBalance, {
        deposits1Count: validDeposits1Count,
        adjustmentCount: validAdjustmentCount,
        revenueCount: validRevenueCount,
        adbCount: validADBCount,
        deposits2Count: validDeposits2Count,
        nsfsCount: validNSFsCount,
        negativesCount: validNegativesCount,
        endingBalanceCount: validEndingBalanceCount
    });
}

function updateTotals(tabNumber, totalDeposits1, totalAdjustment, totalRevenue, totalADB, totalDeposits2, totalNSFs, totalNegatives, totalEndingBalance, validCounts) {
    // Update total fields
    document.getElementById(`totalDeposits1_${tabNumber}`).textContent = totalDeposits1.toFixed(2);
    document.getElementById(`totalAdjustment_${tabNumber}`).textContent = totalAdjustment.toFixed(2);
    document.getElementById(`totalRevenue_${tabNumber}`).textContent = totalRevenue.toFixed(2);
    document.getElementById(`totalADB_${tabNumber}`).textContent = totalADB.toFixed(2);
    document.getElementById(`totalDeposits2_${tabNumber}`).textContent = totalDeposits2.toFixed(2);
    document.getElementById(`totalNSFs_${tabNumber}`).textContent = totalNSFs.toFixed(2);
    document.getElementById(`totalNegatives_${tabNumber}`).textContent = totalNegatives.toFixed(2);
    document.getElementById(`totalEndingBalance_${tabNumber}`).textContent = totalEndingBalance.toFixed(2);

    // Update averages using valid row counts (excluding rows with 0.00 values)
    document.getElementById(`avgDeposits1_${tabNumber}`).textContent = (totalDeposits1 / (validCounts.deposits1Count || 1)).toFixed(2);
    document.getElementById(`avgAdjustment_${tabNumber}`).textContent = (totalAdjustment / (validCounts.adjustmentCount || 1)).toFixed(2);
    document.getElementById(`avgRevenue_${tabNumber}`).textContent = (totalRevenue / (validCounts.revenueCount || 1)).toFixed(2);
    document.getElementById(`avgADB_${tabNumber}`).textContent = (totalADB / (validCounts.adbCount || 1)).toFixed(2);
    document.getElementById(`avgDeposits2_${tabNumber}`).textContent = (totalDeposits2 / (validCounts.deposits2Count || 1)).toFixed(2);
    document.getElementById(`avgNSFs_${tabNumber}`).textContent = (totalNSFs / (validCounts.nsfsCount || 1)).toFixed(2);
    document.getElementById(`avgNegatives_${tabNumber}`).textContent = (totalNegatives / (validCounts.negativesCount || 1)).toFixed(2);
    document.getElementById(`avgEndingBalance_${tabNumber}`).textContent = (totalEndingBalance / (validCounts.endingBalanceCount || 1)).toFixed(2);
}



    function saveTabData(tabNumber) {
    const tabContent = document.getElementById(`content${tabNumber}`);
    const data = {};
    const csrf_token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    // Assuming bank name is in an input field with ID 'bank_name'
    const bankName = document.querySelector(`#bank_name_${tabNumber}`).value;
    // Check if the bank name is empty
    if (!bankName) {
        toastr.error("Bank name should not be null.");
        return; // Prevent form submission if bank name is empty
    }
    // Collect data from the editable cells
    const rows = tabContent.querySelectorAll('tbody tr');
    rows.forEach(row => {
        const month = row.querySelector('td').textContent;

// Add the bank name to the data object
      // Assign bank_id starting from 2
      const bankId = tabNumber + 1; // If tabNumber starts at 1

// Add the bank_id and bank_name to the data object
data['bank_name'] = bankName;
data['bank_id'] = bankId;
        data[month] = {
            deposit1: row.querySelector('.deposit1').textContent,
            adjustment: row.querySelector('.adjustment').textContent,
            adb: row.querySelector('.adb').textContent,
            deposit2: row.querySelector('.deposit2').textContent,
            nsfs: row.querySelector('.nsfs').textContent,
            negatives: row.querySelector('.negatives').textContent,
            ending_balance: row.querySelector('.ending-balance').textContent
        };
    });
    const baseUrl = "{{url('leads/fcs-data')}}"; // Define the base URL
    fetch(`${baseUrl}/${leadId}`, { // Replace with your actual URL
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrf_token, // Include CSRF token here
            // Include any other headers as needed, e.g., Authorization
        },
        body: JSON.stringify({ tabNumber: tabNumber, data: data }) // Sending tab number and data
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok: ' + response.statusText);
        }
        // Check if response is JSON
        const contentType = response.headers.get("content-type");
        if (!contentType || !contentType.includes("application/json")) {
            throw new TypeError("Response is not JSON");
        }
        return response.json();
    })
    .then(responseData => {
        window.location.reload(1);
        // window.location.href = '/leads/fcs-data?bank_name=' + encodeURIComponent(bankName);
        toastr.success('Data saved successfully:', responseData);
        
        // Optionally update the UI to reflect the saved state
    })
    .catch(error => {
        console.error('Error saving data:', error);
    });
}

</script>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const table = document.getElementById("#editTable1"); 
    const tbody = table.querySelector("tbody");
    const tfoot = table.querySelector("tfoot");

    function calculateTotalsAndAverages() {
        let totals = {
            deposits1: 0,
            adjustment: 0,
            revenue: 0,
            adb: 0,
            deposits2: 0,
            nsfs: 0,
            negatives: 0,
            endingBalance: 0
        };

        let count = 0; // Count of rows with at least one numeric entry

        tbody.querySelectorAll("tr").forEach(row => {
            let deposits1 = parseFloat(row.querySelector(".deposit1").textContent) || 0;
            let adjustment = parseFloat(row.querySelector(".adjustment").textContent) || 0;
            let adb = parseFloat(row.querySelector(".adb").textContent) || 0;
            let deposits2 = parseFloat(row.querySelector(".deposit2").textContent) || 0;
            let nsfs = parseFloat(row.querySelector(".nsfs").textContent) || 0;
            let negatives = parseFloat(row.querySelector(".negatives").textContent) || 0;
            let endingBalance = parseFloat(row.querySelector(".ending-balance").textContent) || 0;

            // Calculate revenue as deposits1 - adjustment
            let revenue = deposits1 - adjustment;
            row.querySelector(".revenue").textContent = revenue.toFixed(2);

            // Accumulate totals
            totals.deposits1 += deposits1;
            totals.adjustment += adjustment;
            totals.revenue += revenue;
            totals.adb += adb;
            totals.deposits2 += deposits2;
            totals.nsfs += nsfs;
            totals.negatives += negatives;
            totals.endingBalance += endingBalance;

            // Check if the row has at least one numeric entry
            if (deposits1 || adjustment || adb || deposits2 || nsfs || negatives || endingBalance) {
                count++;
            }
        });

        // Update totals
        document.getElementById("totalDeposits1").textContent = totals.deposits1.toFixed(2);
        document.getElementById("totalAdjustment").textContent = totals.adjustment.toFixed(2);
        document.getElementById("totalRevenue").textContent = totals.revenue.toFixed(2);
        document.getElementById("totalADB").textContent = totals.adb.toFixed(2);
        document.getElementById("totalDeposits2").textContent = totals.deposits2.toFixed(2);
        document.getElementById("totalNSFs").textContent = totals.nsfs.toFixed(2);
        document.getElementById("totalNegatives").textContent = totals.negatives.toFixed(2);
        document.getElementById("totalEndingBalance").textContent = totals.endingBalance.toFixed(2);

        // Update averages
        if (count > 0) {
            document.getElementById("avgDeposits1").textContent = (totals.deposits1 / count).toFixed(2);
            document.getElementById("avgAdjustment").textContent = (totals.adjustment / count).toFixed(2);
            document.getElementById("avgRevenue").textContent = (totals.revenue / count).toFixed(2);
            document.getElementById("avgADB").textContent = (totals.adb / count).toFixed(2);
            document.getElementById("avgDeposits2").textContent = (totals.deposits2 / count).toFixed(2);
            document.getElementById("avgNSFs").textContent = (totals.nsfs / count).toFixed(2);
            document.getElementById("avgNegatives").textContent = (totals.negatives / count).toFixed(2);
            document.getElementById("avgEndingBalance").textContent = (totals.endingBalance / count).toFixed(2);
        } else {
            // If count is 0, set averages to 0
            document.getElementById("avgDeposits1").textContent = "0.00";
            document.getElementById("avgAdjustment").textContent = "0.00";
            document.getElementById("avgRevenue").textContent = "0.00";
            document.getElementById("avgADB").textContent = "0.00";
            document.getElementById("avgDeposits2").textContent = "0.00";
            document.getElementById("avgNSFs").textContent = "0.00";
            document.getElementById("avgNegatives").textContent = "0.00";
            document.getElementById("avgEndingBalance").textContent = "0.00";
        }
    }

    // Attach event listeners to all editable cells
    const editableCells = tbody.querySelectorAll("td[contenteditable='true']");
    editableCells.forEach(cell => {
        cell.addEventListener("input", calculateTotalsAndAverages);
    });

    // Initial calculation on page load
    calculateTotalsAndAverages();
});
</script>
<script>
document.querySelectorAll('td[contenteditable="true"]').forEach(function(td) {
    td.addEventListener('input', function(e) {
        // Get the current content
        let content = e.target.textContent;

        // Remove any characters that are not digits or decimal points
        const cleanedContent = content.replace(/[^0-9.-]/g, '');

        // Replace the content with the cleaned version
        if (content !== cleanedContent) {
            e.target.textContent = cleanedContent;
        }

        // Set caret position to the end after cleaning input
        setEndOfContenteditable(e.target);
    });
});

// Function to set caret at the end of contenteditable element after cleaning
function setEndOfContenteditable(contentEditableElement) {
    let range, selection;
    if (document.createRange) { // All browsers, except IE < 9
        range = document.createRange(); // Create a range (a range is like a selection but invisible)
        range.selectNodeContents(contentEditableElement); // Select the entire contents of the element with the range
        range.collapse(false); // Collapse the range to the end point (false means collapse to end rather than the start)
        selection = window.getSelection(); // Get the selection object (allows you to change selection)
        selection.removeAllRanges(); // Remove any selections already made
        selection.addRange(range); // Make the range you have just created the visible selection
    }
}
</script>
@endsection
