@extends('FrontUser.layouts.app')

@section('title', 'Wallet Balance')

@section('content')
<div class="wallet-dashboard">
    <!-- Wallet Header -->
    <div class="wallet-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="wallet-title">Wallet Balance</h2>
                <p class="wallet-subtitle">Manage your funds and transactions</p>
            </div>
            <div class="wallet-actions">
                <button class="btn btn-primary me-2" onclick="showAddFundsModal()">
                    <i class="fas fa-plus"></i> + Recharge Wallet
                </button>
                <button class="btn btn-outline-primary" onclick="showWithdrawModal()">
                    <i class="fas fa-minus"></i> Withdraw
                </button>
            </div>
        </div>
    </div>

    <!-- Wallet Balance Section -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="card wallet-balance-card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="wallet-info">
                            <h3 class="wallet-balance-title">Wallet Balance</h3>
                            <div class="wallet-balance-amount">₹{{ number_format($currentBalance, 2) }}</div>
                            <div class="wallet-last-recharge">
                                Last recharge: {{ $lastTransaction && $lastTransaction->created_at ? '₹' . number_format($lastTransaction->amount, 2) . ' on ' . $lastTransaction->created_at->format('M d, Y') : '—' }}
                            </div>
                        </div>
                        <div class="wallet-action">
                            <button class="btn btn-primary btn-lg" onclick="showAddFundsModal()">
                                <i class="fas fa-plus"></i> + Recharge Wallet
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-body text-center">
                    <h6 class="card-title">Quick Stats</h6>
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="stat-item">
                                <div class="stat-value">{{ number_format($totalCalls) }}</div>
                                <div class="stat-label">Total Calls</div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="stat-item">
                                <div class="stat-value">₹{{ number_format($totalSpent, 1) }}</div>
                                <div class="stat-label">Money Used</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Usage Statistics -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card stat-card">
                <div class="card-body text-center">
                    <div class="stat-icon bg-primary">
                        <i class="fas fa-phone text-white"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-title">Total Calls</div>
                        <div class="stat-value">{{ number_format($totalCalls) }}</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stat-card">
                <div class="card-body text-center">
                    <div class="stat-icon bg-info">
                        <i class="fas fa-clock text-white"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-title">Total Duration</div>
                        <div class="stat-value">0</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card stat-card">
                <div class="card-body text-center">
                    <div class="stat-icon bg-warning">
                        <i class="fas fa-rupee-sign text-white"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-title">Money Used</div>
                        <div class="stat-value">₹{{ number_format($totalSpent, 1) }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="quick-action" onclick="showAddFundsModal()">
                                <div class="action-icon">
                                    <i class="fas fa-plus"></i>
                                </div>
                                <div class="action-content">
                                    <h6>Add Funds</h6>
                                    <p>Top up your wallet</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="quick-action" onclick="showWithdrawModal()">
                                <div class="action-icon">
                                    <i class="fas fa-minus"></i>
                                </div>
                                <div class="action-content">
                                    <h6>Withdraw</h6>
                                    <p>Transfer to bank</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="quick-action" onclick="showTransactionHistory()">
                                <div class="action-icon">
                                    <i class="fas fa-history"></i>
                                </div>
                                <div class="action-content">
                                    <h6>Transaction History</h6>
                                    <p>View all transactions</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="quick-action" onclick="showPaymentMethods()">
                                <div class="action-icon">
                                    <i class="fas fa-credit-card"></i>
                                </div>
                                <div class="action-content">
                                    <h6>Payment Methods</h6>
                                    <p>Manage payment options</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Transactions -->
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title">Recent Transactions</h5>
                    <a href="{{ route('user.wallet.transactions') }}" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body">
                    @if($recentTransactions->count() > 0)
                        <div class="transaction-list">
                            @foreach($recentTransactions as $transaction)
                            <div class="transaction-item">
                                <div class="transaction-icon">
                                    <i class="fas {{ $transaction->type === 'credit' ? 'fa-arrow-down text-success' : 'fa-arrow-up text-danger' }}"></i>
                                </div>
                                <div class="transaction-details">
                                    <div class="transaction-description">{{ $transaction->description }}</div>
                                    <div class="transaction-meta">
                                        <span class="transaction-date">{{ $transaction->created_at->format('M d, Y h:i A') }}</span>
                                        <span class="transaction-method">{{ ucfirst($transaction->payment_method ?? 'N/A') }}</span>
                                    </div>
                                </div>
                                <div class="transaction-amount">
                                    <span class="amount {{ $transaction->type === 'credit' ? 'text-success' : 'text-danger' }}">
                                        {{ $transaction->type === 'credit' ? '+' : '-' }}₹{{ number_format($transaction->amount, 2) }}
                                    </span>
                                    <span class="status-badge status-{{ $transaction->status }}">
                                        {{ ucfirst($transaction->status) }}
                                    </span>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    @else
                        <div class="empty-state">
                            <i class="fas fa-receipt"></i>
                            <h6>No transactions yet</h6>
                            <p>Your transaction history will appear here</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Wallet Insights</h5>
                </div>
                <div class="card-body">
                    <div class="insight-item">
                        <div class="insight-label">Average Monthly Spending</div>
                        <div class="insight-value">₹{{ number_format($thisMonthSpent, 2) }}</div>
                    </div>
                    <div class="insight-item">
                        <div class="insight-label">Most Used Payment Method</div>
                        <div class="insight-value">{{ ucfirst($lastTransaction->payment_method ?? 'N/A') }}</div>
                    </div>
                    <div class="insight-item">
                        <div class="insight-label">Last Transaction</div>
                        <div class="insight-value">
                            {{ $lastTransaction && $lastTransaction->created_at ? $lastTransaction->created_at->diffForHumans() : 'Never' }}
                        </div>
                    </div>
                    <div class="insight-item">
                        <div class="insight-label">Wallet Health</div>
                        <div class="insight-value">
                            <span class="health-indicator {{ $currentBalance > 1000 ? 'healthy' : ($currentBalance > 500 ? 'warning' : 'low') }}">
                                {{ $currentBalance > 1000 ? 'Healthy' : ($currentBalance > 500 ? 'Low' : 'Critical') }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Funds Modal -->
<div class="modal fade" id="addFundsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Funds to Wallet</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addFundsForm">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Amount</label>
                                <div class="input-group">
                                    <span class="input-group-text">₹</span>
                                    <input type="number" class="form-control" name="amount" placeholder="Enter amount" min="100" max="100000" required>
                                </div>
                                <small class="form-text">Minimum: ₹100, Maximum: ₹1,00,000</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">Quick Amounts</label>
                                <div class="quick-amounts">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setAmount(500)">₹500</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setAmount(1000)">₹1,000</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setAmount(2500)">₹2,500</button>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setAmount(5000)">₹5,000</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Method</label>
                        <div class="payment-methods" id="paymentMethods">
                            <!-- Payment methods will be loaded here -->
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="savePaymentMethod">
                            <label class="form-check-label" for="savePaymentMethod">
                                Save this payment method for future use
                            </label>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-lock"></i> Proceed to Payment
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Withdraw Modal -->
<div class="modal fade" id="withdrawModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Withdraw Funds</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="withdrawForm">
                    @csrf
                    <div class="form-group">
                        <label class="form-label">Withdrawal Amount</label>
                        <div class="input-group">
                            <span class="input-group-text">₹</span>
                            <input type="number" class="form-control" name="amount" placeholder="Enter amount" min="100" max="50000" required>
                        </div>
                        <small class="form-text">Available Balance: ₹{{ number_format($currentBalance, 2) }}</small>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Bank Account Number</label>
                        <input type="text" class="form-control" name="bank_account" placeholder="Enter bank account number" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Account Holder Name</label>
                        <input type="text" class="form-control" name="account_holder" value="{{ Auth::user()->name }}" readonly>
                    </div>
                    
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        <strong>Processing Time:</strong> 1-2 business days<br>
                        <strong>Processing Fee:</strong> Free
                    </div>
                    
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-paper-plane"></i> Submit Withdrawal Request
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Payment Methods Modal -->
<div class="modal fade" id="paymentMethodsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Payment Methods</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="payment-methods-list" id="paymentMethodsList">
                    <!-- Payment methods will be loaded here -->
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('styles')
<style>
.wallet-balance-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.wallet-balance-title {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.wallet-balance-amount {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
}

.wallet-last-recharge {
    font-size: 0.9rem;
    opacity: 0.8;
}

.stat-card {
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    transition: transform 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1rem;
    font-size: 1.5rem;
}

.stat-title {
    font-size: 0.9rem;
    color: #6c757d;
    margin-bottom: 0.5rem;
}

.stat-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #2c3e50;
}

.quick-action {
    padding: 1.5rem;
    border: 2px dashed #e9ecef;
    border-radius: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.quick-action:hover {
    border-color: #007bff;
    background: #e3f2fd;
    transform: translateY(-2px);
}

.action-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #007bff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1rem;
    font-size: 1.2rem;
}

.action-content h6 {
    margin-bottom: 0.5rem;
    font-weight: 600;
}

.action-content p {
    margin: 0;
    color: #6c757d;
    font-size: 0.9rem;
}

.transaction-item {
    display: flex;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 1px solid #f1f3f4;
}

.transaction-item:last-child {
    border-bottom: none;
}

.transaction-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    background: #f8f9fa;
}

.transaction-details {
    flex: 1;
}

.transaction-description {
    font-weight: 500;
    margin-bottom: 0.25rem;
}

.transaction-meta {
    font-size: 0.85rem;
    color: #6c757d;
}

.transaction-amount {
    text-align: right;
}

.amount {
    font-weight: 600;
    font-size: 1.1rem;
}

.status-badge {
    display: inline-block;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.75rem;
    font-weight: 500;
    margin-top: 0.25rem;
}

.status-completed {
    background: #d4edda;
    color: #155724;
}

.status-pending {
    background: #fff3cd;
    color: #856404;
}

.status-failed {
    background: #f8d7da;
    color: #721c24;
}

.payment-method {
    display: flex;
    align-items: center;
    padding: 1rem;
    border: 2px solid #e9ecef;
    border-radius: 10px;
    margin-bottom: 0.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.payment-method:hover {
    border-color: #007bff;
    background: #f8f9fa;
}

.payment-method input[type="radio"] {
    margin-right: 1rem;
}

.method-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f8f9fa;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    color: #007bff;
}

.method-details {
    flex: 1;
}

.method-name {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.method-description {
    font-size: 0.9rem;
    color: #6c757d;
    margin-bottom: 0.25rem;
}

.method-fee {
    font-size: 0.8rem;
    color: #28a745;
}

.empty-state {
    text-align: center;
    padding: 3rem 1rem;
    color: #6c757d;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.health-indicator {
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    font-size: 0.8rem;
    font-weight: 500;
}

.health-indicator.healthy {
    background: #d4edda;
    color: #155724;
}

.health-indicator.warning {
    background: #fff3cd;
    color: #856404;
}

.health-indicator.low {
    background: #f8d7da;
    color: #721c24;
}

.insight-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 0;
    border-bottom: 1px solid #f1f3f4;
}

.insight-item:last-child {
    border-bottom: none;
}

.insight-label {
    color: #6c757d;
    font-size: 0.9rem;
}

.insight-value {
    font-weight: 600;
    color: #2c3e50;
}
</style>
@endsection

@section('scripts')
<script>
// Load payment methods
function loadPaymentMethods() {
    fetch('/wallet/payment-methods')
        .then(response => response.json())
        .then(data => {
            const container = document.getElementById('paymentMethods');
            container.innerHTML = '';
            
            data.methods.forEach(method => {
                const methodElement = document.createElement('div');
                methodElement.className = 'payment-method';
                methodElement.innerHTML = `
                    <input type="radio" name="payment_method" value="${method.id}" id="method_${method.id}" required>
                    <label for="method_${method.id}">
                        <div class="method-icon">
                            <i class="${method.icon}"></i>
                        </div>
                        <div class="method-details">
                            <div class="method-name">${method.name}</div>
                            <div class="method-description">${method.description}</div>
                            <div class="method-fee">Fee: ${method.processing_fee} • ${method.processing_time}</div>
                        </div>
                    </label>
                `;
                container.appendChild(methodElement);
            });
        });
}

// Set amount in form
function setAmount(amount) {
    document.querySelector('input[name="amount"]').value = amount;
}

// Show add funds modal
function showAddFundsModal() {
    loadPaymentMethods();
    new bootstrap.Modal(document.getElementById('addFundsModal')).show();
}

// Show withdraw modal
function showWithdrawModal() {
    new bootstrap.Modal(document.getElementById('withdrawModal')).show();
}

// Show transaction history
function showTransactionHistory() {
    window.location.href = '{{ route("user.wallet.transactions") }}';
}

// Show payment methods
function showPaymentMethods() {
    loadPaymentMethods();
    document.getElementById('paymentMethodsList').innerHTML = document.getElementById('paymentMethods').innerHTML;
    new bootstrap.Modal(document.getElementById('paymentMethodsModal')).show();
}

// Add funds form submission
document.getElementById('addFundsForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    submitBtn.disabled = true;
    
    fetch('/wallet/add-funds', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('addFundsModal')).hide();
            location.reload();
        } else {
            showNotification('error', data.message);
        }
    })
    .catch(error => {
        showNotification('error', 'An error occurred. Please try again.');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Withdraw form submission
document.getElementById('withdrawForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    submitBtn.disabled = true;
    
    fetch('/wallet/withdraw', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('success', data.message);
            bootstrap.Modal.getInstance(document.getElementById('withdrawModal')).hide();
            location.reload();
        } else {
            showNotification('error', data.message);
        }
    })
    .catch(error => {
        showNotification('error', 'An error occurred. Please try again.');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});

// Show notification
function showNotification(type, message) {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'success' ? 'success' : 'danger'} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.remove();
    }, 5000);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('Wallet dashboard loaded successfully!');
    
    // Animate stat cards
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        setTimeout(() => {
            card.style.transition = 'all 0.6s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });
});
</script>
@endsection