<?php
/**
 * Stats API
 * GET /api/stats.php?type=public - Get public stats
 * GET /api/stats.php?type=admin  - Get admin stats (auth required)
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$type = $_GET['type'] ?? 'public';
$db = getDB();

if ($method !== 'GET') {
    errorResponse('Method not allowed', 405);
}

if ($type === 'admin') {
    requireAuth();
    
    // Get admin dashboard stats
    $blogCount = $db->query("SELECT COUNT(*) as count FROM blog_posts WHERE status = 'published'")->fetch()['count'];
    $draftCount = $db->query("SELECT COUNT(*) as count FROM blog_posts WHERE status = 'draft'")->fetch()['count'];
    $serviceCount = $db->query("SELECT COUNT(*) as count FROM services")->fetch()['count'];
    $brandCount = $db->query("SELECT COUNT(*) as count FROM brands")->fetch()['count'];
    $productCount = $db->query("SELECT COUNT(*) as count FROM products")->fetch()['count'];
    $totalViews = $db->query("SELECT COALESCE(SUM(views), 0) as total FROM blog_posts")->fetch()['total'];
    
    jsonResponse([
        'blog_posts' => (int)$blogCount,
        'drafts' => (int)$draftCount,
        'services' => (int)$serviceCount,
        'brands' => (int)$brandCount,
        'products' => (int)$productCount,
        'total_views' => (int)$totalViews
    ]);
}

// Public stats (for advertise page)
$blogCount = $db->query("SELECT COUNT(*) as count FROM blog_posts WHERE status = 'published'")->fetch()['count'];
$productCount = $db->query("SELECT COUNT(*) as count FROM products")->fetch()['count'];
$totalViews = $db->query("SELECT COALESCE(SUM(views), 0) as total FROM blog_posts WHERE status = 'published'")->fetch()['total'];

// Estimate monthly visitors
$monthlyVisitors = max((int)($totalViews / 3), 1000);

jsonResponse([
    'total_views' => (int)$totalViews,
    'blog_posts' => (int)$blogCount,
    'products' => (int)$productCount,
    'monthly_visitors' => $monthlyVisitors,
    'avg_time_on_site' => '3:45',
    'bounce_rate' => '42%'
]);
