@extends('layouts.admin')

@section('title', 'Analytics Dashboard')

@section('content')
<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h3 mb-0">
                <i class="bi bi-graph-up"></i> Advanced Analytics
            </h1>
            <p class="text-muted">System-wide performance and insights</p>
        </div>
        <div class="col-md-4 text-end">
            <!-- Period Filter -->
            <div class="btn-group" role="group">
                <a href="{{ route('admin.analytics.index', ['period' => '7']) }}"
                   class="btn btn-sm {{ $period == '7' ? 'btn-primary' : 'btn-outline-primary' }}">
                    7D
                </a>
                <a href="{{ route('admin.analytics.index', ['period' => '30']) }}"
                   class="btn btn-sm {{ $period == '30' ? 'btn-primary' : 'btn-outline-primary' }}">
                    30D
                </a>
                <a href="{{ route('admin.analytics.index', ['period' => '90']) }}"
                   class="btn btn-sm {{ $period == '90' ? 'btn-primary' : 'btn-outline-primary' }}">
                    90D
                </a>
            </div>
            <!-- Export -->
            <a href="{{ route('admin.analytics.export', ['type' => 'redemptions', 'format' => 'csv']) }}" class="btn btn-sm btn-success ms-2">
                <i class="bi bi-download"></i> Export CSV
            </a>
        </div>
    </div>

    <!-- Key Metrics Row 1 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted mb-2"><i class="bi bi-people"></i> Total Users</h6>
                    <h3 class="mb-0">{{ $stats['total_users'] }}</h3>
                    <small class="text-success">{{ $stats['active_users'] }} active</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted mb-2"><i class="bi bi-shop"></i> Businesses</h6>
                    <h3 class="mb-0">{{ $stats['total_businesses'] }}</h3>
                    <small class="text-success">{{ $stats['active_businesses'] }} active</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted mb-2"><i class="bi bi-tag"></i> Total Offers</h6>
                    <h3 class="mb-0">{{ $stats['total_offers'] }}</h3>
                    <small class="text-success">{{ $stats['active_offers'] }} active</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted mb-2"><i class="bi bi-star"></i> Avg Rating</h6>
                    <h3 class="mb-0">{{ number_format($stats['avg_rating'], 1) }}/5</h3>
                    <small class="text-muted">{{ $stats['total_reviews'] }} reviews</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Redemptions Metrics -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-gradient-success text-white">
                <div class="card-body">
                    <h6 class="mb-2"><i class="bi bi-check-circle"></i> Total Redemptions</h6>
                    <h3 class="mb-0">{{ $stats['total_redemptions'] }}</h3>
                    <small>All time</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-gradient-info text-white">
                <div class="card-body">
                    <h6 class="mb-2"><i class="bi bi-calendar-check"></i> Period Redemptions</h6>
                    <h3 class="mb-0">{{ $stats['redemptions_period'] }}</h3>
                    <small>Last {{ $period }} days</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-gradient-warning text-white">
                <div class="card-body">
                    <h6 class="mb-2"><i class="bi bi-currency-dollar"></i> Total Value</h6>
                    <h3 class="mb-0">${{ number_format($revenue['total'], 2) }}</h3>
                    <small>{{ $revenue['count'] }} redemptions</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm bg-gradient-primary text-white">
                <div class="card-body">
                    <h6 class="mb-2"><i class="bi bi-graph-up"></i> Avg Value</h6>
                    <h3 class="mb-0">${{ number_format($revenue['average'], 2) }}</h3>
                    <small>Per redemption</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0"><i class="bi bi-graph-up"></i> Redemption Trends</h5>
                </div>
                <div class="card-body">
                    <canvas id="redemptionChart" height="80"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0"><i class="bi bi-line-chart"></i> User Growth</h5>
                </div>
                <div class="card-body">
                    <canvas id="userGrowthChart" height="80"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Reports Row -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-4">
                    <a href="{{ route('admin.analytics.reports.redemptions') }}" class="card border-0 shadow-sm text-decoration-none h-100">
                        <div class="card-body">
                            <i class="bi bi-check-circle text-success" style="font-size: 2rem;"></i>
                            <h5 class="mt-3 mb-0">Redemptions Report</h5>
                            <small class="text-muted">View detailed redemption analytics</small>
                        </div>
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="{{ route('admin.analytics.reports.businesses') }}" class="card border-0 shadow-sm text-decoration-none h-100">
                        <div class="card-body">
                            <i class="bi bi-shop text-info" style="font-size: 2rem;"></i>
                            <h5 class="mt-3 mb-0">Business Report</h5>
                            <small class="text-muted">Business performance metrics</small>
                        </div>
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="{{ route('admin.analytics.reports.users') }}" class="card border-0 shadow-sm text-decoration-none h-100">
                        <div class="card-body">
                            <i class="bi bi-people text-primary" style="font-size: 2rem;"></i>
                            <h5 class="mt-3 mb-0">User Report</h5>
                            <small class="text-muted">User growth and activity</small>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Top Offers & Business Performance -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0"><i class="bi bi-fire"></i> Top Offers ({{ $period }}D)</h5>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Offer</th>
                                <th>Redemptions</th>
                                <th>Business</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($topOffers as $offer)
                                <tr>
                                    <td><small><strong>{{ Str::limit($offer->title, 20) }}</strong></small></td>
                                    <td><span class="badge bg-success">{{ $offer->redemptions_count }}</span></td>
                                    <td><small class="text-muted">{{ $offer->business->business_name ?? 'N/A' }}</small></td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="3" class="text-center text-muted py-4"><small>No data</small></td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0"><i class="bi bi-chart-bar"></i> Top Businesses ({{ $period }}D)</h5>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Business</th>
                                <th>Redemptions</th>
                                <th>Rating</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($businessPerformance as $business)
                                <tr>
                                    <td><small><strong>{{ Str::limit($business->business_name, 20) }}</strong></small></td>
                                    <td><span class="badge bg-info">{{ $business->redemptions_count }}</span></td>
                                    <td>
                                        <small>
                                            @php $rating = $business->reviews_avg_rating ?? 0; @endphp
                                            {{ number_format($rating, 1) }}/5
                                        </small>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="3" class="text-center text-muted py-4"><small>No data</small></td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Redemption Status Summary -->
    <div class="row">
        <div class="col-md-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0"><i class="bi bi-pie-chart"></i> Redemption Status Distribution</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        @foreach($redemptions['by_status'] as $status)
                            <div class="col-md-4">
                                <div class="text-center">
                                    <h4 class="mb-0">{{ $status->count }}</h4>
                                    <small class="text-muted">{{ ucfirst($status->status) }}</small>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js Script -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Redemption Trends Chart
    const ctx1 = document.getElementById('redemptionChart').getContext('2d');
    const trends = {!! json_encode($redemptions['trending']) !!};
    const labels = trends.map(t => t.date);
    const data = trends.map(t => t.count);

    new Chart(ctx1, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Redemptions',
                data: data,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4,
                pointRadius: 4,
                pointBackgroundColor: '#28a745',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { color: '#f0f0f0' } },
                x: { grid: { display: false } }
            }
        }
    });

    // User Growth Chart
    const ctx2 = document.getElementById('userGrowthChart').getContext('2d');
    const userGrowth = {!! json_encode($userGrowth) !!};
    const userLabels = userGrowth.map(d => d.date);
    const userData = userGrowth.map(d => d.count);

    new Chart(ctx2, {
        type: 'line',
        data: {
            labels: userLabels,
            datasets: [{
                label: 'Users',
                data: userData,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                borderWidth: 2,
                fill: true,
                tension: 0.4,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { color: '#f0f0f0' } },
                x: { grid: { display: false } }
            }
        }
    });
});
</script>
@endsection

