@extends('layouts.app')

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

@section('actions')
    <a href="{{ route('installments.index') }}" class="btn btn-secondary">
        <i class="fas fa-arrow-left"></i> Back
    </a>
    @if($installment->status == 'pending')
    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#paymentModal">
        <i class="fas fa-money-bill-wave"></i> Process Payment
    </button>
    @endif
@endsection

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            @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
            
            <!-- Installment Details -->
            <div class="row">
                <!-- Left Column: Installment Info -->
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Installment Information</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Installment No:</strong> {{ $installment->installment_no }}/{{ $installment->total_installments }}</p>
                                    <p><strong>Amount:</strong> ৳{{ number_format($installment->amount, 2) }}</p>
                                    @if($installment->late_fee > 0)
                                    <p><strong>Late Fee:</strong> ৳{{ number_format($installment->late_fee, 2) }}</p>
                                    @endif
                                    <p><strong>Total Due:</strong> ৳{{ number_format($installment->amount + $installment->late_fee, 2) }}</p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Due Date:</strong> {{ $installment->due_date->format('d M, Y') }}</p>
                                    <p><strong>Status:</strong> 
                                        <span class="badge badge-{{ $installment->status == 'paid' ? 'success' : ($installment->is_overdue ? 'danger' : 'warning') }}">
                                            {{ strtoupper($installment->status) }}
                                            @if($installment->is_overdue)
                                            (Overdue)
                                            @endif
                                        </span>
                                    </p>
                                    @if($installment->paid_date)
                                    <p><strong>Paid Date:</strong> {{ $installment->paid_date->format('d M, Y') }}</p>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Customer Info -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Customer Information</h5>
                        </div>
                        <div class="card-body">
                            @if($installment->customer)
                            <p><strong>Name:</strong> {{ $installment->customer->name }}</p>
                            <p><strong>Phone:</strong> {{ $installment->customer->phone }}</p>
                            <p><strong>Email:</strong> {{ $installment->customer->email ?? 'N/A' }}</p>
                            <p><strong>Address:</strong> {{ $installment->customer->address ?? 'N/A' }}</p>
                            @else
                            <p class="text-muted">Customer information not available</p>
                            @endif
                        </div>
                    </div>
                </div>
                
                <!-- Right Column: Sale & Payment History -->
                <div class="col-md-6">
                    <!-- Sale Info -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Sale Information</h5>
                        </div>
                        <div class="card-body">
                            @if($installment->sale)
                            <p><strong>Invoice No:</strong> 
                                <a href="{{ route('sales.show', $installment->sale_id) }}" class="text-primary">
                                    {{ $installment->sale->invoice_number }}
                                </a>
                            </p>
                            <p><strong>Sale Date:</strong> {{ $installment->sale->sale_date->format('d M, Y') }}</p>
                            <p><strong>Total Amount:</strong> ৳{{ number_format($installment->sale->grand_total, 2) }}</p>
                            <p><strong>Down Payment:</strong> ৳{{ number_format($installment->sale->installment->down_payment ?? 0, 2) }}</p>
                            <p><strong>Remaining:</strong> ৳{{ number_format($installment->sale->installment->remaining_amount ?? 0, 2) }}</p>
                            @else
                            <p class="text-muted">Sale information not available</p>
                            @endif
                        </div>
                    </div>
                    
                    <!-- Payment History -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">Payment History</h5>
                        </div>
                        <div class="card-body">
                            @if($installment->payments->count() > 0)
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Amount</th>
                                            <th>Method</th>
                                            <th>Reference</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($installment->payments as $payment)
                                        <tr>
                                            <td>{{ $payment->payment_date->format('d M, Y') }}</td>
                                            <td class="text-success">৳{{ number_format($payment->amount, 2) }}</td>
                                            <td>{{ ucfirst($payment->payment_method) }}</td>
                                            <td>{{ $payment->reference_no ?? 'N/A' }}</td>
                                        </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                            @else
                            <p class="text-muted">No payment history available</p>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Installment Schedule -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Installment Schedule</h5>
                </div>
                <div class="card-body">
                    @php
                        $installmentsList = $installment->sale->installments ?? collect();
                    @endphp
                    
                    @if($installmentsList->count() > 0)
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Due Date</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Paid Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($installmentsList as $inst)
                                <tr class="{{ $inst->id == $installment->id ? 'table-primary' : '' }}">
                                    <td>{{ $inst->installment_no }}/{{ $inst->total_installments }}</td>
                                    <td>{{ $inst->due_date->format('d M, Y') }}</td>
                                    <td>৳{{ number_format($inst->amount, 2) }}</td>
                                    <td>
                                        <span class="badge badge-{{ $inst->status == 'paid' ? 'success' : ($inst->is_overdue ? 'danger' : 'warning') }}">
                                            {{ strtoupper($inst->status) }}
                                        </span>
                                    </td>
                                    <td>
                                        @if($inst->paid_date)
                                        {{ $inst->paid_date->format('d M, Y') }}
                                        @else
                                        <span class="text-muted">Not Paid</span>
                                        @endif
                                    </td>
                                    <td>
                                        <a href="{{ route('installments.show', $inst->id) }}" 
                                           class="btn btn-sm btn-info" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        @if($inst->status == 'pending')
                                        <a href="{{ route('installments.pay', $inst->id) }}" 
                                           class="btn btn-sm btn-success" title="Pay">
                                            <i class="fas fa-money-bill-wave"></i>
                                        </a>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    @else
                    <p class="text-muted">No installment schedule available</p>
                    @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 for Installment #{{ $installment->installment_no }}</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.process-payment', $installment) }}">
                @csrf
                <div class="modal-body">
                    <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" 
                               value="{{ $installment->amount + $installment->late_fee }}" required>
                        <small class="text-muted">
                            Installment: ৳{{ number_format($installment->amount, 2) }}
                            @if($installment->late_fee > 0)
                            + Late Fee: ৳{{ number_format($installment->late_fee, 2) }}
                            @endif
                        </small>
                    </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>
@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // Auto-calculate late fee if applicable
        $('#payment_date').change(function() {
            var dueDate = new Date('{{ $installment->due_date->format("Y-m-d") }}');
            var paymentDate = new Date($(this).val());
            
            if (paymentDate > dueDate) {
                // Calculate late fee (you can adjust the calculation logic)
                var daysLate = Math.ceil((paymentDate - dueDate) / (1000 * 60 * 60 * 24));
                var lateFee = Math.max(0, daysLate * 100); // Example: 100 per day late fee
                
                var totalAmount = {{ $installment->amount }} + lateFee;
                $('#amount').val(totalAmount.toFixed(2));
            }
        });
    });
</script>
@endpush