@extends('layouts.admin')

@section('title', 'Subscription Reports')

@section('admin-content')
<!-- Page Header -->
<div class="page-header">
    <div>
        <h3 class="page-title">Subscription Reports</h3>
        <p class="text-muted mb-0">Monitor subscriptions, usage, and revenue</p>
    </div>
</div>

<!-- Stats Overview -->
<div class="row g-3 mb-4">
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm bg-primary text-white h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="fw-bold mb-0 text-white">{{ $stats['total_active'] }}</h3>
                        <small class="opacity-75">Paid Subscriptions</small>
                    </div>
                    <i class="bi bi-gem fs-1 opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm bg-secondary text-white h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="fw-bold mb-0 text-white">{{ $stats['total_sellers'] }}</h3>
                        <small class="opacity-75">Total Sellers</small>
                    </div>
                    <i class="bi bi-shop fs-1 opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm bg-success text-white h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="fw-bold mb-0 text-white">₹{{ number_format($stats['total_revenue_inr']) }}</h3>
                        <small class="opacity-75">Revenue (INR)</small>
                    </div>
                    <i class="bi bi-currency-rupee fs-1 opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm bg-info text-white h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h3 class="fw-bold mb-0 text-white">${{ number_format($stats['total_revenue_usd']) }}</h3>
                        <small class="opacity-75">Revenue (USD)</small>
                    </div>
                    <i class="bi bi-currency-dollar fs-1 opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
</div>

@if($stats['pending_approvals'] > 0)
<!-- Pending Approvals -->
<div class="card border-warning mb-4">
    <div class="card-header bg-warning bg-opacity-10 border-warning">
        <h6 class="mb-0 fw-bold text-warning">
            <i class="bi bi-hourglass-split me-2"></i>Pending Manual Approvals ({{ $stats['pending_approvals'] }})
        </h6>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Seller</th>
                        <th>Plan</th>
                        <th>Amount</th>
                        <th>Date</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($pendingApprovals as $payment)
                    <tr>
                        <td>
                            <strong>{{ $payment->seller->company_name ?? 'N/A' }}</strong>
                            <small class="d-block text-muted">{{ $payment->seller->user->email ?? '' }}</small>
                        </td>
                        <td>
                            @php $planData = is_array($payment->metadata) ? $payment->metadata : json_decode($payment->metadata, true); @endphp
                            {{ $planData['plan_name'] ?? 'Unknown' }}
                        </td>
                        <td class="fw-bold">{{ $payment->currency == 'INR' ? '₹' : '$' }}{{ number_format($payment->total_amount, 2) }}</td>
                        <td>{{ $payment->created_at->format('M d, Y') }}</td>
                        <td class="text-end">
                            <form action="{{ route('admin.subscriptions.approve', $payment) }}" method="POST" class="d-inline">
                                @csrf
                                <button type="submit" class="btn btn-sm btn-success" onclick="return confirm('Approve?')">
                                    <i class="bi bi-check-lg"></i>
                                </button>
                            </form>
                            <form action="{{ route('admin.subscriptions.reject', $payment) }}" method="POST" class="d-inline">
                                @csrf
                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Reject?')">
                                    <i class="bi bi-x-lg"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>
@endif

<!-- Tabs -->
<ul class="nav nav-tabs mb-0" id="reportTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active fw-bold" id="active-tab" data-bs-toggle="tab" data-bs-target="#activeSubscriptions" type="button">
            <i class="bi bi-gem me-1"></i>Active Subscriptions <span class="badge bg-primary ms-1">{{ $stats['total_active'] }}</span>
        </button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link fw-bold" id="all-tab" data-bs-toggle="tab" data-bs-target="#allSellers" type="button">
            <i class="bi bi-people me-1"></i>All Sellers <span class="badge bg-secondary ms-1">{{ $stats['total_sellers'] }}</span>
        </button>
    </li>
</ul>

<div class="tab-content">
    <!-- Tab 1: Active Subscriptions -->
    <div class="tab-pane fade show active" id="activeSubscriptions" role="tabpanel">
        <div class="card border-top-0" style="border-top-left-radius: 0; border-top-right-radius: 0;">
            <!-- Filters -->
            <div class="card-body border-bottom py-3">
                <form action="" method="GET" class="row g-2 align-items-end">
                    <div class="col-md-3">
                        <select name="plan_id" class="form-select form-select-sm">
                            <option value="">All Plans</option>
                            @foreach($plans as $plan)
                                <option value="{{ $plan->id }}" {{ request('plan_id') == $plan->id ? 'selected' : '' }}>{{ $plan->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="expiring_soon" value="1" id="expiringSoon" {{ request('expiring_soon') ? 'checked' : '' }}>
                            <label class="form-check-label small" for="expiringSoon">Expiring Soon</label>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <button type="submit" class="btn btn-sm btn-primary"><i class="bi bi-funnel"></i> Filter</button>
                        <a href="{{ route('admin.subscriptions.report') }}" class="btn btn-sm btn-light">Reset</a>
                    </div>
                </form>
            </div>
            <!-- Table -->
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Seller</th>
                            <th>Plan</th>
                            <th>Products</th>
                            <th>Inquiries</th>
                            <th>Expires</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($subscriptions as $sub)
                        <tr>
                            <td>
                                <strong>{{ $sub->seller->company_name ?? 'N/A' }}</strong>
                                <small class="d-block text-muted">{{ $sub->seller->user->email ?? '' }}</small>
                            </td>
                            <td><span class="badge bg-primary-subtle text-primary px-2 py-1">{{ $sub->plan->name ?? 'Unknown' }}</span></td>
                            <td>
                                @if(isset($sub->usage['products']))
                                    @php 
                                        $pUsed = $sub->usage['products']['used'];
                                        $pLimit = $sub->usage['products']['limit'];
                                        $pPercent = $pLimit > 0 ? ($pUsed / $pLimit) * 100 : 0;
                                    @endphp
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="progress" style="height: 6px; width: 60px;">
                                            <div class="progress-bar {{ $pPercent >= 90 ? 'bg-danger' : 'bg-primary' }}" style="width: {{ min($pPercent, 100) }}%"></div>
                                        </div>
                                        <small class="fw-bold">{{ $pUsed }}/{{ $pLimit }}</small>
                                    </div>
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if(isset($sub->usage['inquiries']))
                                    {{ $sub->usage['inquiries']['sent'] }}/{{ $sub->usage['inquiries']['limit'] }}
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @php $daysLeft = now()->diffInDays($sub->end_date, false); @endphp
                                <span class="{{ $daysLeft <= 7 ? 'text-danger fw-bold' : '' }}">{{ $sub->end_date->format('M d, Y') }}</span>
                                @if($daysLeft <= 7 && $daysLeft > 0)
                                    <small class="d-block text-danger">{{ $daysLeft }}d left</small>
                                @endif
                            </td>
                            <td><span class="badge bg-success">Active</span></td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">No active subscriptions found.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            @if($subscriptions->hasPages())
            <div class="card-footer bg-white">{{ $subscriptions->appends(request()->query())->links() }}</div>
            @endif
        </div>
    </div>

    <!-- Tab 2: All Sellers -->
    <div class="tab-pane fade" id="allSellers" role="tabpanel">
        <div class="card border-top-0" style="border-top-left-radius: 0; border-top-right-radius: 0;">
            <div class="card-body border-bottom py-2 bg-light">
                <small class="text-muted"><i class="bi bi-info-circle me-1"></i>Shows all sellers including free tier. <span class="text-danger">🔥</span> = Upgrade opportunity (at or near limit)</small>
            </div>
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Seller</th>
                            <th>Plan</th>
                            <th>Products Used</th>
                            <th>Usage</th>
                            <th>Joined</th>
                            <th>Upgrade</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($allSellers as $seller)
                        <tr class="{{ $seller->usage_data['upgrade_potential'] ? 'table-warning' : '' }}">
                            <td>
                                <strong>{{ $seller->company_name ?? 'N/A' }}</strong>
                                <small class="d-block text-muted">{{ $seller->user->email ?? '' }}</small>
                            </td>
                            <td>
                                @if($seller->usage_data['has_subscription'])
                                    <span class="badge bg-primary-subtle text-primary px-2 py-1">{{ $seller->usage_data['plan_name'] }}</span>
                                @else
                                    <span class="badge bg-secondary-subtle text-secondary px-2 py-1">Free</span>
                                @endif
                            </td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div class="progress" style="height: 6px; width: 60px;">
                                        <div class="progress-bar {{ $seller->usage_data['usage_percent'] >= 80 ? 'bg-danger' : 'bg-success' }}" style="width: {{ min($seller->usage_data['usage_percent'], 100) }}%"></div>
                                    </div>
                                    <small class="fw-bold">{{ $seller->usage_data['products_used'] }}/{{ $seller->usage_data['products_limit'] }}</small>
                                </div>
                            </td>
                            <td>
                                <span class="badge {{ $seller->usage_data['usage_percent'] >= 80 ? 'bg-danger' : 'bg-light text-dark' }}">{{ $seller->usage_data['usage_percent'] }}%</span>
                            </td>
                            <td><small>{{ $seller->created_at->format('M d, Y') }}</small></td>
                            <td>
                                @if($seller->usage_data['upgrade_potential'])
                                    <span class="text-danger" title="Upgrade Opportunity">🔥 High</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="6" class="text-center py-4 text-muted">No sellers found.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            @if($allSellers->hasPages())
            <div class="card-footer bg-white">{{ $allSellers->appends(request()->query())->links() }}</div>
            @endif
        </div>
    </div>
</div>
@endsection
