@extends('layouts.app')

@section('title', 'Installment Management')

@section('actions')
    <a href="{{ route('sales.create') }}" class="btn btn-primary">
        <i class="fas fa-plus"></i> New Sale
    </a>
@endsection

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

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-left-primary 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-primary text-uppercase mb-1">
                                Total Installments
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($stats['total_installments'] ?? 0) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-md-6 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">
                                Total Amount
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($stats['total_amount'] ?? 0, 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-lg-3 col-md-6 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">
                                Pending Installments
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($stats['total_pending'] ?? 0) }}
                            </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-lg-3 col-md-6 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">
                                Overdue Installments
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($stats['total_overdue'] ?? 0) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs Navigation -->
    <div class="row">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header bg-white py-3">
                    <ul class="nav nav-tabs card-header-tabs" id="installmentTabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="all-tab" data-toggle="tab" href="#all" role="tab">
                                All Installments
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="pending-tab" data-toggle="tab" href="#pending" role="tab">
                                Pending <span class="badge badge-warning">{{ $stats['total_pending'] ?? 0 }}</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="overdue-tab" data-toggle="tab" href="#overdue" role="tab">
                                Overdue <span class="badge badge-danger">{{ $stats['total_overdue'] ?? 0 }}</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="this-month-tab" data-toggle="tab" href="#this-month" role="tab">
                                Due This Month <span class="badge badge-info">{{ $stats['total_due_this_month'] ?? 0 }}</span>
                            </a>
                        </li>
                    </ul>
                </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

                    <!-- Filter Form -->
                    <form method="GET" action="{{ route('installments.index') }}" class="row mb-4 g-2">
                        <div class="col-md-3 col-6 mb-2">
                            <input type="date" name="start_date" class="form-control form-control-sm" 
                                   value="{{ request('start_date') }}" placeholder="From Date">
                        </div>
                        <div class="col-md-3 col-6 mb-2">
                            <input type="date" name="end_date" class="form-control form-control-sm" 
                                   value="{{ request('end_date') }}" placeholder="To Date">
                        </div>
                        <div class="col-md-3 col-6 mb-2">
                            <input type="text" name="search" class="form-control form-control-sm" 
                                   value="{{ request('search') }}" placeholder="Search customer...">
                        </div>
                        <div class="col-md-1 col-3 mb-2">
                            <button type="submit" class="btn btn-primary btn-sm btn-block">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <button type="submit" class="btn btn-primary btn-sm btn-block">
                                <i class="fas fa-filter"></i> Filter
                            </button>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <a href="{{ route('installments.index') }}" class="btn btn-secondary btn-sm btn-block">
                                <i class="fas fa-redo"></i> Clear
                            </a>
                        </div>
                    </form>

                    <!-- Tab Content -->
                    <div class="tab-content" id="installmentTabsContent">
                        <!-- All Installments Tab -->
                        <div class="tab-pane fade show active" id="all" role="tabpanel">
                            @include('installments.partials.installment-table', ['installments' => $installments])
                        </div>
                        
                        <!-- Pending Tab -->
                        <div class="tab-pane fade" id="pending" role="tabpanel">
                            @php
                                $pendingInstallments = $installments->filter(function($installment) {
                                    return $installment->status == 'pending';
                                });
                            @endphp
                            @include('installments.partials.installment-table', ['installments' => $pendingInstallments])
                        </div>
                        
                        <!-- Overdue Tab -->
                        <div class="tab-pane fade" id="overdue" role="tabpanel">
                            @php
                                $overdueInstallments = $installments->filter(function($installment) {
                                    return $installment->is_overdue;
                                });
                            @endphp
                            @include('installments.partials.installment-table', ['installments' => $overdueInstallments])
                        </div>
                        
                        <!-- Due This Month Tab -->
                        <div class="tab-pane fade" id="this-month" role="tabpanel">
                            @php
                                $dueThisMonth = $installments->filter(function($installment) {
                                    return $installment->due_date->isCurrentMonth() && 
                                           $installment->status == 'pending';
                                });
                            @endphp
                            @include('installments.partials.installment-table', ['installments' => $dueThisMonth])
                        </div>
                    </div>
                </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">Amount (৳)</label>
                        <input type="number" name="amount" id="amount" 
                               class="form-control" step="0.01" min="0" required>
                    </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="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="message">Message</label>
                        <textarea name="message" id="message" class="form-control" rows="5" required>
Dear customer, this is a reminder for your installment payment. Please make the payment by the due date to avoid late fees.

Installment Amount: ৳[amount]
Due Date: [due_date]
Reference: [installment_no]

Thank you,
{{ config('app.name') }}
                        </textarea>
                        <small class="text-muted">Use [amount], [due_date], [installment_no] as placeholders</small>
                    </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>
@endsection

@push('styles')
<style>
    .nav-tabs .nav-link {
        border: none;
        color: #6c757d;
        font-weight: 500;
    }
    
    .nav-tabs .nav-link.active {
        color: #495057;
        background-color: #fff;
        border-bottom: 3px solid #4e73df;
    }
    
    .installment-row:hover {
        background-color: #f8f9fa;
        cursor: pointer;
    }
    
    .badge {
        font-size: 0.75rem;
        padding: 0.35em 0.65em;
    }
    
    .overdue {
        background-color: #fff8e1 !important;
        border-left: 4px solid #ffc107;
    }
    
    .due-soon {
        background-color: #e8f4fd !important;
        border-left: 4px solid #17a2b8;
    }
    
    .paid {
        background-color: #e7f7ef !important;
        border-left: 4px solid #28a745;
    }
    
    .payment-btn {
        min-width: 100px;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        // Initialize tabs
        $('#installmentTabs a').on('click', function (e) {
            e.preventDefault();
            $(this).tab('show');
        });
        
        // Open payment modal
        $('.pay-btn').click(function(e) {
            e.stopPropagation();
            
            var installmentId = $(this).data('id');
            var amount = $(this).data('amount');
            var dueAmount = $(this).data('due-amount');
            
            $('#installment_id').val(installmentId);
            $('#amount').val(dueAmount || amount);
            $('#paymentModal').modal('show');
        });
        
        // Open reminder modal
        $('.remind-btn').click(function(e) {
            e.stopPropagation();
            
            var installmentId = $(this).data('id');
            var amount = $(this).data('amount');
            var dueDate = $(this).data('due-date');
            var installmentNo = $(this).data('installment-no');
            
            $('#reminder_installment_id').val(installmentId);
            
            // Replace placeholders in message
            var message = $('#message').val();
            message = message.replace('[amount]', amount);
            message = message.replace('[due_date]', dueDate);
            message = message.replace('[installment_no]', installmentNo);
            $('#message').val(message);
            
            $('#reminderModal').modal('show');
        });
        
        // View installment details
        $('.installment-row').click(function() {
            var installmentId = $(this).data('id');
            window.location.href = '/installments/' + installmentId;
        });
        
        // Payment form submission
        $('#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() {
                    $('#paymentModal').modal('hide');
                    Swal.fire({
                        title: 'Processing...',
                        text: 'Please wait while we process your payment',
                        allowOutsideClick: false,
                        didOpen: () => {
                            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'
                    });
                }
            });
        });
        
        // Reminder form submission
        $('#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() {
                    $('#reminderModal').modal('hide');
                    Swal.fire({
                        title: 'Sending...',
                        text: 'Please wait while we send the reminder',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                },
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Reminder Sent!',
                        text: response.message || 'Reminder sent successfully',
                        confirmButtonText: 'OK'
                    });
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Failed to Send',
                        text: xhr.responseJSON?.message || 'Something went wrong',
                        confirmButtonText: 'OK'
                    });
                }
            });
        });
        
        // Auto-submit form on date change
        $('input[name="start_date"], input[name="end_date"]').change(function() {
            if ($(this).val()) {
                $(this).closest('form').submit();
            }
        });
    });
</script>
@endpush