<style>
    .custom-schedule-repay-table th,
    .custom-schedule-repay-table td {
        font-size: 12px;
        padding: 4px 6px;
        vertical-align: middle;
    }

    .custom-schedule-repay-table thead th {
        white-space: nowrap;
    }

    .custom-schedule-repay-table .section-header {
        font-size: 13px;
        font-weight: 600;
        padding: 6px;
    }

    @media (max-width: 768px) {
        .custom-schedule-repay-table th,
        .custom-schedule-repay-table td {
            font-size: 11px;
            padding: 3px 4px;
        }
    }
</style>

<?php
    use Carbon\Carbon;

    $scheduleTotal = ['amount' => 0, 'principal' => 0, 'interest' => 0];
    $repaymentTotal = ['amount' => 0, 'principal' => 0, 'interest' => 0];
    $maxRows = max(count($getScheduleData), count($getRepaymentDetails));
?>



<!-- Import Loan Repayment Button -->
<button class="btn btn-success btn-sm me-2" data-bs-toggle="modal"
        data-bs-target="#importLoanRepaymentModal">
    <i class="menu-icon ti ti-square-rounded-plus"></i>
    Import Loan Repayments
</button>


<div class="table-responsive">
    <table class="table table-bordered table-sm text-center align-middle custom-schedule-repay-table">
        <thead>
            <tr>
                <th colspan="7" class="bg-info text-white section-header">Schedule</th>
                <th colspan="7" class="bg-primary text-white section-header">Repayment</th>
            </tr>
            <tr>
                
                <th>#</th>
                <th>Date</th>
                <th>Amount</th>
                <th>Principal</th>
                <th>Interest</th>
                <th>Balance</th>
                <th>Status</th>

                
                <th>#</th>
                <th>Date</th>
                <th>Amount</th>
                <th>Principal</th>
                <th>Interest</th>
                <th>Balance</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php for($i = 0; $i < $maxRows; $i++): ?>
                <?php
                    $schedule = $getScheduleData[$i] ?? null;
                    $repayment = $getRepaymentDetails[$i] ?? null;

                    // Totals
                    if ($schedule) {
                        $scheduleTotal['amount'] += $schedule->monthlyPayment;
                        $scheduleTotal['principal'] += $schedule->principalPayment;
                        $scheduleTotal['interest'] += $schedule->interestPayment;
                    }

                    if ($repayment) {
                        $repaymentTotal['amount'] += $repayment->repaymentAmount;
                        $repaymentTotal['principal'] += $repayment->principalAmount;
                        $repaymentTotal['interest'] += $repayment->interest;
                    }

                    // Row background if no repayment
                    $rowClass = !$repayment ? 'table-secondary' : '';
                ?>
                <tr class="<?php echo e($rowClass); ?>">
                    
                    <?php if($schedule): ?>
                        <?php $status = strtolower($schedule->status); ?>
                        <td><?php echo e($i + 1); ?></td>
                        <td><?php echo e(Carbon::parse($schedule->paymentDate)->format('d-m-Y')); ?></td>
                        <td><?php echo e(number_format($schedule->monthlyPayment, 2)); ?></td>
                        <td><?php echo e(number_format($schedule->principalPayment, 2)); ?></td>
                        <td><?php echo e(number_format($schedule->interestPayment, 2)); ?></td>
                        <td><?php echo e(number_format($schedule->balance, 2)); ?></td>
                        <td>
                            <span class="badge
                                <?php if($status == 'paid'): ?> bg-success
                                <?php elseif($status == 'unpaid'): ?> bg-warning
                                <?php elseif($status == 'interest wise'): ?> bg-primary
                                <?php elseif($status == 'write off'): ?> bg-danger
                                <?php else: ?> bg-secondary <?php endif; ?>
                            ">
                                <?php echo e(ucfirst($schedule->status)); ?>

                            </span>
                        </td>
                    <?php else: ?>
                        
                        <td colspan="7">—</td>
                    <?php endif; ?>

                    
                    <?php if($repayment): ?>
                        <td><?php echo e($i + 1); ?></td>
                        <td><?php echo e(Carbon::parse($repayment->repaymentDate)->format('d-m-Y')); ?></td>
                        <td><?php echo e(number_format($repayment->repaymentAmount, 2)); ?></td>
                        <td><?php echo e(number_format($repayment->principalAmount, 2)); ?></td>
                        <td><?php echo e(number_format($repayment->interest, 2)); ?></td>
                        <td><?php echo e(number_format($repayment->lastLoanBalance, 2)); ?></td>
                        <td>—</td>
                    <?php else: ?>
                        
                        <td colspan="7">—</td>
                    <?php endif; ?>
                </tr>
            <?php endfor; ?>

            
            <tr class="bg-light fw-bold">
                <td colspan="2">Total</td>
                <td><?php echo e(number_format($scheduleTotal['amount'], 2)); ?></td>
                <td><?php echo e(number_format($scheduleTotal['principal'], 2)); ?></td>
                <td><?php echo e(number_format($scheduleTotal['interest'], 2)); ?></td>
                <td colspan="2"></td>

                <td colspan="2">Total</td>
                <td><?php echo e(number_format($repaymentTotal['amount'], 2)); ?></td>
                <td><?php echo e(number_format($repaymentTotal['principal'], 2)); ?></td>
                <td><?php echo e(number_format($repaymentTotal['interest'], 2)); ?></td>
                <td colspan="2"></td>
            </tr>
        </tbody>
    </table>
</div>


<hr>
<h6 class="fw-bold mt-3 d-flex justify-content-between align-items-center">
    Repayment Details Breakdown
    <button class="btn btn-sm btn-outline-dark" onclick="printSection('repayment-breakdown')">
        🖨️ Print Table
    </button>
</h6>

<div id="repayment-breakdown" class="table-responsive">
    <table class="table table-bordered table-sm text-center align-middle custom-schedule-repay-table">
        <thead class="table-secondary">
            <tr>
                <th>#</th>
                <th>Transaction ID</th>
                <th>Repayment Date</th>
                <th>Staff Name</th>
                <th>Days</th>
                <th>Total Amount</th>
                <th>Principal</th>
                <th>Interest</th>
                <th>Savings</th>
                <th>Balance After</th>
                <th>Remarks</th>
                <th>Receipt</th>
            </tr>
        </thead>
        <tbody>
            <?php
                $totalArrears = 0;
                $totalSavings = 0;
            ?>

            <?php $__empty_1 = true; $__currentLoopData = $getRepaymentDetails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $repayment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <?php
                    $arrears = $repayment->arrears ?? 0;
                    $savings = $repayment->savingAmount ?? 0;
                    $user = \App\Models\Users::find($repayment->userId);
                    $repayDate = Carbon::parse($repayment->repaymentDate);
                    $loanDate = Carbon::parse($repayment->loanStartDate ?? $repayment->repaymentDate);
                    $days = $loanDate->diffInDays($repayDate);

                    $totalArrears += $arrears;
                    $totalSavings += $savings;
                ?>
                <tr>
                    <td><?php echo e($index + 1); ?></td>
                    <td><?php echo e($repayment->transectionId ?? '—'); ?></td>
                    <td><?php echo e($repayDate->format('d-m-Y')); ?></td>
                    <td><?php echo e($user?->name ?? 'Unknown'); ?></td>
                    <td><?php echo e($repayment->days ?? 0); ?></td>
                    <td><?php echo e(number_format($repayment->repaymentAmount, 2)); ?></td>
                    <td><?php echo e(number_format($repayment->principalAmount, 2)); ?></td>
                    <td><?php echo e(number_format($repayment->interest, 2)); ?></td>
                    <td><?php echo e(number_format($savings, 2)); ?></td>
                    <td><?php echo e(number_format($repayment->lastLoanBalance, 2)); ?></td>
                    <td>
                        <?php if($arrears > 0): ?>
                            <span class="badge bg-warning text-dark">Arrears Included</span>
                        <?php elseif($repayment->repaymentAmount > ($repayment->principalAmount + $repayment->interest)): ?>
                            <span class="badge bg-info text-dark">Extra Paid</span>
                        <?php else: ?>
                            —
                        <?php endif; ?>
                    </td>
                    <td>
                        <a href="<?php echo e(route('repayment_receipt', ['id' => $repayment->transectionId])); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
    Print Receipt
</a>
                    </td>
                </tr>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <tr>
                    <td colspan="12">No repayment records available.</td>
                </tr>
            <?php endif; ?>

            <tr class="fw-bold bg-light">
                <td colspan="5">Total</td>
                <td><?php echo e(number_format($getRepaymentDetails->sum('repaymentAmount'), 2)); ?></td>
                <td><?php echo e(number_format($getRepaymentDetails->sum('principalAmount'), 2)); ?></td>
                <td><?php echo e(number_format($getRepaymentDetails->sum('interest'), 2)); ?></td>
                <td><?php echo e(number_format($totalSavings, 2)); ?></td>
                <td colspan="3"></td>
            </tr>
        </tbody>
    </table>
</div>


<!-- Import Loan Repayment Button -->
<button class="btn btn-success btn-sm me-2" data-bs-toggle="modal"
        data-bs-target="#importLoanRepaymentModal">
    <i class="menu-icon ti ti-square-rounded-plus"></i>
    Import Loan Repayments
</button>

<!-- Import Loan Repayment Modal -->
<div class="modal fade" id="importLoanRepaymentModal" 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 Loan Repayments</h4>
                    <p>Verify loan first, then analyze and import repayment data</p>
                </div>

                <!-- Member & Loan ID Inputs -->
                <div class="row mb-3">
                    <div class="col-md-4">
                        <label class="form-label">Member ID</label>
                        <input type="text" id="member_id" class="form-control">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Loan ID</label>
                        <input type="text" id="loan_id" class="form-control">
                    </div>
                    <div class="col-md-4" id="loan_amount_row" style="display:none;">
                        <label class="form-label">Loan Amount</label>
                        <input type="text" id="loan_amount" class="form-control" readonly>
                    </div>
                </div>

                <div class="text-center mb-3">
                    <button class="btn btn-info me-2" id="verify_btn">Verify Loan</button>
                </div>

                <!-- Paste Section -->
                <div class="mb-3" id="paste_section" style="display:none;">
                    <label class="form-label">Paste Loan Repayment Data</label>
                    <textarea id="repayment_data" class="form-control" rows="10"
                              placeholder="Paste your Excel rows here..."></textarea>
                    <small>Format: Date | Skip Column | Principal | Interest</small>
                </div>

                <!-- Action Buttons -->
                <div class="text-center demo-vertical-spacing" id="action_buttons" style="display:none;">
                    <button class="btn btn-primary me-2" id="analyze_btn">Analyze</button>
                    <button class="btn btn-success me-2" id="import_btn" disabled>Import</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>Principal Amount</th>
                                <th>Interest Amount</th>
                                <th>Total Amount</th>
                                <th>Balance</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Loader & Success Popups -->
<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>Please wait...</h5>
</div>

<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;">
    Loan repayments imported successfully!
</div>

<script>
let validRowsToImport = [];
let loanPrincipal = 0;

// Helper function to normalize date
function parseDateString(dateStr){
    dateStr = dateStr.trim();
    if(!dateStr) return "";

    dateStr = dateStr.replace(/\//g,'-');
    let parts = dateStr.split('-');
    if(parts.length === 3){
        let day = parts[0].padStart(2,'0');
        let month = parts[1].padStart(2,'0');
        let year = parts[2].length === 2 ? '20' + parts[2] : parts[2];
        return `${year}-${month}-${day}`;
    }
    return dateStr;
}

// Step 1: Verify Loan
document.getElementById('verify_btn').addEventListener('click', function() {
    let memberId = document.getElementById('member_id').value.trim();
    let loanId = document.getElementById('loan_id').value.trim();
    if(!memberId || !loanId){ alert("Enter Member ID and Loan ID"); return; }

    fetch("<?php echo e(url('/verify-loan')); ?>", {
        method:'POST',
        headers:{ 'Content-Type':'application/json', 'X-CSRF-TOKEN': "<?php echo e(csrf_token()); ?>" },
        body: JSON.stringify({ memberId: memberId, loanId: loanId })
    })
    .then(res=>res.json())
    .then(res=>{
        if(res.success){
            loanPrincipal = parseFloat(res.loanPrincipal) || 0;
            document.getElementById('loan_amount_row').style.display = 'block';
            document.getElementById('loan_amount').value = loanPrincipal.toFixed(2);
            document.getElementById('paste_section').style.display='block';
            document.getElementById('action_buttons').style.display='block';
        } else {
            alert(res.message || "Loan verification failed");
        }
    })
    .catch(err=>{ alert("Error verifying loan"); console.log(err); });
});

// Step 2: Analyze
document.getElementById('analyze_btn').addEventListener('click', function() {
    let rawData = document.getElementById('repayment_data').value.trim();
    if(!rawData){ alert("Paste loan repayment data"); return; }

    rawData = rawData.split("\n").map(row => row.trim().replace(/\s+/g, "\t")).join("\n");

    let runningBalance = loanPrincipal;
    let tempData = {};

    rawData.split("\n").forEach(row => {
        let cols = row.split("\t");
        if(cols.length < 4) return; 

        let dateStr = parseDateString(cols[0]);
        let principal = parseFloat(cols[2].replace(/,/g,'').trim()) || 0;
        let interest = parseFloat(cols[3].replace(/,/g,'').trim()) || 0;

        if(tempData[dateStr]){
            tempData[dateStr].principalAmount += principal;
            tempData[dateStr].interest += interest;
            tempData[dateStr].repaymentAmount += (principal + interest);
        } else {
            tempData[dateStr] = {
                repaymentDate: dateStr,
                principalAmount: principal,
                interest: interest,
                repaymentAmount: principal + interest
            };
        }
    });

    let sortedDates = Object.keys(tempData).sort((a,b) => new Date(a) - new Date(b));
    validRowsToImport = [];

    sortedDates.forEach(dateStr => {
        let r = tempData[dateStr];
        runningBalance -= r.principalAmount;
        r.lastLoanBalance = runningBalance;
        validRowsToImport.push(r);
    });

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

    let tbody = document.querySelector('#preview_table tbody');
    tbody.innerHTML = '';
    validRowsToImport.forEach(r=>{
        tbody.innerHTML += `<tr>
            <td>${r.repaymentDate}</td>
            <td>${r.principalAmount.toFixed(2)}</td>
            <td>${r.interest.toFixed(2)}</td>
            <td>${r.repaymentAmount.toFixed(2)}</td>
            <td>${r.lastLoanBalance.toFixed(2)}</td>
        </tr>`;
    });

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

// Step 3: Import
document.getElementById('import_btn').addEventListener('click', function(){
    let memberId = document.getElementById('member_id').value.trim();
    let loanId = document.getElementById('loan_id').value.trim();

    if(validRowsToImport.length===0){ alert("Nothing to import!"); return; }

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

    fetch("<?php echo e(url('/import-repayment-data')); ?>", {
        method:'POST',
        headers:{ 'Content-Type':'application/json', 'X-CSRF-TOKEN': "<?php echo e(csrf_token()); ?>" },
        body: JSON.stringify({ memberId: memberId, loanId: loanId, rows: validRowsToImport, action:'import' })
    })
    .then(res=>res.json())
    .then(res=>{
        document.getElementById('import_loader').style.display='none';
        if(res.success){
            let popup = document.getElementById('import_success');
            popup.style.display='block';
            setTimeout(()=>{ popup.style.display='none'; location.reload(); }, 2000);
        } else { alert(res.message || "Import failed"); }
    })
    .catch(err=>{
        document.getElementById('import_loader').style.display='none';
        alert("Error importing data"); console.log(err);
    });
});
</script>






<script>
function printSection(sectionId) {
    var original = document.body.innerHTML;
    var printArea = document.getElementById(sectionId).innerHTML;
    document.body.innerHTML = printArea;
    window.print();
    document.body.innerHTML = original;
}
</script>
<?php /**PATH /home/techhdyz/swd.technathi.cloud/resources/views/pages/allpages/loan/repayment_schedule_view.blade.php ENDPATH**/ ?>