@extends('member.layout')

@section('title', 'My Savings')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-piggy-bank mr-2"></i>My Savings Accounts
                    </h3>
                    <div class="card-tools">
                        <span class="badge badge-success">Savings Management</span>
                    </div>
                </div>

                <div class="card-body">
                    <div class="row">
                        <!-- Left Column: Savings Summary -->
                        <div class="col-md-4">
                            <div class="border-right pr-4">
                                <h5 class="text-success mb-3">
                                    <i class="fas fa-chart-bar mr-2"></i>Savings Summary
                                </h5>

                                <div class="row mb-3">
                                    <div class="col-12">
                                        <div class="form-group mb-2">
                                            <label class="form-label small">Total Accounts</label>
                                            <input type="text" value="{{ $savings->count() }}" class="form-control form-control-sm bg-light" readonly>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-6">
                                        <div class="form-group mb-2">
                                            <label class="form-label small">Active</label>
                                            <input type="text" value="{{ $savings->where('status', 'active')->count() }}" class="form-control form-control-sm bg-light" readonly>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="form-group mb-2">
                                            <label class="form-label small">Inactive</label>
                                            <input type="text" value="{{ $savings->where('status', '!=', 'active')->count() }}" class="form-control form-control-sm bg-light" readonly>
                                        </div>
                                    </div>
                                </div>

                                <div class="row mb-3">
                                    <div class="col-12">
                                        <div class="form-group mb-2">
                                            <label class="form-label small">Total Balance</label>
                                            <input type="text" value="KSh {{ number_format($savings->sum('amount'), 2) }}" class="form-control form-control-sm bg-light" readonly>
                                        </div>
                                    </div>
                                </div>

                                <!-- Open Account Button -->
                                <div class="mt-4">
                                    <a href="{{ route('member.savings.create') }}" class="btn btn-success btn-block">
                                        <i class="fas fa-plus mr-1"></i>Open New Account
                                    </a>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: Savings Accounts List -->
                        <div class="col-md-8">
                            <div class="pl-4">
                                <h5 class="text-info mb-3">
                                    <i class="fas fa-list mr-2"></i>My Savings Accounts
                                </h5>

                                @if($savings->count() > 0)
                                    <div class="row">
                                        @foreach($savings as $saving)
                                        <div class="col-xl-6 col-lg-12 col-md-12 col-12 mb-3">
                                            <div class="card h-100 border-left-success">
                                                <div class="card-body p-3">
                                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                                        <div>
                                                            <h6 class="card-title mb-1 text-success font-weight-bold capitalize">
                                                                {{ $saving->type }} Account
                                                            </h6>
                                                            <small class="text-muted">Account #{{ $saving->id }}</small>
                                                        </div>
                                                        <span class="badge
                                                            @if($saving->status === 'active') badge-success
                                                            @else badge-secondary @endif">
                                                            {{ ucfirst($saving->status) }}
                                                        </span>
                                                    </div>

                                                    <div class="row text-center mb-2">
                                                        <div class="col-12">
                                                            <small class="text-muted d-block">Current Balance</small>
                                                            <div class="font-weight-bold text-success">KSh {{ number_format($saving->amount, 2) }}</div>
                                                        </div>
                                                    </div>

                                                    @if($saving->type === 'fixed' && $saving->maturity_date)
                                                    <div class="mb-2">
                                                        <small class="text-muted d-block">Maturity Date</small>
                                                        <div class="font-weight-bold text-primary small">{{ $saving->maturity_date->format('M d, Y') }}</div>
                                                    </div>
                                                    @endif

                                                    <div class="d-flex justify-content-between mt-3">
                                                        <a href="{{ route('member.savings.show', $saving) }}" class="btn btn-outline-success btn-sm">
                                                            <i class="fas fa-eye"></i> View
                                                        </a>
                                                        @if($saving->status === 'active')
                                                        <button onclick="depositToAccount({{ $saving->id }})" class="btn btn-success btn-sm">
                                                            <i class="fas fa-plus"></i> Deposit
                                                        </button>
                                                        @endif
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        @endforeach
                                    </div>

                                    <!-- Pagination -->
                                    <div class="d-flex justify-content-center mt-3">
                                        {{ $savings->links() }}
                                    </div>
                                @else
                                    <!-- Empty State -->
                                    <div class="text-center py-5">
                                        <i class="fas fa-piggy-bank fa-3x text-muted mb-3"></i>
                                        <h5 class="text-muted mb-2">No Savings Accounts Yet</h5>
                                        <p class="text-muted mb-3">You haven't opened any savings accounts yet. Start saving with us!</p>
                                        <a href="{{ route('member.savings.create') }}" class="btn btn-success">
                                            <i class="fas fa-plus mr-2"></i>Open Your First Account
                                        </a>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Deposit Modal -->
<div class="modal fade" id="depositModal" tabindex="-1" role="dialog" aria-labelledby="depositModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="depositModalLabel">
                    <i class="fas fa-plus mr-2"></i>Make Deposit
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <form id="depositForm" onsubmit="submitDeposit(event)">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label for="deposit_amount" class="form-label">Deposit Amount (KSh)</label>
                        <input type="number" id="deposit_amount" name="amount" min="100" step="0.01"
                               class="form-control" placeholder="Enter deposit amount" required>
                        <small class="form-text text-muted">Minimum deposit: KSh 100</small>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Cancel
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-paper-plane mr-1"></i>Send M-Pesa Request
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('js')
<script>
let currentSavingId = null;

function depositToAccount(savingId) {
    currentSavingId = savingId;
    $('#deposit_amount').val(''); // Clear previous value
    $('#depositModal').modal('show');
}

function submitDeposit(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    formData.append('saving_id', currentSavingId);

    $.ajax({
        url: `{{ url('member/savings') }}/${currentSavingId}/deposit`,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Deposit Initiated!',
                    text: 'Please check your phone and complete the M-Pesa payment.',
                    timer: 3000,
                    showConfirmButton: false
                });
                $('#depositModal').modal('hide');
                $('#depositForm')[0].reset();
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Deposit Failed',
                    text: data.message
                });
            }
        },
        error: function(xhr, status, error) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while processing your deposit.'
            });
        }
    });
}

// Reset form when modal is hidden
$('#depositModal').on('hidden.bs.modal', function() {
    $('#depositForm')[0].reset();
    currentSavingId = null;
});
</script>
@endpush
@endsection
