@extends('layouts.app')

@section('title', 'Customer Credit Profile')

@section('content')
<div class="container-fluid pt-4">
    <div class="row mb-4">
        <div class="col-md-12">
            <h2 class="mb-4">
                <i class="fas fa-credit-card"></i> Customer Credit Profile
            </h2>
        </div>
    </div>

    <!-- Customer Selection Section -->
    <div class="card mb-4 shadow-sm">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">
                <i class="fas fa-search"></i> Select Customer
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-8">
                    <label for="customer_search" class="form-label">Search Customer</label>
                    <select id="customer_search" class="form-control form-control-lg" style="width: 100%;">
                        <option value="">-- Select Customer --</option>
                        @foreach($customers as $cust)
                            <option value="{{ $cust->id }}" data-balance="{{ $cust->balance_amount ?? 0 }}">
                                {{ $cust->customer_name }} | Contact: {{ $cust->contact_number ?? 'N/A' }} | NIC: {{ $cust->nic ?? 'N/A' }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button id="loadProfile" class="btn btn-primary btn-lg w-100">
                        <i class="fas fa-chart-line"></i> Load Profile
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Profile Content (shown after selection) -->
    <div id="profileContent" style="display: none;">
        <!-- Credit Score Header -->
        <div class="card mb-4 shadow-sm">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0">
                    <i class="fas fa-star"></i> Credit Summary
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3 text-center">
                        <div class="credit-score-circle" id="creditScoreCircle" style="width: 120px; height: 120px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 32px; font-weight: bold; margin: 0 auto; background: #f0f0f0; color: #333;">
                            --
                        </div>
                        <small class="text-muted">Credit Score (0-100)</small>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-box stat-overdue">
                            <div class="stat-label">Current Balance</div>
                            <div class="stat-value" id="currentBalance">0.00</div>
                            <div class="stat-unit">LKR</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-box stat-overdue">
                            <div class="stat-label">Total Invoices</div>
                            <div class="stat-value" id="totalInvoices">0</div>
                            <div class="stat-unit">Invoices</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="stat-box stat-overdue">
                            <div class="stat-label">Payment Status</div>
                            <div class="stat-value" id="paymentStatus">GOOD</div>
                            <div class="stat-unit" id="paymentStatusDetail">No Overdue</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Key Metrics -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card shadow-sm border-left-primary">
                    <div class="card-body">
                        <div class="small text-muted text-uppercase font-weight-bold">Total Outstanding</div>
                        <div class="h3 mb-0" id="totalOutstanding">0.00</div>
                        <small class="text-muted">All due amounts</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card shadow-sm border-left-warning">
                    <div class="card-body">
                        <div class="small text-muted text-uppercase font-weight-bold">Overdue Amount</div>
                        <div class="h3 mb-0 text-danger" id="overdueAmount">0.00</div>
                        <small class="text-muted">Past due date</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card shadow-sm border-left-success">
                    <div class="card-body">
                        <div class="small text-muted text-uppercase font-weight-bold">Avg Payment Days</div>
                        <div class="h3 mb-0" id="avgPaymentDays">--</div>
                        <small class="text-muted">Days after due date</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card shadow-sm border-left-danger">
                    <div class="card-body">
                        <div class="small text-muted text-uppercase font-weight-bold">Max Overdue Days</div>
                        <div class="h3 mb-0 text-danger" id="maxOverdueDays">0</div>
                        <small class="text-muted">Longest delay</small>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs for different views -->
        <ul class="nav nav-tabs mb-4" id="profileTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="invoices-tab" data-bs-toggle="tab" data-bs-target="#invoices" type="button">
                    <i class="fas fa-file-invoice"></i> Invoices
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="installments-tab" data-bs-toggle="tab" data-bs-target="#installments" type="button">
                    <i class="fas fa-list"></i> Installments & Due Dates
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="payments-tab" data-bs-toggle="tab" data-bs-target="#payments" type="button">
                    <i class="fas fa-money-check"></i> Payment History
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="analysis-tab" data-bs-toggle="tab" data-bs-target="#analysis" type="button">
                    <i class="fas fa-chart-bar"></i> Analysis
                </button>
            </li>
        </ul>

        <div class="tab-content">
            <!-- Invoices Tab -->
            <div class="tab-pane fade show active" id="invoices" role="tabpanel">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <h6 class="mb-0">All Invoices</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id="invoicesTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>Date</th>
                                        <th>Mode</th>
                                        <th>Amount</th>
                                        <th>Paid</th>
                                        <th>Outstanding</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="invoicesBody">
                                    <tr><td colspan="7" class="text-center text-muted">Loading...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Installments Tab -->
            <div class="tab-pane fade" id="installments" role="tabpanel">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <h6 class="mb-0">Installment Schedule & Due Dates</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-sm" id="installmentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>Installment</th>
                                        <th>Amount</th>
                                        <th>Due Date</th>
                                        <th>Days Until Due</th>
                                        <th>Paid Amount</th>
                                        <th>Outstanding</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody id="installmentsBody">
                                    <tr><td colspan="8" class="text-center text-muted">Loading...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Payments Tab -->
            <div class="tab-pane fade" id="payments" role="tabpanel">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <h6 class="mb-0">Payment History</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-sm" id="paymentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Invoice #</th>
                                        <th>Payment Date</th>
                                        <th>Installment</th>
                                        <th>Amount Paid</th>
                                        <th>Days After Due</th>
                                        <th>Payment Status</th>
                                    </tr>
                                </thead>
                                <tbody id="paymentsBody">
                                    <tr><td colspan="6" class="text-center text-muted">Loading...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Analysis Tab -->
            <div class="tab-pane fade" id="analysis" role="tabpanel">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card shadow-sm mb-4">
                            <div class="card-header">
                                <h6 class="mb-0">Payment Timeliness</h6>
                            </div>
                            <div class="card-body">
                                <canvas id="paymentTimelinessChart" height="80"></canvas>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card shadow-sm mb-4">
                            <div class="card-header">
                                <h6 class="mb-0">Invoice Distribution</h6>
                            </div>
                            <div class="card-body">
                                <canvas id="invoiceDistributionChart" height="80"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card shadow-sm">
                    <div class="card-header">
                        <h6 class="mb-0">Customer Creditworthiness Assessment</h6>
                    </div>
                    <div class="card-body">
                        <div id="creditAssessment">
                            <!-- Assessment will be loaded here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Create Invoice Button removed -->
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<!-- jQuery (needed by Select2 and page scripts) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<style>
    .stat-box {
        text-align: center;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 8px;
    }
    .stat-label {
        font-size: 12px;
        color: #666;
        text-transform: uppercase;
        font-weight: 600;
        margin-bottom: 8px;
    }
    .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #333;
    }
    .stat-unit {
        font-size: 11px;
        color: #999;
    }
    .border-left-primary {
        border-left: 4px solid #007bff !important;
    }
    .border-left-warning {
        border-left: 4px solid #ffc107 !important;
    }
    .border-left-success {
        border-left: 4px solid #28a745 !important;
    }
    .border-left-danger {
        border-left: 4px solid #dc3545 !important;
    }
    .status-badge {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
    }
    .status-paid {
        background: #d4edda;
        color: #155724;
    }
    .status-pending {
        background: #fff3cd;
        color: #856404;
    }
    .status-overdue {
        background: #f8d7da;
        color: #721c24;
    }
    .status-good {
        background: #d4edda;
        color: #155724;
    }
    .status-fair {
        background: #fff3cd;
        color: #856404;
    }
    .status-poor {
        background: #f8d7da;
        color: #721c24;
    }

    /* Select2 dark styling for the customer search dropdown */
    .select2-container--default .select2-selection--single {
        background-color: #343a40; /* dark background */
        color: #fff;
        border: 1px solid #495057;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #fff;
    }
    .select2-container--default .select2-selection--single .select2-selection__placeholder {
        color: #ced4da;
    }
    .select2-dropdown {
        background-color: #343a40;
        color: #fff;
        border: 1px solid #495057;
    }
    .select2-container--default .select2-results__option {
        background-color: transparent; /* inherit dropdown bg */
        color: #fff;
    }
    .select2-container--default .select2-results__option--highlighted {
        background-color: #495057; /* slightly lighter for hover */
        color: #fff;
    }
    /* make the dropdown arrow visible on dark background */
    .select2-container .select2-selection--single .select2-selection__arrow b {
        border-color: #fff transparent transparent;
    }

    /* overdue-like highlighted stat box (match Overdue Amount styling) */
    .stat-overdue {
        background: #f8d7da; /* light red */
        color: #721c24; /* dark red text */
    }
    .stat-overdue .stat-label {
        color: #721c24;
    }
    .stat-overdue .stat-value {
        color: #721c24;
    }
</style>

<script>
    let currentCustomerId = null;
    let customerData = null;

    // Initialize Select2
    $('#customer_search').select2({
        placeholder: 'Search by name, contact, or NIC',
        allowClear: true,
        width: '100%'
    });

    // Load Profile
    $('#loadProfile').click(function() {
        const customerId = $('#customer_search').val();
        if (!customerId) {
            alert('Please select a customer');
            return;
        }
        loadCustomerProfile(customerId);
    });

    // Enter key on customer search
    $('#customer_search').on('select2:select', function() {
        loadCustomerProfile($(this).val());
    });

    function loadCustomerProfile(customerId) {
        currentCustomerId = customerId;
        
        // Show loading state
        $('#profileContent').show();
        $('#invoicesBody').html('<tr><td colspan="7" class="text-center"><div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div> Loading customer profile...</td></tr>');
        $('#installmentsBody').html('<tr><td colspan="8" class="text-center"><div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div> Loading installments...</td></tr>');
        $('#paymentsBody').html('<tr><td colspan="6" class="text-center"><div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div> Loading payments...</td></tr>');

        // Fetch customer profile data
        fetch(`/api/customers/${customerId}/credit-profile`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) throw new Error('Failed to load profile');
            return response.json();
        })
        .then(data => {
            customerData = data;
            renderProfile(data);
            renderCharts(data);
            renderAssessment(data);
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading customer profile: ' + error.message);
        });
    }

    function renderProfile(data) {
        // Customer info
        document.title = data.customer.customer_name + ' - Credit Profile';

        // Credit Score
        const creditScore = calculateCreditScore(data);
        const scoreColor = creditScore >= 75 ? '#28a745' : (creditScore >= 50 ? '#ffc107' : '#dc3545');
        $('#creditScoreCircle').css('background', scoreColor).css('color', 'white').text(creditScore);

        // Summary stats
        $('#currentBalance').text(formatCurrency(data.customer.balance_amount || 0));
        $('#totalInvoices').text(data.invoices.length);

        // Payment status
        const overdueAmount = data.summary.total_overdue_amount;
        const paymentStatus = overdueAmount > 0 ? 'AT RISK' : 'GOOD';
        const paymentStatusDetail = overdueAmount > 0 ? `Overdue: ${formatCurrency(overdueAmount)}` : 'No Overdue';
        $('#paymentStatus').text(paymentStatus).css('color', overdueAmount > 0 ? '#dc3545' : '#28a745');
        $('#paymentStatusDetail').text(paymentStatusDetail);

        // Key metrics
        $('#totalOutstanding').text(formatCurrency(data.summary.total_outstanding));
        $('#overdueAmount').text(formatCurrency(data.summary.total_overdue_amount));
        $('#avgPaymentDays').text(data.summary.avg_payment_days !== null ? data.summary.avg_payment_days.toFixed(1) : '--');
        $('#maxOverdueDays').text(data.summary.max_overdue_days || 0);

        // Invoices Table
        renderInvoicesTable(data.invoices);

        // Installments Table
        renderInstallmentsTable(data.installments);

        // Payments Table
        renderPaymentsTable(data.payments);
    }

    function renderInvoicesTable(invoices) {
        if (invoices.length === 0) {
            $('#invoicesBody').html('<tr><td colspan="7" class="text-center text-muted">No invoices found</td></tr>');
            return;
        }

        let html = '';
        invoices.forEach(inv => {
            const outstanding = inv.net_total - (inv.down_payment || 0) - (inv.total_paid || 0);
            const statusClass = outstanding > 0 ? 'status-pending' : 'status-paid';
            const statusText = outstanding > 0 ? 'Pending' : 'Paid';
            
            html += `<tr>
                <td><strong>${inv.invoice_number}</strong></td>
                <td>${new Date(inv.date_time).toLocaleDateString('en-GB')}</td>
                <td><span class="badge" style="background: ${inv.invoice_mode === 'loan' ? '#0066cc' : '#28a745'}">${inv.invoice_mode.toUpperCase()}</span></td>
                <td>${formatCurrency(inv.net_total)}</td>
                <td>${formatCurrency((inv.down_payment || 0) + (inv.total_paid || 0))}</td>
                <td><strong>${formatCurrency(Math.max(0, outstanding))}</strong></td>
                <td><span class="status-badge ${statusClass}">${statusText}</span></td>
            </tr>`;
        });
        $('#invoicesBody').html(html);
    }

    function renderInstallmentsTable(installments) {
        if (installments.length === 0) {
            $('#installmentsBody').html('<tr><td colspan="8" class="text-center text-muted">No installments found</td></tr>');
            return;
        }

        let html = '';
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        installments.forEach(inst => {
            const dueDate = new Date(inst.due_date);
            dueDate.setHours(0, 0, 0, 0);
            const daysUntilDue = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
            const outstanding = inst.amount - inst.paid_amount;
            
            let statusClass = 'status-pending';
            let statusText = 'PENDING';
            if (outstanding <= 0) {
                statusClass = 'status-paid';
                statusText = 'PAID';
            } else if (daysUntilDue < 0) {
                statusClass = 'status-overdue';
                statusText = `OVERDUE (${Math.abs(daysUntilDue)} days)`;
            }

            html += `<tr>
                <td><strong>${inst.invoice_number}</strong></td>
                <td>${inst.installment_number}</td>
                <td>${formatCurrency(inst.amount)}</td>
                <td>${dueDate.toLocaleDateString('en-GB')}</td>
                <td>${daysUntilDue > 0 ? daysUntilDue + ' days' : (daysUntilDue === 0 ? 'Today' : `${Math.abs(daysUntilDue)} days ago`)}</td>
                <td>${formatCurrency(inst.paid_amount)}</td>
                <td><strong>${formatCurrency(Math.max(0, outstanding))}</strong></td>
                <td><span class="status-badge ${statusClass}">${statusText}</span></td>
            </tr>`;
        });
        $('#installmentsBody').html(html);
    }

    function renderPaymentsTable(payments) {
        if (payments.length === 0) {
            $('#paymentsBody').html('<tr><td colspan="6" class="text-center text-muted">No payments found</td></tr>');
            return;
        }

        let html = '';
        payments.forEach(pmt => {
            const paymentDate = new Date(pmt.payment_date);
            const dueDate = new Date(pmt.due_date);
            const daysAfterDue = Math.ceil((paymentDate - dueDate) / (1000 * 60 * 60 * 24));
            
            let statusClass = 'status-good';
            let statusText = 'ON TIME';
            if (daysAfterDue > 0 && daysAfterDue <= 7) {
                statusClass = 'status-fair';
                statusText = `${daysAfterDue} days late`;
            } else if (daysAfterDue > 7) {
                statusClass = 'status-poor';
                statusText = `${daysAfterDue} days late`;
            }

            html += `<tr>
                <td><strong>${pmt.invoice_number}</strong></td>
                <td>${paymentDate.toLocaleDateString('en-GB')}</td>
                <td>${pmt.installment_number}</td>
                <td>${formatCurrency(pmt.paid_amount)}</td>
                <td>${daysAfterDue <= 0 ? 'Early' : daysAfterDue + ' days'}</td>
                <td><span class="status-badge ${statusClass}">${statusText}</span></td>
            </tr>`;
        });
        $('#paymentsBody').html(html);
    }

    function renderCharts(data) {
        renderPaymentTimelinessChart(data);
        renderInvoiceDistributionChart(data);
    }

    function renderPaymentTimelinessChart(data) {
        const payments = data.payments;
        const onTime = payments.filter(p => {
            const paymentDate = new Date(p.payment_date);
            const dueDate = new Date(p.due_date);
            return (paymentDate - dueDate) <= 0;
        }).length;
        const late = payments.length - onTime;

            const canvas = document.getElementById('paymentTimelinessChart');
            const ctx = canvas.getContext('2d');
            // Safely destroy any previous Chart instance: prefer Chart.getChart (Chart.js API)
            try {
                const existing = (typeof Chart !== 'undefined' && Chart.getChart) ? Chart.getChart(canvas) : window.paymentTimelinessChart;
                if (existing && typeof existing.destroy === 'function') {
                    existing.destroy();
                }
            } catch (err) {
                // If anything goes wrong destroying, remove silently and continue to recreate
                console.warn('Could not destroy previous paymentTimelinessChart instance:', err);
            }
            window.paymentTimelinessChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['On Time', 'Late'],
                datasets: [{
                    data: [onTime, late],
                    backgroundColor: ['#28a745', '#dc3545'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });
    }

    function renderInvoiceDistributionChart(data) {
        const invoices = data.invoices;
        const cash = invoices.filter(i => i.invoice_mode === 'cash').length;
        const loan = invoices.filter(i => i.invoice_mode === 'loan').length;

        const canvas = document.getElementById('invoiceDistributionChart');
        const ctx = canvas.getContext('2d');
        try {
            const existing = (typeof Chart !== 'undefined' && Chart.getChart) ? Chart.getChart(canvas) : window.invoiceDistributionChart;
            if (existing && typeof existing.destroy === 'function') {
                existing.destroy();
            }
        } catch (err) {
            console.warn('Could not destroy previous invoiceDistributionChart instance:', err);
        }
        window.invoiceDistributionChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: ['Cash', 'Loan'],
                datasets: [{
                    data: [cash, loan],
                    backgroundColor: ['#28a745', '#0066cc'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { position: 'bottom' }
                }
            }
        });
    }

    function renderAssessment(data) {
        const creditScore = calculateCreditScore(data);
        const assessment = generateCreditAssessment(data, creditScore);
        
        let html = `
            <div class="alert alert-${assessment.level === 'Excellent' ? 'success' : (assessment.level === 'Good' ? 'info' : (assessment.level === 'Fair' ? 'warning' : 'danger'))}">
                <h5><strong>Credit Rating: ${assessment.level}</strong></h5>
                <p>${assessment.message}</p>
                <hr>
                <ul>
        `;
        
        assessment.details.forEach(detail => {
            html += `<li>${detail}</li>`;
        });
        
        html += `</ul></div>`;
        
        $('#creditAssessment').html(html);
    }

    function calculateCreditScore(data) {
        let score = 100;
        
        // Deduct for overdue amounts
        if (data.summary.total_overdue_amount > 0) {
            score -= Math.min(40, data.summary.total_overdue_amount / 1000); // Max -40
        }
        
        // Deduct for late payments
        const latePayments = data.payments.filter(p => {
            const paymentDate = new Date(p.payment_date);
            const dueDate = new Date(p.due_date);
            return (paymentDate - dueDate) > 0;
        }).length;
        
        if (data.payments.length > 0) {
            const latePercentage = (latePayments / data.payments.length) * 100;
            score -= Math.min(30, latePercentage / 5); // Max -30
        }
        
        // Deduct for high outstanding balance
        const totalCredit = data.summary.total_outstanding + data.summary.total_paid;
        if (totalCredit > 0) {
            const outstandingPercentage = (data.summary.total_outstanding / totalCredit) * 100;
            if (outstandingPercentage > 50) {
                score -= Math.min(20, (outstandingPercentage - 50) / 5); // Max -20
            }
        }
        
        return Math.max(0, Math.round(score));
    }

    function generateCreditAssessment(data, score) {
        let level, message;
        
        if (score >= 80) {
            level = 'Excellent';
            message = 'This customer has an excellent payment record with consistent on-time payments and no overdue amounts.';
        } else if (score >= 60) {
            level = 'Good';
            message = 'This customer has a good payment record with mostly on-time payments and minimal overdue issues.';
        } else if (score >= 40) {
            level = 'Fair';
            message = 'This customer has a fair payment record with some late payments or moderate outstanding amounts.';
        } else {
            level = 'Poor';
            message = 'This customer has a poor payment record with frequent late payments or significant overdue amounts.';
        }
        
        const details = [];
        details.push(`Total Credit Transactions: ${data.invoices.length} invoices`);
        details.push(`Total Transaction Value: ${formatCurrency(data.summary.total_credit_value)}`);
        details.push(`Current Outstanding: ${formatCurrency(data.summary.total_outstanding)}`);
        details.push(`Total Overdue: ${formatCurrency(data.summary.total_overdue_amount)}`);
        
        if (data.payments.length > 0) {
            const latePayments = data.payments.filter(p => {
                const paymentDate = new Date(p.payment_date);
                const dueDate = new Date(p.due_date);
                return (paymentDate - dueDate) > 0;
            }).length;
            const latePercentage = ((latePayments / data.payments.length) * 100).toFixed(1);
            details.push(`Late Payment Rate: ${latePercentage}% of payments`);
        }
        
        details.push(`Maximum Overdue Days: ${data.summary.max_overdue_days || 0} days`);
        
        if (data.summary.avg_payment_days !== null) {
            details.push(`Average Payment Delay: ${data.summary.avg_payment_days.toFixed(1)} days after due date`);
        }
        
        return { level, message, details };
    }

    function formatCurrency(amount) {
        return new Intl.NumberFormat('en-LK', { 
            style: 'currency', 
            currency: 'LKR',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(amount);
    }

</script>
@endsection
