@extends('layouts.app')

@section('title', 'Overdue Installments')

@section('actions')
    <a href="{{ route('installments.index') }}" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back to All
    </a>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#sendBulkRemindersModal">
        <i class="fas fa-bell"></i> Send Bulk Reminders
    </button>
@endsection

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-12">
            <h2 class="h3 mb-0">Overdue Installments</h2>
            <p class="text-muted">Manage overdue installment payments</p>
        </div>
    </div>

    <!-- Stats Card -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                                Total Overdue
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($installments->total()) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Total Overdue Amount
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($installments->sum('amount'), 2) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-money-bill-wave fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Total Late Fees
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($installments->sum('late_fee'), 2) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Potential Revenue
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($installments->sum('amount') + $installments->sum('late_fee'), 2) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-chart-line fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Overdue Installments Table -->
    <div class="row">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Overdue Installment List</h5>
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                            <label class="form-check-label" for="selectAll">Select All</label>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> {{ session('success') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif
                    
                    @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif

                    @if($installments->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="thead-light">
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" class="form-check-input" id="selectAllRows">
                                    </th>
                                    <th>#</th>
                                    <th>Customer</th>
                                    <th>Sale Invoice</th>
                                    <th>Installment</th>
                                    <th>Amount</th>
                                    <th>Due Date</th>
                                    <th>Days Overdue</th>
                                    <th>Late Fee</th>
                                    <th>Total Due</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($installments as $installment)
                                @php
                                    $daysOverdue = now()->diffInDays($installment->due_date);
                                    $lateFee = $installment->late_fee > 0 ? $installment->late_fee : ($daysOverdue * 100); // Example: 100 per day
                                    $totalDue = $installment->amount + $lateFee;
                                @endphp
                                <tr class="overdue-row" data-id="{{ $installment->id }}">
                                    <td>
                                        <input type="checkbox" class="form-check-input row-checkbox" 
                                               value="{{ $installment->id }}" 
                                               data-customer="{{ $installment->customer->name ?? '' }}"
                                               data-phone="{{ $installment->customer->phone ?? '' }}"
                                               data-amount="{{ $installment->amount }}"
                                               data-due-date="{{ $installment->due_date->format('Y-m-d') }}">
                                    </td>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>
                                        <strong>{{ $installment->customer->name ?? 'N/A' }}</strong>
                                        <br>
                                        <small class="text-muted">{{ $installment->customer->phone ?? '' }}</small>
                                    </td>
                                    <td>
                                        <a href="{{ route('sales.show', $installment->sale_id) }}" class="text-primary">
                                            {{ $installment->sale->invoice_number ?? 'N/A' }}
                                        </a>
                                    </td>
                                    <td>
                                        <strong>{{ $installment->installment_no }}/{{ $installment->total_installments }}</strong>
                                    </td>
                                    <td>
                                        <strong class="text-success">৳{{ number_format($installment->amount, 2) }}</strong>
                                    </td>
                                    <td>
                                        <span class="text-danger">
                                            {{ $installment->due_date->format('d M, Y') }}
                                        </span>
                                        <br>
                                        <small class="text-muted">{{ $installment->due_date->diffForHumans() }}</small>
                                    </td>
                                    <td>
                                        <span class="badge badge-danger">{{ $daysOverdue }} days</span>
                                    </td>
                                    <td class="text-warning">
                                        <strong>৳{{ number_format($lateFee, 2) }}</strong>
                                    </td>
                                    <td class="text-danger">
                                        <strong>৳{{ number_format($totalDue, 2) }}</strong>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-success pay-btn"
                                                    data-id="{{ $installment->id }}"
                                                    data-amount="{{ $installment->amount }}"
                                                    data-late-fee="{{ $lateFee }}"
                                                    title="Pay Now">
                                                <i class="fas fa-money-bill-wave"></i> Pay
                                            </button>
                                            
                                            <button type="button" class="btn btn-warning remind-btn"
                                                    data-id="{{ $installment->id }}"
                                                    data-customer="{{ $installment->customer->name ?? '' }}"
                                                    data-phone="{{ $installment->customer->phone ?? '' }}"
                                                    data-amount="{{ $installment->amount }}"
                                                    data-days-overdue="{{ $daysOverdue }}"
                                                    title="Send Reminder">
                                                <i class="fas fa-bell"></i> Remind
                                            </button>
                                            
                                            <a href="{{ route('installments.show', $installment->id) }}" 
                                               class="btn btn-info" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div class="text-muted">
                            Showing {{ $installments->firstItem() ?? 0 }} to {{ $installments->lastItem() ?? 0 }} 
                            of {{ $installments->total() }} overdue installments
                        </div>
                        <div>
                            {{ $installments->links() }}
                        </div>
                    </div>
                    
                    <!-- Bulk Actions -->
                    <div class="mt-4 p-3 bg-light rounded">
                        <h6>Bulk Actions for Selected Installments:</h6>
                        <div class="btn-group">
                            <button type="button" class="btn btn-primary" id="bulkRemindBtn">
                                <i class="fas fa-bell"></i> Send Reminders
                            </button>
                            <button type="button" class="btn btn-success" id="bulkPayBtn">
                                <i class="fas fa-money-bill-wave"></i> Process Payments
                            </button>
                            <button type="button" class="btn btn-warning" id="bulkWaiveBtn">
                                <i class="fas fa-hand-holding-usd"></i> Waive Late Fees
                            </button>
                            <button type="button" class="btn btn-info" id="bulkExportBtn">
                                <i class="fas fa-download"></i> Export List
                            </button>
                        </div>
                    </div>
                    
                    @else
                    <div class="text-center py-5">
                        <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                        <h5>No Overdue Installments!</h5>
                        <p class="text-muted">All installments are up to date.</p>
                        <a href="{{ route('installments.index') }}" class="btn btn-primary">
                            <i class="fas fa-list"></i> View All Installments
                        </a>
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Process Payment</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="paymentForm" method="POST">
                @csrf
                <div class="modal-body">
                    <input type="hidden" name="installment_id" id="installment_id">
                    
                    <div class="form-group">
                        <label for="payment_date">Payment Date</label>
                        <input type="date" name="payment_date" id="payment_date" 
                               class="form-control" value="{{ date('Y-m-d') }}" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="amount">Installment Amount (৳)</label>
                        <input type="number" name="installment_amount" id="installment_amount" 
                               class="form-control" step="0.01" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="late_fee">Late Fee (৳)</label>
                        <input type="number" name="late_fee" id="late_fee" 
                               class="form-control" step="0.01" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="total_amount">Total Amount (৳)</label>
                        <input type="number" name="amount" id="total_amount" 
                               class="form-control" step="0.01" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="payment_method">Payment Method</label>
                        <select name="payment_method" id="payment_method" class="form-control" required>
                            <option value="cash">Cash</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="check">Check</option>
                            <option value="mobile_banking">Mobile Banking</option>
                            <option value="others">Others</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="reference_no">Reference No</label>
                        <input type="text" name="reference_no" id="reference_no" class="form-control">
                    </div>
                    
                    <div class="form-group">
                        <label for="notes">Notes</label>
                        <textarea name="notes" id="notes" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Process Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reminder Modal -->
<div class="modal fade" id="reminderModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Reminder</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="reminderForm" method="POST">
                @csrf
                <div class="modal-body">
                    <input type="hidden" name="installment_id" id="reminder_installment_id">
                    
                    <div class="form-group">
                        <label for="customer_name">Customer</label>
                        <input type="text" id="customer_name" class="form-control" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="customer_phone">Phone</label>
                        <input type="text" id="customer_phone" class="form-control" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label for="reminder_type">Reminder Type</label>
                        <select name="reminder_type" id="reminder_type" class="form-control" required>
                            <option value="sms">SMS</option>
                            <option value="email">Email</option>
                            <option value="both">Both SMS & Email</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="reminder_message">Message Template</label>
                        <select id="message_template" class="form-control mb-2">
                            <option value="">Select Template</option>
                            <option value="friendly">Friendly Reminder</option>
                            <option value="urgent">Urgent Reminder</option>
                            <option value="final">Final Notice</option>
                        </select>
                        <textarea name="message" id="reminder_message" class="form-control" rows="5" required>
Dear [Customer Name],

This is a reminder for your overdue installment payment.

Amount Due: ৳[Amount]
Due Date: [Due Date]
Days Overdue: [Days] days
Late Fee: ৳[Late Fee]

Please make the payment at your earliest convenience.

Thank you,
{{ config('app.name') }}
                        </textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Reminder</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Reminders Modal -->
<div class="modal fade" id="sendBulkRemindersModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Send Bulk Reminders</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form method="POST" action="{{ route('installments.bulk-remind') }}">
                @csrf
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> This will send reminders to all overdue installment customers.
                    </div>
                    
                    <div class="form-group">
                        <label for="bulk_reminder_type">Reminder Type</label>
                        <select name="reminder_type" id="bulk_reminder_type" class="form-control" required>
                            <option value="sms">SMS Only</option>
                            <option value="email">Email Only</option>
                            <option value="both">Both SMS & Email</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="bulk_message_template">Message Template</label>
                        <textarea name="message" id="bulk_message_template" class="form-control" rows="6" required>
Dear customer,

Your installment payment is overdue. Please make the payment immediately to avoid additional late fees.

Best regards,
{{ config('app.name') }}
                        </textarea>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" name="include_late_fee" id="include_late_fee" class="form-check-input" checked>
                        <label class="form-check-label" for="include_late_fee">
                            Include late fee information
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Bulk Reminders</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .overdue-row {
        background-color: #fff8e1;
    }
    
    .overdue-row:hover {
        background-color: #fff3cd;
    }
    
    .badge-danger {
        font-size: 0.75rem;
        padding: 0.35em 0.65em;
    }
    
    .btn-group-sm > .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    
    .bg-light {
        background-color: #f8f9fa !important;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        // Select All checkbox
        $('#selectAll, #selectAllRows').change(function() {
            $('.row-checkbox').prop('checked', $(this).prop('checked'));
        });
        
        // Individual checkbox
        $('.row-checkbox').change(function() {
            if(!$(this).prop('checked')) {
                $('#selectAll, #selectAllRows').prop('checked', false);
            } else {
                var allChecked = $('.row-checkbox:checked').length === $('.row-checkbox').length;
                $('#selectAll, #selectAllRows').prop('checked', allChecked);
            }
        });
        
        // Payment modal
        $('.pay-btn').click(function(e) {
            e.stopPropagation();
            
            var installmentId = $(this).data('id');
            var amount = $(this).data('amount');
            var lateFee = $(this).data('late-fee');
            var totalAmount = parseFloat(amount) + parseFloat(lateFee);
            
            $('#installment_id').val(installmentId);
            $('#installment_amount').val(amount);
            $('#late_fee').val(lateFee);
            $('#total_amount').val(totalAmount.toFixed(2));
            
            $('#paymentModal').modal('show');
        });
        
        // Reminder modal
        $('.remind-btn').click(function(e) {
            e.stopPropagation();
            
            var installmentId = $(this).data('id');
            var customerName = $(this).data('customer');
            var phone = $(this).data('phone');
            var amount = $(this).data('amount');
            var daysOverdue = $(this).data('days-overdue');
            
            $('#reminder_installment_id').val(installmentId);
            $('#customer_name').val(customerName);
            $('#customer_phone').val(phone);
            
            // Generate message with placeholders
            var dueDate = new Date($(this).closest('tr').find('td:nth-child(6)').text().trim());
            var lateFee = $(this).closest('tr').find('td:nth-child(9)').text().replace('৳', '').trim();
            
            var message = `Dear ${customerName},\n\nThis is a reminder for your overdue installment payment.\n\nAmount Due: ৳${amount}\nDays Overdue: ${daysOverdue} days\nLate Fee: ৳${lateFee}\n\nPlease make the payment at your earliest convenience.\n\nThank you,\n{{ config('app.name') }}`;
            
            $('#reminder_message').val(message);
            $('#reminderModal').modal('show');
        });
        
        // Message template selector
        $('#message_template').change(function() {
            var template = $(this).val();
            var message = '';
            
            switch(template) {
                case 'friendly':
                    message = "Dear [Customer Name],\n\nWe hope this message finds you well. This is a friendly reminder that your installment payment is overdue.\n\nAmount Due: ৳[Amount]\nDue Date: [Due Date]\n\nPlease make the payment at your convenience.\n\nBest regards,\n{{ config('app.name') }}";
                    break;
                case 'urgent':
                    message = "URGENT: Payment Overdue\n\nDear [Customer Name],\n\nYour installment payment is now overdue. Immediate payment is required to avoid additional late fees.\n\nAmount Due: ৳[Amount]\nDays Overdue: [Days] days\nLate Fee: ৳[Late Fee]\n\nPlease make payment immediately.\n\n{{ config('app.name') }}";
                    break;
                case 'final':
                    message = "FINAL NOTICE: Payment Overdue\n\nDear [Customer Name],\n\nThis is the final reminder for your overdue installment. Failure to make payment may result in further action.\n\nTotal Due: ৳[Total Amount]\nDays Overdue: [Days] days\n\nContact us immediately to arrange payment.\n\n{{ config('app.name') }}";
                    break;
            }
            
            if(message) {
                $('#reminder_message').val(message);
            }
        });
        
        // Bulk Actions
        $('#bulkRemindBtn').click(function() {
            var selected = $('.row-checkbox:checked');
            if(selected.length === 0) {
                Swal.fire('Error', 'Please select at least one installment', 'error');
                return;
            }
            
            $('#sendBulkRemindersModal').modal('show');
        });
        
        $('#bulkPayBtn').click(function() {
            var selected = $('.row-checkbox:checked');
            if(selected.length === 0) {
                Swal.fire('Error', 'Please select at least one installment', 'error');
                return;
            }
            
            Swal.fire({
                title: 'Process Bulk Payments?',
                text: `You are about to process payments for ${selected.length} installment(s).`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Process',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Implement bulk payment processing
                    Swal.fire('Success', 'Bulk payments processed successfully', 'success');
                }
            });
        });
        
        $('#bulkWaiveBtn').click(function() {
            var selected = $('.row-checkbox:checked');
            if(selected.length === 0) {
                Swal.fire('Error', 'Please select at least one installment', 'error');
                return;
            }
            
            Swal.fire({
                title: 'Waive Late Fees?',
                text: `You are about to waive late fees for ${selected.length} installment(s).`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Waive',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Implement late fee waiver
                    Swal.fire('Success', 'Late fees waived successfully', 'success');
                }
            });
        });
        
        $('#bulkExportBtn').click(function() {
            var selected = $('.row-checkbox:checked');
            var ids = selected.map(function() {
                return $(this).val();
            }).get();
            
            if(ids.length === 0) {
                ids = $('.row-checkbox').map(function() {
                    return $(this).val();
                }).get();
            }
            
            // Export to CSV
            var csvContent = "data:text/csv;charset=utf-8,";
            csvContent += "Customer,Phone,Amount,Due Date,Days Overdue,Late Fee,Total Due\n";
            
            $('.overdue-row').each(function() {
                if(ids.includes($(this).data('id'))) {
                    var cols = $(this).find('td');
                    var customer = $(cols[2]).text().trim();
                    var phone = $(cols[2]).find('small').text().trim();
                    var amount = $(cols[5]).text().replace('৳', '').trim();
                    var dueDate = $(cols[6]).text().split('\n')[0].trim();
                    var daysOverdue = $(cols[7]).text().replace('days', '').trim();
                    var lateFee = $(cols[8]).text().replace('৳', '').trim();
                    var totalDue = $(cols[9]).text().replace('৳', '').trim();
                    
                    csvContent += `"${customer}","${phone}","${amount}","${dueDate}","${daysOverdue}","${lateFee}","${totalDue}"\n`;
                }
            });
            
            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "overdue_installments_" + new Date().toISOString().slice(0,10) + ".csv");
            document.body.appendChild(link);
            link.click();
        });
        
        // Form submissions
        $('#paymentForm').submit(function(e) {
            e.preventDefault();
            var form = $(this);
            var installmentId = $('#installment_id').val();
            
            $.ajax({
                url: '/installments/' + installmentId + '/pay',
                method: 'POST',
                data: form.serialize(),
                beforeSend: function() {
                    Swal.showLoading();
                },
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Payment Successful!',
                        text: response.message || 'Payment processed successfully',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Payment Failed',
                        text: xhr.responseJSON?.message || 'Something went wrong',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });
        
        $('#reminderForm').submit(function(e) {
            e.preventDefault();
            var form = $(this);
            var installmentId = $('#reminder_installment_id').val();
            
            $.ajax({
                url: '/installments/' + installmentId + '/remind',
                method: 'POST',
                data: form.serialize(),
                beforeSend: function() {
                    Swal.showLoading();
                },
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Reminder Sent!',
                        text: response.message || 'Reminder sent successfully',
                        confirmButtonText: 'OK'
                    });
                    $('#reminderModal').modal('hide');
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Failed to Send',
                        text: xhr.responseJSON?.message || 'Something went wrong',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });
    });
</script>
@endpush