@extends('adminlte::page')

@section('title', 'Analytics')

@section('content')
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Analytics Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('brand.dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item active">Analytics</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <div class="container-fluid">
        <!-- Filter Controls -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="dateRange">Date Range</label>
                                    <select class="form-control" id="dateRange">
                                        <option value="7">Last 7 Days</option>
                                        <option value="30" selected>Last 30 Days</option>
                                        <option value="90">Last 90 Days</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="platformFilter">Platform</label>
                                    <select class="form-control" id="platformFilter">
                                        <option value="all" selected>All Platforms</option>
                                        <option value="youtube">YouTube</option>
                                        <option value="instagram">Instagram</option>
                                        <option value="tiktok">TikTok</option>
                                        <option value="linkedin">LinkedIn</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="campaignFilter">Campaign</label>
                                    <select class="form-control" id="campaignFilter">
                                        <option value="" selected>All Campaigns</option>
                                        @foreach($campaigns as $campaign)
                                            <option value="{{ $campaign->id }}">{{ $campaign->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 text-right">
                                <button type="button" class="btn btn-primary" id="applyFilters">Apply Filters</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- KPI Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3>{{ number_format($totalFollowers) }}</h3>
                        <p>Total Followers</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3>{{ number_format($totalPosts) }}</h3>
                        <p>Total Posts</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-file-alt"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3>{{ number_format($engagementRate, 2) }}%</h3>
                        <p>Avg Engagement Rate</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-heart"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3>{{ $socialAccounts->count() }}</h3>
                        <p>Connected Accounts</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-plug"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Additional KPI Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3>{{ number_format($totalImpressions) }}</h3>
                        <p>Impressions</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-eye"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3>{{ number_format($totalLikes) }}</h3>
                        <p>Likes</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-thumbs-up"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3>{{ number_format($totalComments) }}</h3>
                        <p>Comments</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-comment"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3>{{ number_format($totalShares) }}</h3>
                        <p>Shares</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-share"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3>{{ number_format($totalSaves) }}</h3>
                        <p>Saves</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-bookmark"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3>{{ number_format($followerGrowth, 2) }}%</h3>
                        <p>Follower Growth</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Charts -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Impressions Over Time</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="impressionsChart" height="100"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Engagement Over Time</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="engagementChart" height="100"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Platform Breakdown and Top Performing Posts -->
        <div class="row">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Platform Breakdown</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <canvas id="platformChart" height="100"></canvas>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Top Performing Posts</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Post</th>
                                        <th>Platform</th>
                                        <th>Impressions</th>
                                        <th>Engagement</th>
                                    </tr>
                                </thead>
                                <tbody id="topPostsTable">
                                    <!-- Top posts will be loaded here by JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize charts
    var impressionsCtx = document.getElementById('impressionsChart').getContext('2d');
    var engagementCtx = document.getElementById('engagementChart').getContext('2d');
    var platformCtx = document.getElementById('platformChart').getContext('2d');
    
    // Impressions chart
    var impressionsChart = new Chart(impressionsCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Impressions',
                data: [],
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // Engagement chart
    var engagementChart = new Chart(engagementCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Engagement',
                data: [],
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
    
    // Platform chart
    var platformChart = new Chart(platformCtx, {
        type: 'doughnut',
        data: {
            labels: ['YouTube', 'Instagram', 'TikTok', 'LinkedIn'],
            datasets: [{
                data: [30, 25, 35, 10],
                backgroundColor: [
                    'rgb(255, 99, 132)',
                    'rgb(54, 162, 235)',
                    'rgb(255, 205, 86)',
                    'rgb(153, 102, 255)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
    
    // Load initial chart data
    loadChartData();
    
    // Function to load chart data
    window.loadChartData = function() {
        const dateRange = document.getElementById('dateRange').value;
        const platform = document.getElementById('platformFilter').value;
        const campaign = document.getElementById('campaignFilter').value;
        
        fetch(`/brand/analytics/data?days=${dateRange}&provider=${platform}&campaign_id=${campaign}`)
            .then(response => response.json())
            .then(data => {
                // Update impressions chart
                impressionsChart.data.labels = data.labels;
                impressionsChart.data.datasets[0].data = data.time_series.impressions;
                impressionsChart.update();
                
                // Update engagement chart
                engagementChart.data.labels = data.labels;
                engagementChart.data.datasets[0].data = data.time_series.engagements;
                engagementChart.update();
                
                // Update top posts table
                const topPostsTable = document.getElementById('topPostsTable');
                topPostsTable.innerHTML = '';
                
                data.top_posts.forEach(post => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${post.title}</td>
                        <td>${post.provider}</td>
                        <td>${post.impressions.toLocaleString()}</td>
                        <td>${post.engagement.toLocaleString()}</td>
                    `;
                    topPostsTable.appendChild(row);
                });
            })
            .catch(error => {
                console.error('Error loading chart data:', error);
            });
    };
    
    // Apply filters button
    document.getElementById('applyFilters').addEventListener('click', function() {
        loadChartData();
    });
    
    // Update charts when filters change
    document.getElementById('dateRange').addEventListener('change', function() {
        loadChartData();
    });
    
    document.getElementById('platformFilter').addEventListener('change', function() {
        loadChartData();
    });
    
    document.getElementById('campaignFilter').addEventListener('change', function() {
        loadChartData();
    });
});
</script>
@endsection