@extends('admin.layouts.app')

@section('title', 'Payment Gateway Settings')

@section('content')
<div class="payment-gateways-settings">
    <!-- Header -->
    <div class="page-header">
        <h1>💳 Payment Gateway Management</h1>
        <p>Configure and manage payment gateways for your platform</p>
    </div>

    @if(session('success'))
        <div class="alert alert-success">
            ✅ {{ session('success') }}
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-error">
            ❌ {{ session('error') }}
        </div>
    @endif

    <!-- Statistics Overview -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon">💰</div>
            <div class="stat-content">
                <div class="stat-label">Total Revenue</div>
                <div class="stat-value">₹{{ number_format(array_sum(array_column($transactions, 'revenue')), 2) }}</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-label">Total Transactions</div>
                <div class="stat-value">{{ array_sum(array_column($transactions, 'transactions')) }}</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">✅</div>
            <div class="stat-content">
                <div class="stat-label">Active Gateways</div>
                <div class="stat-value">{{ count(array_filter($gateways, fn($g) => $g['enabled'])) }}/{{ count($gateways) }}</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">🔧</div>
            <div class="stat-content">
                <div class="stat-label">Configured</div>
                <div class="stat-value">{{ count(array_filter($gateways, fn($g) => $g['has_credentials'])) }}/{{ count($gateways) }}</div>
            </div>
        </div>
    </div>

    <!-- Payment Gateways Grid -->
    <div class="gateways-grid">
        @foreach($gateways as $key => $gateway)
            <div class="gateway-card {{ $gateway['enabled'] ? 'enabled' : 'disabled' }}">
                <!-- Gateway Header -->
                <div class="gateway-header">
                    <div class="gateway-info">
                        <div class="gateway-icon">
                            @if($key === 'stripe')
                                💳
                            @elseif($key === 'razorpay')
                                🎯
                            @elseif($key === 'phonepe')
                                📱
                            @elseif($key === 'paypal')
                                🅿️
                            @else
                                💰
                            @endif
                        </div>
                        <div>
                            <h3>{{ $gateway['name'] }}</h3>
                            <p class="gateway-description">{{ $gateway['description'] }}</p>
                        </div>
                    </div>
                    <div class="gateway-status">
                        <span class="status-badge {{ $gateway['enabled'] ? 'active' : 'inactive' }}">
                            {{ $gateway['enabled'] ? 'Active' : 'Inactive' }}
                        </span>
                    </div>
                </div>

                <!-- Gateway Details -->
                <div class="gateway-details">
                    <div class="detail-row">
                        <span class="detail-label">🌍 Coverage:</span>
                        <span class="detail-value">{{ $gateway['countries'] }}</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">💵 Transaction Fee:</span>
                        <span class="detail-value">{{ $gateway['fee'] }}</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">🔑 Credentials:</span>
                        <span class="detail-value {{ $gateway['has_credentials'] ? 'text-success' : 'text-danger' }}">
                            {{ $gateway['has_credentials'] ? '✅ Configured' : '❌ Not Configured' }}
                        </span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">🧪 Mode:</span>
                        <span class="detail-value">
                            {{ $gateway['test_mode'] ? '🔬 Test Mode' : '🚀 Live Mode' }}
                        </span>
                    </div>
                </div>

                <!-- Gateway Stats -->
                <div class="gateway-stats">
                    <div class="stat">
                        <div class="stat-label">Transactions</div>
                        <div class="stat-value">{{ $transactions[$key]['transactions'] ?? 0 }}</div>
                    </div>
                    <div class="stat">
                        <div class="stat-label">Revenue</div>
                        <div class="stat-value">₹{{ number_format($transactions[$key]['revenue'] ?? 0, 2) }}</div>
                    </div>
                </div>

                <!-- Gateway Actions -->
                <div class="gateway-actions">
                    <button class="btn btn-config" onclick="openConfigModal('{{ $key }}', '{{ $gateway['name'] }}')">
                        ⚙️ Configure
                    </button>
                    <button class="btn btn-test" onclick="testGateway('{{ $key }}')">
                        🧪 Test Connection
                    </button>
                    <button class="btn {{ $gateway['enabled'] ? 'btn-disable' : 'btn-enable' }}" 
                            onclick="toggleGateway('{{ $key }}', {{ $gateway['enabled'] ? 'false' : 'true' }})">
                        {{ $gateway['enabled'] ? '⏸️ Disable' : '▶️ Enable' }}
                    </button>
                </div>
            </div>
        @endforeach
    </div>

    <!-- Recommended Setup Guide -->
    <div class="setup-guide">
        <h2>📖 Quick Setup Guide</h2>
        <div class="guide-grid">
            <div class="guide-card">
                <h3>🇮🇳 For Indian Users</h3>
                <ol>
                    <li><strong>Razorpay</strong> - Primary (All payment methods)</li>
                    <li><strong>PhonePe</strong> - UPI Only (Lowest fees)</li>
                    <li><strong>Stripe</strong> - Backup (International cards)</li>
                </ol>
            </div>
            <div class="guide-card">
                <h3>🌍 For International Users</h3>
                <ol>
                    <li><strong>Stripe</strong> - Primary (Best global coverage)</li>
                    <li><strong>PayPal</strong> - Alternative (Trusted brand)</li>
                    <li><strong>Paystack</strong> - Expansion (Specific regions)</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Configuration Modal -->
<div id="configModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Configure Gateway</h2>
            <button class="modal-close" onclick="closeConfigModal()">✕</button>
        </div>
        <form id="configForm" method="POST">
            @csrf
            @method('PUT')
            <div class="modal-body">
                <div class="form-group">
                    <label for="api_key">API Key / Client ID</label>
                    <input type="text" name="api_key" id="api_key" class="form-control" placeholder="Enter API key">
                    <small>Your publishable/public key</small>
                </div>
                <div class="form-group">
                    <label for="api_secret">API Secret</label>
                    <input type="password" name="api_secret" id="api_secret" class="form-control" placeholder="Enter API secret">
                    <small>Your secret key (kept secure)</small>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="test_mode" value="1" checked>
                        Enable Test Mode
                    </label>
                    <small>Use sandbox/test environment</small>
                </div>
                <div class="form-group">
                    <label>
                        <input type="checkbox" name="enabled" value="1">
                        Enable Gateway
                    </label>
                    <small>Make this gateway available to users</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeConfigModal()">Cancel</button>
                <button type="submit" class="btn btn-primary">💾 Save Configuration</button>
            </div>
        </form>
    </div>
</div>

<style>
.payment-gateways-settings {
    padding: 20px;
    max-width: 1400px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 30px;
}

.page-header h1 {
    font-size: 32px;
    margin-bottom: 10px;
    color: #fff;
}

.page-header p {
    color: #aaa;
    font-size: 16px;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.3);
    color: #10b981;
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #ef4444;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-icon {
    font-size: 32px;
}

.stat-label {
    color: #aaa;
    font-size: 14px;
    margin-bottom: 5px;
}

.stat-value {
    color: #fff;
    font-size: 24px;
    font-weight: bold;
}

.gateways-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
    gap: 24px;
    margin-bottom: 40px;
}

.gateway-card {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 16px;
    padding: 24px;
    border: 2px solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
}

.gateway-card.enabled {
    border-color: rgba(16, 185, 129, 0.3);
    background: rgba(16, 185, 129, 0.05);
}

.gateway-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}

.gateway-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
}

.gateway-info {
    display: flex;
    gap: 15px;
}

.gateway-icon {
    font-size: 40px;
}

.gateway-info h3 {
    color: #fff;
    font-size: 20px;
    margin-bottom: 5px;
}

.gateway-description {
    color: #aaa;
    font-size: 13px;
}

.status-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: bold;
}

.status-badge.active {
    background: rgba(16, 185, 129, 0.2);
    color: #10b981;
}

.status-badge.inactive {
    background: rgba(107, 114, 128, 0.2);
    color: #9ca3af;
}

.gateway-details {
    margin-bottom: 20px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.detail-label {
    color: #aaa;
    font-size: 14px;
}

.detail-value {
    color: #fff;
    font-size: 14px;
    font-weight: 500;
}

.text-success {
    color: #10b981 !important;
}

.text-danger {
    color: #ef4444 !important;
}

.gateway-stats {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 20px;
    padding: 15px;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 8px;
}

.gateway-stats .stat {
    text-align: center;
}

.gateway-stats .stat-label {
    color: #aaa;
    font-size: 12px;
    margin-bottom: 5px;
}

.gateway-stats .stat-value {
    color: #fff;
    font-size: 18px;
    font-weight: bold;
}

.gateway-actions {
    display: flex;
    gap: 10px;
}

.btn {
    flex: 1;
    padding: 10px 16px;
    border: none;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}

.btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.btn-config {
    background: rgba(59, 130, 246, 0.2);
    color: #3b82f6;
    border: 1px solid rgba(59, 130, 246, 0.3);
}

.btn-test {
    background: rgba(245, 158, 11, 0.2);
    color: #f59e0b;
    border: 1px solid rgba(245, 158, 11, 0.3);
}

.btn-enable {
    background: rgba(16, 185, 129, 0.2);
    color: #10b981;
    border: 1px solid rgba(16, 185, 129, 0.3);
}

.btn-disable {
    background: rgba(239, 68, 68, 0.2);
    color: #ef4444;
    border: 1px solid rgba(239, 68, 68, 0.3);
}

.setup-guide {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 16px;
    padding: 30px;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.setup-guide h2 {
    color: #fff;
    margin-bottom: 20px;
}

.guide-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.guide-card {
    background: rgba(0, 0, 0, 0.2);
    padding: 20px;
    border-radius: 12px;
}

.guide-card h3 {
    color: #fff;
    margin-bottom: 15px;
}

.guide-card ol {
    color: #ddd;
    padding-left: 20px;
}

.guide-card li {
    margin-bottom: 10px;
}

.guide-card strong {
    color: #10b981;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: #1a1a2e;
    border-radius: 16px;
    width: 90%;
    max-width: 600px;
    max-height: 90vh;
    overflow-y: auto;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h2 {
    color: #fff;
    margin: 0;
}

.modal-close {
    background: none;
    border: none;
    color: #fff;
    font-size: 24px;
    cursor: pointer;
}

.modal-body {
    padding: 24px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    color: #fff;
    margin-bottom: 8px;
    font-weight: 500;
}

.form-control {
    width: 100%;
    padding: 12px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    color: #fff;
    font-size: 14px;
}

.form-control:focus {
    outline: none;
    border-color: #3b82f6;
}

.form-group small {
    color: #aaa;
    font-size: 12px;
    display: block;
    margin-top: 5px;
}

.modal-footer {
    padding: 24px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.btn-primary {
    background: #3b82f6;
    color: #fff;
}

.btn-secondary {
    background: rgba(255, 255, 255, 0.1);
    color: #fff;
}
</style>

<script>
let currentGateway = null;

function openConfigModal(gatewayKey, gatewayName) {
    currentGateway = gatewayKey;
    document.getElementById('modalTitle').textContent = `Configure ${gatewayName}`;
    document.getElementById('configForm').action = `/admin/payment-gateways/${gatewayKey}`;
    document.getElementById('configModal').style.display = 'flex';
}

function closeConfigModal() {
    document.getElementById('configModal').style.display = 'none';
    document.getElementById('configForm').reset();
}

async function testGateway(gateway) {
    try {
        const response = await fetch(`/admin/payment-gateways/${gateway}/test`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✅ Connection successful!');
        } else {
            alert('❌ ' + data.message);
        }
    } catch (error) {
        alert('❌ Connection failed: ' + error.message);
    }
}

async function toggleGateway(gateway, enabled) {
    const formData = new FormData();
    formData.append('_token', '{{ csrf_token() }}');
    formData.append('_method', 'PUT');
    formData.append('enabled', enabled ? '1' : '0');
    
    try {
        const response = await fetch(`/admin/payment-gateways/${gateway}`, {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            location.reload();
        }
    } catch (error) {
        alert('❌ Failed to update gateway: ' + error.message);
    }
}
</script>
@endsection
