<?php
require_once 'auth_check.php';
require_once 'db.php';

header('Content-Type: application/json');

try {
    $db1 = getDB1Connection();
    
    $totalVisits = $db1->query("SELECT COUNT(*) FROM visitors")->fetchColumn();
    
    $todayVisits = $db1->query("SELECT COUNT(*) FROM visitors WHERE DATE(visit_date) = CURDATE()")->fetchColumn();
    
    $weekVisits = $db1->query("SELECT COUNT(*) FROM visitors WHERE visit_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)")->fetchColumn();
    
    $uniqueCountries = $db1->query("SELECT COUNT(DISTINCT country) FROM visitors WHERE country IS NOT NULL AND country != ''")->fetchColumn();
    
    $uniqueLanguages = $db1->query("SELECT COUNT(DISTINCT language) FROM visitors WHERE language IS NOT NULL AND language != ''")->fetchColumn();
    
    $avgDaily = $db1->query("
        SELECT ROUND(COUNT(*) / DATEDIFF(CURDATE(), MIN(DATE(visit_date))) + 1, 1) as avg_daily 
        FROM visitors 
        WHERE visit_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    ")->fetchColumn();
    
    $topCountries = $db1->query("
        SELECT country, COUNT(*) as count 
        FROM visitors 
        WHERE country IS NOT NULL AND country != '' 
        GROUP BY country 
        ORDER BY count DESC 
        LIMIT 15
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $topLanguages = $db1->query("
        SELECT language, COUNT(*) as count 
        FROM visitors 
        WHERE language IS NOT NULL AND language != '' 
        GROUP BY language 
        ORDER BY count DESC 
        LIMIT 15
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $recentVisits = $db1->query("
        SELECT ip_address, country, language, visit_date,
               CASE 
                   WHEN TIMESTAMPDIFF(MINUTE, visit_date, NOW()) < 1 THEN 'Just now'
                   WHEN TIMESTAMPDIFF(MINUTE, visit_date, NOW()) < 60 THEN CONCAT(TIMESTAMPDIFF(MINUTE, visit_date, NOW()), 'm ago')
                   WHEN TIMESTAMPDIFF(HOUR, visit_date, NOW()) < 24 THEN CONCAT(TIMESTAMPDIFF(HOUR, visit_date, NOW()), 'h ago')
                   ELSE CONCAT(TIMESTAMPDIFF(DAY, visit_date, NOW()), 'd ago')
               END as time_ago
        FROM visitors 
        ORDER BY visit_date DESC 
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $topIPs = $db1->query("
        SELECT ip_address, COUNT(*) as count 
        FROM visitors 
        GROUP BY ip_address 
        ORDER BY count DESC 
        LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    $dailyBreakdown = $db1->query("
        SELECT DATE(visit_date) as date, COUNT(*) as count 
        FROM visitors 
        WHERE visit_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
        GROUP BY DATE(visit_date) 
        ORDER BY date DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'total_visits' => $totalVisits ?: 0,
        'today_visits' => $todayVisits ?: 0,
        'week_visits' => $weekVisits ?: 0,
        'unique_countries' => $uniqueCountries ?: 0,
        'unique_languages' => $uniqueLanguages ?: 0,
        'avg_daily' => $avgDaily ?: 0,
        'top_countries' => $topCountries ?: [],
        'top_languages' => $topLanguages ?: [],
        'recent_visits' => $recentVisits ?: [],
        'top_ips' => $topIPs ?: [],
        'daily_breakdown' => $dailyBreakdown ?: []
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error occurred']);
}
?>