<?php
/**
 * Modern Dashboard
 * 
 * Secure admin dashboard with authentication and statistics
 */

// Set page title
$pageTitle = 'Dashboard';

// Include admin header
require_once __DIR__ . '/includes/admin-header.php';

// Log page view
log_admin_action('view_dashboard');

try {
    // Get database connection from Database class
    $pdo = $db->getConnection();

    // Include tracking functions
    require_once '../includes/tracking_functions.php';

    // Get statistics
    $totalCities = $pdo->query("SELECT COUNT(*) as count FROM cities")->fetch()['count'];
    $totalServices = $pdo->query("SELECT COUNT(*) as count FROM services")->fetch()['count'];
    $totalCombinations = $pdo->query("SELECT COUNT(*) as count FROM city_service")->fetch()['count'];
    $expectedCombinations = $totalCities * $totalServices;
    
    // Calculate completion percentage
    $completionPercentage = $expectedCombinations > 0 ? round(($totalCombinations / $expectedCombinations) * 100) : 0;
    
    // Get most visited links
    $mostVisitedLinks = getMostVisitedLinks(5); // Get top 5 most visited links
    
    // Get recent activity
    $recentActivity = $pdo->query("
        SELECT cs.updated_at, c.name as city_name, s.name as service_name, c.slug as city_slug, s.slug as service_slug
        FROM city_service cs
        JOIN cities c ON cs.city_id = c.id
        JOIN services s ON cs.service_id = s.id
        ORDER BY cs.updated_at DESC
        LIMIT 8
    ")->fetchAll();
    
    // Get top cities
    $topCities = $pdo->query("
        SELECT c.name, c.slug, COUNT(cs.id) as combination_count
        FROM cities c
        LEFT JOIN city_service cs ON c.id = cs.city_id
        GROUP BY c.id, c.name, c.slug
        ORDER BY combination_count DESC
        LIMIT 6
    ")->fetchAll();
    
    // Get monthly stats for the chart
    $monthlyStats = $pdo->query("
        SELECT 
            DATE_FORMAT(cs.updated_at, '%Y-%m') as month,
            COUNT(DISTINCT cs.id) as count
        FROM city_service cs
        WHERE cs.updated_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(cs.updated_at, '%Y-%m')
        ORDER BY month ASC
    ")->fetchAll(PDO::FETCH_KEY_PAIR);
    
} catch (PDOException $e) {
    error_log('Dashboard Error: ' . $e->getMessage());
    $_SESSION['flash'] = [
        'type' => 'error',
        'message' => 'Error loading dashboard data. Please try again.'
    ];
    
    // Set default values
    $totalCities = 0;
    $totalServices = 0;
    $totalCombinations = 0;
    $expectedCombinations = 0;
    $completionPercentage = 0;
    $mostVisitedLinks = [];
    $recentActivity = [];
    $topCities = [];
    $monthlyStats = [];
}
?>

<!-- Custom styles for this page -->
<style>
    .metric-card {
        @apply bg-white rounded-xl shadow-sm p-6 relative overflow-hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .metric-card:hover {
        @apply shadow-md;
        transform: translateY(-3px);
    }
    
    .metric-card .icon {
        @apply absolute right-4 top-4 text-gray-200 text-4xl;
    }
    
    .progress-bar {
        height: 6px;
        @apply bg-gray-200 rounded-full overflow-hidden;
    }
    
    .progress-bar-fill {
        height: 100%;
        @apply bg-blue-500;
        transition: width 0.6s ease;
    }
    
    .activity-item {
        @apply py-3 border-b border-gray-100 last:border-0;
    }
    
    .city-tag {
        @apply inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800;
    }
    
    .chart-container {
        position: relative;
        height: 300px;
        width: 100%;
    }
    
    .link-stats {
        @apply space-y-2;
    }
    
    .link-stat-item {
        @apply flex items-center justify-between p-2 hover:bg-gray-50 rounded-lg;
    }
    
    .link-stat-count {
        @apply font-medium text-gray-900;
    }
    
    /* Animations */
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .animate-fade-in-up {
        animation: fadeInUp 0.6s ease forwards;
    }
    
    .animate-delay-1 { animation-delay: 0.1s; }
    .animate-delay-2 { animation-delay: 0.2s; }
    .animate-delay-3 { animation-delay: 0.3s; }
    .animate-delay-4 { animation-delay: 0.4s; }
</style>

<!-- Main content -->
<div class="container mx-auto px-4 py-8">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <!-- Total Cities -->
        <div class="metric-card bg-gradient-to-br from-blue-50 to-blue-100">
            <div class="flex items-center">
                <div>
                    <p class="text-sm font-medium text-gray-500">Total Cities</p>
                    <p class="mt-1 text-3xl font-semibold text-gray-900"><?php echo number_format($totalCities); ?></p>
                    <div class="mt-2 text-sm text-gray-500">
                        <span class="text-green-600 font-medium">+2.5%</span> from last month
                    </div>
                </div>
                <div class="ml-auto">
                    <i class="fas fa-city icon"></i>
                </div>
            </div>
        </div>
        
        <!-- Total Services -->
        <div class="metric-card bg-gradient-to-br from-green-50 to-green-100">
            <div class="flex items-center">
                <div>
                    <p class="text-sm font-medium text-gray-500">Total Services</p>
                    <p class="mt-1 text-3xl font-semibold text-gray-900"><?php echo number_format($totalServices); ?></p>
                    <div class="mt-2 text-sm text-gray-500">
                        <span class="text-green-600 font-medium">+5.2%</span> from last month
                    </div>
                </div>
                <div class="ml-auto">
                    <i class="fas fa-cogs icon"></i>
                </div>
            </div>
        </div>
        
        <!-- Total Pages -->
        <div class="metric-card bg-gradient-to-br from-purple-50 to-purple-100">
            <div class="flex items-center">
                <div>
                    <p class="text-sm font-medium text-gray-500">Total Pages</p>
                    <p class="mt-1 text-3xl font-semibold text-gray-900"><?php echo number_format($totalCombinations); ?></p>
                    <div class="mt-2">
                        <div class="flex justify-between text-sm text-gray-500 mb-1">
                            <span>Completion</span>
                            <span><?php echo $completionPercentage; ?>%</span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-bar-fill" style="width: <?php echo $completionPercentage; ?>%"></div>
                        </div>
                    </div>
                </div>
                <div class="ml-auto">
                    <i class="fas fa-file-alt icon"></i>
                </div>
            </div>
        </div>
        
        <!-- Expected Pages -->
        <div class="metric-card bg-gradient-to-br from-yellow-50 to-yellow-100">
            <div class="flex items-center">
                <div>
                    <p class="text-sm font-medium text-gray-500">Expected Pages</p>
                    <p class="mt-1 text-3xl font-semibold text-gray-900"><?php echo number_format($expectedCombinations); ?></p>
                    <div class="mt-2 text-sm text-gray-500">
                        <?php 
                        $remaining = $expectedCombinations - $totalCombinations;
                        echo number_format($remaining) . ' remaining';
                        ?>
                    </div>
                </div>
                <div class="ml-auto">
                    <i class="fas fa-tasks icon"></i>
                </div>
            </div>
        </div>
    </div>
    
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <!-- Recent Activity -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">Recent Activity</h3>
                    <p class="mt-1 text-sm text-gray-500">Latest updates to city-service pages</p>
                </div>
                <div class="divide-y divide-gray-100">
                    <?php if (!empty($recentActivity)): ?>
                        <?php foreach ($recentActivity as $activity): ?>
                            <div class="activity-item">
                                <div class="px-6">
                                    <div class="flex items-center">
                                        <div class="flex-shrink-0">
                                            <i class="fas fa-sync-alt text-blue-500"></i>
                                        </div>
                                        <div class="ml-3 flex-1">
                                            <p class="text-sm font-medium text-gray-900">
                                                <a href="/<?php echo htmlspecialchars($activity['city_slug']); ?>/<?php echo htmlspecialchars($activity['service_slug']); ?>" 
                                                   class="hover:text-blue-600" target="_blank">
                                                    <?php echo htmlspecialchars($activity['city_name']); ?> - <?php echo htmlspecialchars($activity['service_name']); ?>
                                                </a>
                                            </p>
                                            <p class="text-xs text-gray-500">
                                                Updated <?php echo date('M j, Y g:i A', strtotime($activity['updated_at'])); ?>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="p-6 text-center text-gray-500">
                            No recent activity found.
                        </div>
                    <?php endif; ?>
                </div>
                <div class="px-6 py-3 bg-gray-50 text-right">
                    <a href="modern-manage-cities-services.php" class="text-sm font-medium text-blue-600 hover:text-blue-500">
                        View all activity <span aria-hidden="true">&rarr;</span>
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Top Cities -->
        <div>
            <div class="bg-white rounded-xl shadow-sm overflow-hidden h-full">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-gray-900">Top Cities</h3>
                    <p class="mt-1 text-sm text-gray-500">Cities with the most service pages</p>
                </div>
                <div class="p-6">
                    <?php if (!empty($topCities)): ?>
                        <div class="space-y-4">
                            <?php foreach ($topCities as $city): ?>
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center">
                                        <span class="city-tag">
                                            <?php echo htmlspecialchars($city['name']); ?>
                                        </span>
                                    </div>
                                    <span class="text-sm font-medium text-gray-900">
                                        <?php echo number_format($city['combination_count']); ?> pages
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-gray-500 py-4">
                            No city data available.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Charts Row -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- Page Growth -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">Page Growth</h3>
                <p class="mt-1 text-sm text-gray-500">New pages added over time</p>
            </div>
            <div class="p-6">
                <div class="chart-container">
                    <canvas id="pageGrowthChart"></canvas>
                </div>
            </div>
        </div>
        
        <!-- Most Visited Links -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-medium text-gray-900">Most Visited Pages</h3>
                <p class="mt-1 text-sm text-gray-500">Top 5 most visited pages</p>
            </div>
            <div class="p-6">
                <?php if (!empty($mostVisitedLinks)): ?>
                    <div class="link-stats">
                        <?php foreach ($mostVisitedLinks as $link): ?>
                            <div class="link-stat-item">
                                <a href="<?php echo htmlspecialchars($link['url']); ?>" 
                                   class="text-blue-600 hover:text-blue-800 truncate" 
                                   target="_blank"
                                   title="<?php echo htmlspecialchars($link['title']); ?>">
                                    <?php echo htmlspecialchars($link['title']); ?>
                                </a>
                                <span class="link-stat-count">
                                    <?php echo number_format($link['visits']); ?> visits
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center text-gray-500 py-4">
                        No visit data available.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Quick Actions -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden mb-8">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">Quick Actions</h3>
            <p class="mt-1 text-sm text-gray-500">Common tasks you might want to perform</p>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 p-6">
            <a href="modern-manage-cities-services.php" class="group">
                <div class="p-4 border border-gray-200 rounded-lg hover:border-blue-500 transition-colors">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-blue-50 text-blue-600 group-hover:bg-blue-100 transition-colors">
                            <i class="fas fa-plus-circle text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <h4 class="font-medium text-gray-900">Add New Page</h4>
                            <p class="text-sm text-gray-500">Create a new city-service page</p>
                        </div>
                    </div>
                </div>
            </a>
            
            <a href="modern-seo-optimizer.php" class="group">
                <div class="p-4 border border-gray-200 rounded-lg hover:border-green-500 transition-colors">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-green-50 text-green-600 group-hover:bg-green-100 transition-colors">
                            <i class="fas fa-search-plus text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <h4 class="font-medium text-gray-900">SEO Optimizer</h4>
                            <p class="text-sm text-gray-500">Improve your SEO scores</p>
                        </div>
                    </div>
                </div>
            </a>
            
            <a href="modern-sync-data.php" class="group">
                <div class="p-4 border border-gray-200 rounded-lg hover:border-purple-500 transition-colors">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-purple-50 text-purple-600 group-hover:bg-purple-100 transition-colors">
                            <i class="fas fa-sync-alt text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <h4 class="font-medium text-gray-900">Sync Data</h4>
                            <p class="text-sm text-gray-500">Update city and service data</p>
                        </div>
                    </div>
                </div>
            </a>
            
            <a href="modern-content-management.php" class="group">
                <div class="p-4 border border-gray-200 rounded-lg hover:border-yellow-500 transition-colors">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-yellow-50 text-yellow-600 group-hover:bg-yellow-100 transition-colors">
                            <i class="fas fa-edit text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <h4 class="font-medium text-gray-900">Content Manager</h4>
                            <p class="text-sm text-gray-500">Manage all content</p>
                        </div>
                    </div>
                </div>
            </a>
        </div>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// Page Growth Chart
document.addEventListener('DOMContentLoaded', function() {
    const growthCtx = document.getElementById('pageGrowthChart');
    
    if (growthCtx) {
        const pageGrowthChart = new Chart(growthCtx, {
            type: 'line',
            data: {
                labels: [
                    'January', 'February', 'March', 'April', 'May', 'June',
                    'July', 'August', 'September', 'October', 'November', 'December'
                ],
                datasets: [{
                    label: 'Pages Added',
                    data: [0, 100, 250, 400, 600, 800, 1000, 1250, 1500, 1800, 2100, 2500],
                    borderColor: '#4F46E5',
                    backgroundColor: 'rgba(79, 70, 229, 0.05)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            drawBorder: false
                        },
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString();
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // Update time every second
    function updateTime() {
        const now = new Date();
        const timeElement = document.getElementById('current-time');
        if (timeElement) {
            timeElement.textContent = now.toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: true
            });
        }
    }

    // Initialize and update time
    updateTime();
    setInterval(updateTime, 1000);

    // Initialize tooltips
    const tooltipTriggers = document.querySelectorAll('[data-tooltip]');
    
    tooltipTriggers.forEach(trigger => {
        const tooltip = document.createElement('div');
        tooltip.className = 'hidden bg-gray-800 text-white text-xs rounded py-1 px-2 absolute z-50 whitespace-nowrap';
        tooltip.textContent = trigger.getAttribute('data-tooltip');
        document.body.appendChild(tooltip);
        
        const updateTooltip = (e) => {
            tooltip.style.left = `${e.pageX + 10}px`;
            tooltip.style.top = `${e.pageY + 10}px`;
        };
        
        trigger.addEventListener('mouseenter', (e) => {
            tooltip.classList.remove('hidden');
            updateTooltip(e);
        });
        
        trigger.addEventListener('mousemove', updateTooltip);
        
        trigger.addEventListener('mouseleave', () => {
            tooltip.classList.add('hidden');
        });
    });
});
</script>

<?php
// Include admin footer
require_once __DIR__ . '/includes/admin-footer.php';
?>
