<?php
require_once 'config.php';

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

try {
    // Get total downloads
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM downloads");
    $downloads = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    // Get total reviews and average rating
    $stmt = $pdo->query("SELECT COUNT(*) as count, AVG(rating) as avg_rating FROM reviews WHERE status = 'approved'");
    $reviewsData = $stmt->fetch(PDO::FETCH_ASSOC);
    $reviews = $reviewsData['count'];
    $avgRating = round($reviewsData['avg_rating'], 1) ?? 0;
    
    // Get rating distribution
    $ratingDistribution = [];
    for ($i = 1; $i <= 5; $i++) {
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM reviews WHERE rating = ? AND status = 'approved'");
        $stmt->execute([$i]);
        $ratingDistribution[$i] = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    }
    
    echo json_encode([
        'success' => true,
        'downloads' => (int)$downloads,
        'reviews' => (int)$reviews,
        'avg_rating' => (float)$avgRating,
        'rating_distribution' => $ratingDistribution
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>