@php
    use Carbon\Carbon;
@endphp
<div class="content-wrapper">
    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row">
            <div class="col">
                <div class="card shadow">
                    <div class="card-header text-uppercase custom-header bg-primary text-bg-info fw-bold">
                        <div class="col-6">
                            <i class="menu-icon ti ti-users-group"></i>

                            @foreach ($getMember as $member)
                                @if ($member->id == $memberId)
                                    {{ $member->firstName }} - {{ $member->nicNumber }} -
                                    {{ $member->oldAccountNumber }} - Savings
                                @endif
                            @endforeach
                        </div>
                        <div class="d-none d-lg-flex justify-content-end align-items-center gap-2">
    @if ($userType == 'superAdmin')
        <button class="btn btn-success btn-sm" data-bs-toggle="modal"
                data-bs-target="#transferMemberSavingsAmountModal">
            <i class="menu-icon ti ti-square-rounded-plus"></i> Member Transfer
        </button>
        <button class="btn btn-success btn-sm" data-bs-toggle="modal"
                data-bs-target="#transferSavingsAmountModal">
            <i class="menu-icon ti ti-square-rounded-plus"></i> Transfer
        </button>
        <button class="btn btn-success btn-sm" data-bs-toggle="modal"
                data-bs-target="#importSavingHistoryModal">
            <i class="menu-icon ti ti-square-rounded-plus"></i> Import
        </button>
    @else
        @php
            $userRolesArray = $getUserRole->pluck('roleName')->toArray();
            $usersDataPer = json_decode($permissions, true);
        @endphp

        @if (in_array($userType, $userRolesArray))
            @if (in_array('ImportSavingHistory', $usersDataPer))
                <button class="btn btn-success btn-sm" data-bs-toggle="modal"
                        data-bs-target="#importSavingHistoryModal">
                    <i class="menu-icon ti ti-square-rounded-plus"></i> Import Saving history
                </button>
            @endif

            @if (in_array('transferSavings', $usersDataPer))
                <button class="btn btn-success btn-sm" data-bs-toggle="modal"
                        data-bs-target="#transferSavingsAmountModal">
                    <i class="menu-icon ti ti-square-rounded-plus"></i> Transfer
                </button>
            @endif
        @endif
    @endif

    {{-- Saving ID badge --}}
    <div class="badge bg-light text-dark shadow-sm px-3 py-2 rounded-pill cursor-pointer" 
         onclick="copySavingId('{{ $getmemuniId->savingsId }}')"
         title="Click to copy Saving ID">
        Saving ID: <span class="fw-bold">#{{ $getmemuniId->savingsId }}</span>
    </div>
</div>

                    </div>
                     <div class="card-body">
                        <div class="row mt-3">
                            <!-- Filters Section -->
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <label class="form-label">From Date</label>
                                    <input type="date" class="form-control" id="filterFromDate">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">To Date</label>
                                    <input type="date" class="form-control" id="filterToDate">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Min Amount</label>
                                    <input type="number" class="form-control" id="filterMinAmount" step="0.01">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Max Amount</label>
                                    <input type="number" class="form-control" id="filterMaxAmount" step="0.01">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Type</label>
                                    <select class="form-select" id="filterType">
                                        <option value="">All</option>
                                        <option value="Credit">Credit</option>
                                        <option value="Debit">Debit</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-12">
                                    <button class="btn btn-primary btn-sm" id="applyFilters">Apply Filters</button>
                                    <button class="btn btn-secondary btn-sm ms-2" id="resetFilters">Reset Filters</button>
                                </div>
                            </div>
                            
                            <div class="">
                                <table class="table table-sm table-bordered" id="savingHistoryTable">
                                    <thead class="sticky-top bg-white">
                                        <tr>
                                            <th>#</th>
                                            <th>Transection Id</th>
                                            <th>Date</th>
                                            <th>User</th>
                                            <th>Description</th>
                                            <th>Type</th>
                                            <th>Amount</th>
                                            <th>Balance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php
                                            $count = 1;
                                        @endphp
                                        @foreach ($getSavingHistory as $history)
                                            <tr data-date="{{ $history->created_at }}" data-amount="{{ $history->amount }}" data-type="{{ $history->type }}">
                                                <td>{{ $count++ }}</td>
                                                <td>
                                                    {{ $history->randomId }}
                                                </td>
                                                <td>
                                                    @php
                                                        $date = Carbon::createFromFormat(
                                                            'Y-m-d H:i:s',
                                                            $history->created_at,
                                                        );
                                                        $formattedDate = $date->format('d-m-Y h:i:s A');
                                                    @endphp
                                                    {{ $formattedDate }}
                                                </td>
                                                <td>
                                                    @foreach ($getUser as $user)
                                                        @if ($user->id == $history->userId)
                                                            {{ $user->name }}
                                                        @endif
                                                    @endforeach
                                                </td>
                                                <td>
                                                    {{ $history->description }}
                                                </td>
                                                <td>
                                                    @if ($history->type == 'Credit')
                                                        <span class="badge bg-success">Credit</span>
                                                    @else
                                                        <span class="badge bg-danger">Debit</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    {{ number_format($history->amount, 2) }}
                                                </td>
                                                <td>
                                                    {{ number_format($history->balance, 2) }}
                                                </td>
                                            </tr>
                                        @endforeach

                                        @foreach ($geInterData as $history)
                                            <tr data-date="{{ $history->created_at }}" data-amount="{{ $history->amount }}" data-type="{{ $history->type }}">
                                                <td>{{ $count++ }}</td>
                                                <td>
                                                    {{ $history->randomId }}
                                                </td>
                                                <td>
                                                    @php
                                                        $date = Carbon::createFromFormat(
                                                            'Y-m-d H:i:s',
                                                            $history->created_at,
                                                        );
                                                        $formattedDate = $date->format('d-m-Y h:i:s A');
                                                    @endphp
                                                    {{ $formattedDate }}
                                                </td>
                                                <td>
                                                    @foreach ($getUser as $user)
                                                        @if ($user->id == $history->userId)
                                                            {{ $user->name }}
                                                        @endif
                                                    @endforeach
                                                </td>
                                                <td>
                                                    {{ $history->description }}
                                                </td>
                                                <td>
                                                    @if ($history->type == 'Credit')
                                                        <span class="badge bg-success">Credit</span>
                                                    @else
                                                        <span class="badge bg-danger">Debit</span>
                                                    @endif
                                                </td>
                                                <td>
                                                    {{ number_format($history->amount, 2) }}
                                                </td>
                                                <td>
                                                    {{ number_format($history->balance, 2) }}
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Transfer Saving History Modal -->
<div class="modal fade" id="transferSavingsAmountModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-simple">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="btn-close btn-pinned" data-bs-dismiss="modal"
                    aria-label="Close"></button>
                <div class="text-center mb-4">
                    <h4 class="mb-2">Transfer Saving Amount</h4>
                    <p>Transfer Saving Amount</p>
                </div>

                <input type="hidden" id="txtMemberUniqueId" value="{{ $memberUniqueId }}" />
                <div class="col-12 mt-3">
                    <div class="form-group">
                        <label>Select Account</label>
                        <select class="selectize" id="txtSelectAcccount">
                            <option value="">---Select---</option>
                            <option value="Death">Death</option>
                            <option value="Other Income">Other Income</option>
                        </select>
                    </div>
                </div>

                <div class="col-12 mt-3">
                    <div class="form-group">
                        <label>Amount</label>
                        <input type="text" id="txtAmount" class="form-control" placeholder="Enter Amount" />
                    </div>
                </div>

                <div class="col-12 mt-3">
                    <div class="form-group">
                        <label>Remarks</label>
                        <textarea class="form-control" id="txtRemarks"></textarea>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="col-12 text-center demo-vertical-spacing">
                    <button class="btn btn-primary me-4" id="btnTransferAccount">Transfer</button>
                    <button type="reset" class="btn btn-label-secondary" data-bs-dismiss="modal"
                        aria-label="Close">
                        Discard
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<!--/ Transfer Saving History Modal -->

<!-- Transfer Member Saving History Modal -->
<div class="modal fade" id="transferMemberSavingsAmountModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-simple">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="btn-close btn-pinned" data-bs-dismiss="modal"
                    aria-label="Close"></button>
                <div class="text-center mb-4">
                    <h4 class="mb-2">Transfer Member Saving Amount</h4>
                    <p>Transfer Member Saving Amount</p>
                </div>

                <div class="col-12 mt-3">
                    <div class="form-group">
                        <label>Select Member</label>
                        <select class="selectize" id="txtSelectMember">
                            <option value="">---Select---</option>
                          @foreach ($getAllMemberData as $mem)
                          @if ($memberId != $mem->id)
                          <option value="{{ $mem->id }}">{{ $mem->firstName }} {{ $mem->lastName }} / {{ $mem->oldAccountNumber }} </option>
                          @endif
                          @endforeach
                        </select>
                    </div>
                </div>

                <div class="col-12 mt-3">
                    <div class="form-group">
                        <label>Amount</label>
                        <input type="text" id="txtMemberAmount" class="form-control" placeholder="Enter Amount" />
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="col-12 text-center demo-vertical-spacing">
                    <button class="btn btn-primary me-4" id="btnTransferMemberAccount">Transfer</button>
                    <button type="reset" class="btn btn-label-secondary" data-bs-dismiss="modal"
                        aria-label="Close">
                        Discard
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<!--/ Transfer Member Saving History Modal -->

<!-- Import Saving History Modal -->
<div class="modal fade" id="importSavingHistoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-simple modal-lg">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="btn-close btn-pinned" data-bs-dismiss="modal"></button>
                <div class="text-center mb-4">
                    <h4 class="mb-2">Import Saving History</h4>
                    <p>Savings import function</p>
                </div>
                
                <!-- Member & Saving ID Inputs -->
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label class="form-label">Member ID</label>
                        <input type="text" id="member_id" class="form-control">
                        <div id="member_id_status" class="form-text"></div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Saving ID</label>
                        <input type="text" id="saving_id" class="form-control">
                        <div id="saving_id_status" class="form-text"></div>
                    </div>
                </div>
                
                <!-- Textarea for Paste -->
                <div class="mb-3">
                    <label class="form-label">Paste Excel Data Here</label>
                    <textarea id="excel_data" class="form-control" rows="10" placeholder="Paste your Excel rows here..."></textarea>
                </div>
                
                <!-- Warning Message -->
                <div class="alert alert-warning">
                    <strong>Note:</strong> Importing will delete all existing transactions for this saving account and replace them with the new data.
                </div>
                
                <!-- Action Buttons -->
                <div class="text-center demo-vertical-spacing">
                    <button class="btn btn-primary me-2" id="verify_btn">Verify IDs</button>
                    <button class="btn btn-primary me-2" id="analyze_btn" disabled>Analyze Data</button>
                    <button class="btn btn-success me-2" id="import_btn" disabled>Import Data</button>
                    <button type="reset" class="btn btn-label-secondary" data-bs-dismiss="modal">Discard</button>
                </div>
                
                <!-- Preview Table -->
                <div id="preview_container" style="display:none; margin-top:15px;">
                    <h5>Preview</h5>
                    <table class="table table-bordered" id="preview_table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Description</th>
                                <th>Amount</th>
                                <th>Type</th>
                                <th>Balance</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Loader Popup -->
<div id="import_loader" style="display:none; position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);
    background:#fff;padding:25px;border-radius:10px;box-shadow:0 0 15px rgba(0,0,0,0.3);z-index:9999;">
    <h5 id="loader_text">Processing...</h5>
    <div class="progress mt-2">
        <div id="progress_bar" class="progress-bar" role="progressbar" style="width: 0%"></div>
    </div>
</div>

<!-- Success Popup -->
<div id="import_success" style="display:none; position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);
    background:#28a745;color:#fff;padding:20px 30px;border-radius:10px;box-shadow:0 0 15px rgba(0,0,0,0.3);z-index:9999;">
    Saving History imported successfully!
</div>

<script>
// Initialize DataTable with custom filters
document.addEventListener('DOMContentLoaded', function() {
    let table;
    
    // Function to initialize DataTable
    function initDataTable() {
        // Check if DataTable is already initialized
        if ($.fn.DataTable.isDataTable('#savingHistoryTable')) {
            table.destroy();
        }
        
        // Initialize DataTable
        table = $('#savingHistoryTable').DataTable({
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
            ordering: false,
            info: true,
            paging: true,
            searching: true, // Enable default search
            responsive: true,
            scrollX: true,
            scrollY: '500px',
            scrollCollapse: true,
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                 '<"row"<"col-sm-12"tr>>' +
                 '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>'
        });
    }
    
    // Initialize DataTable on page load
    initDataTable();

    // Store the custom filter function
    let customFilterFunction = null;

    // Function to apply filters
    function applyFilters() {
        const fromDate = document.getElementById('filterFromDate').value;
        const toDate = document.getElementById('filterToDate').value;
        const minAmount = parseFloat(document.getElementById('filterMinAmount').value) || 0;
        const maxAmount = parseFloat(document.getElementById('filterMaxAmount').value) || Number.MAX_VALUE;
        const type = document.getElementById('filterType').value;
        
        // Remove any existing custom filter
        if (customFilterFunction !== null) {
            const index = $.fn.dataTable.ext.search.indexOf(customFilterFunction);
            if (index !== -1) {
                $.fn.dataTable.ext.search.splice(index, 1);
            }
        }
        
        // Add new custom filter function
        customFilterFunction = function(settings, data, dataIndex) {
            const row = table.row(dataIndex).node();
            const rowAmount = parseFloat($(row).data('amount'));
            const rowType = $(row).data('type');
            
            // Get the date from the data attribute (format: Y-m-d H:i:s)
            const rowDateStr = $(row).data('date');
            
            // Date filter
            if (fromDate || toDate) {
                if (!rowDateStr) return false;
                
                // Parse the row date (convert from Y-m-d H:i:s to Date object)
                const rowDate = new Date(rowDateStr);
                
                // Parse the filter dates
                const fromDateObj = fromDate ? new Date(fromDate) : null;
                const toDateObj = toDate ? new Date(toDate) : null;
                
                // Adjust toDate to include the entire day
                if (toDateObj) {
                    toDateObj.setHours(23, 59, 59, 999);
                }
                
                // Check if row date is within the range
                if (fromDateObj && rowDate < fromDateObj) return false;
                if (toDateObj && rowDate > toDateObj) return false;
            }
            
            // Amount filter
            if (rowAmount < minAmount || rowAmount > maxAmount) {
                return false;
            }
            
            // Type filter
            if (type && rowType !== type) {
                return false;
            }
            
            return true;
        };
        
        // Add the custom filter to the search array
        $.fn.dataTable.ext.search.push(customFilterFunction);
        
        // Redraw the table
        table.draw();
    }

    // Function to reset filters
    function resetFilters() {
        document.getElementById('filterFromDate').value = '';
        document.getElementById('filterToDate').value = '';
        document.getElementById('filterMinAmount').value = '';
        document.getElementById('filterMaxAmount').value = '';
        document.getElementById('filterType').value = '';
        
        // Reset DataTable search
        table.search('').columns().search('').draw();
        
        // Remove custom filters
        if (customFilterFunction !== null) {
            const index = $.fn.dataTable.ext.search.indexOf(customFilterFunction);
            if (index !== -1) {
                $.fn.dataTable.ext.search.splice(index, 1);
            }
            customFilterFunction = null;
        }
        
        table.draw();
    }

    // Handle filter buttons
    document.getElementById('applyFilters').addEventListener('click', applyFilters);
    document.getElementById('resetFilters').addEventListener('click', resetFilters);
});

// Saving history import functionality
let validRowsToImport = [];
let runningBalance = 0;

// Verify IDs Button
document.getElementById('verify_btn').addEventListener('click', function() {
    let memberId = document.getElementById('member_id').value.trim();
    let savingId = document.getElementById('saving_id').value.trim();

    if(!memberId || !savingId){
        alert("Please enter both Member ID and Saving ID!");
        return;
    }

    // Show loader
    document.getElementById('loader_text').textContent = "Verifying IDs...";
    document.getElementById('import_loader').style.display='block';

    fetch("{{ route('saving.verify') }}",{
        method:'POST',
        headers:{ 
            'Content-Type':'application/json', 
            'X-CSRF-TOKEN': "{{ csrf_token() }}" 
        },
        body: JSON.stringify({ member_id: memberId, saving_id: savingId })
    })
    .then(res => res.json())
    .then(res => {
        document.getElementById('import_loader').style.display='none';

        document.getElementById('member_id_status').innerHTML = 
            res.member_valid ? '<span class="text-success">✓ Valid</span>' : '<span class="text-danger">✗ Invalid</span>';
        document.getElementById('saving_id_status').innerHTML = 
            res.saving_valid ? '<span class="text-success">✓ Valid</span>' : '<span class="text-danger">✗ Invalid</span>';

        if(res.member_valid && res.saving_valid) {
            document.getElementById('analyze_btn').disabled = false;
            document.getElementById('verify_btn').textContent = 'IDs Verified';
            document.getElementById('verify_btn').classList.replace('btn-primary', 'btn-success');
        } else {
            alert("Invalid Member ID or Saving ID. Please check and try again.");
        }
    })
    .catch(err => {
        document.getElementById('import_loader').style.display='none';
        alert("Error verifying IDs: " + err);
    });
});

// Analyze Button
document.getElementById('analyze_btn').addEventListener('click', function() {
    let memberId = document.getElementById('member_id').value.trim();
    let savingId = document.getElementById('saving_id').value.trim();

    validRowsToImport = [];
    runningBalance = 0;
    let tbody = document.querySelector('#preview_table tbody');
    tbody.innerHTML = '';

    let rawData = document.getElementById('excel_data').value.trim();
    if(!rawData){ 
        alert("Please paste Saving History data!"); 
        return; 
    }

    let rows = rawData.split('\n');

    rows.forEach((row, index) => {
        // Split by any whitespace (tabs or spaces)
        let cols = row.split(/\s+/).filter(col => col.trim() !== '');
        
        // Check if we have at least 7 columns (0-6)
        if(cols.length < 7) return;
        
        // Extract date from 2nd column (index 1)
        let dateStr = cols[1].trim();
        
        // Skip 3rd column (index 2), 5th column (index 4), 6th column (index 5)
        // Extract amount from 4th column (index 3)
        let amountStr = cols[3].replace(/,/g,'').trim();
        
        // Join 7th column (index 6) and 1st column (index 0) for description
        let description = cols[6] + " - " + cols[0];

        if(!dateStr || !description || !amountStr) return;

        let type='Credit', amount=0;
        if(amountStr.startsWith('(') && amountStr.endsWith(')')){
            amount = parseFloat(amountStr.replace(/[()]/g,''));
            type='Debit';
            runningBalance -= amount;
        } else {
            amount = parseFloat(amountStr);
            if(amount<0){ 
                type='Debit'; 
                amount=Math.abs(amount); 
                runningBalance -= amount; 
            } else {
                runningBalance += amount;
            }
        }

        validRowsToImport.push({
            date: dateStr,
            description: description,
            amount: amount,
            type: type
        });

        tbody.innerHTML += `<tr>
            <td>${dateStr}</td>
            <td>${description}</td>
            <td>${amount.toFixed(2)}</td>
            <td>${type}</td>
            <td>${runningBalance.toFixed(2)}</td>
        </tr>`;
    });

    if(validRowsToImport.length===0){
        alert("No valid rows found!");
        document.getElementById('import_btn').disabled=true;
        return;
    }

    document.getElementById('preview_container').style.display='block';
    document.getElementById('import_btn').disabled=false;
});

// Import Button
document.getElementById('import_btn').addEventListener('click', function(){
    let memberId = document.getElementById('member_id').value.trim();
    let savingId = document.getElementById('saving_id').value.trim();

    document.getElementById('import_loader').style.display='block';

    fetch("{{ route('saving.import') }}",{
        method:'POST',
        headers:{ 
            'Content-Type':'application/json', 
            'X-CSRF-TOKEN': "{{ csrf_token() }}" 
        },
        body: JSON.stringify({ member_id:memberId, saving_id:savingId, rows:validRowsToImport })
    })
    .then(res => res.json())
    .then(res => {
        document.getElementById('import_loader').style.display='none';
        if(res.success){ 
            let successPopup = document.getElementById('import_success');
            successPopup.style.display = 'block';
            setTimeout(() => {
                successPopup.style.display = 'none';
                location.reload();
            }, 2000);
        } else {
            alert(res.message || "Import failed");
        }
    })
    .catch(err => {
        document.getElementById('import_loader').style.display='none';
        alert("Error importing: " + err);
    });
});

function copySavingId(id) {
    if(!id) return;
    navigator.clipboard.writeText(id).then(() => {
        let toast = document.createElement("div");
        toast.innerText = "Saving ID " + id + " copied!";
        toast.className = "position-fixed bottom-0 end-0 m-3 p-2 bg-success text-white rounded shadow";
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 2000);
    });
}
</script>

<style>
/* Sticky table header */
.sticky-top {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: white;
}

/* Ensure table header is visible when scrolling */
.table-responsive {
    max-height: 500px;
    overflow-y: auto;
}

/* Style for DataTables search input */
.dataTables_filter input {
    margin-left: 0.5em;
}
</style>