-- Monthly Report Statistics for the Last Year
-- This query aggregates placementCount, videoCount, returnVisitInfoCount, and conversationCount
-- by month for the last 12 months

SELECT 
    DATE_FORMAT(date, '%Y-%m') AS month,
    YEAR(date) AS year,
    MONTH(date) AS month_number,
    COUNT(*) AS total_reports,
    SUM(COALESCE(placementCount, 0)) AS total_placements,
    SUM(COALESCE(videoCount, 0)) AS total_videos,
    SUM(COALESCE(returnVisitInfoCount, 0)) AS total_return_visits,
    SUM(COALESCE(conversationCount, 0)) AS total_conversations,
    AVG(COALESCE(placementCount, 0)) AS avg_placements_per_report,
    AVG(COALESCE(videoCount, 0)) AS avg_videos_per_report,
    AVG(COALESCE(returnVisitInfoCount, 0)) AS avg_return_visits_per_report,
    AVG(COALESCE(conversationCount, 0)) AS avg_conversations_per_report,
    COUNT(CASE WHEN placementCount > 0 THEN 1 END) AS reports_with_placements,
    COUNT(CASE WHEN videoCount > 0 THEN 1 END) AS reports_with_videos,
    COUNT(CASE WHEN returnVisitInfoCount > 0 THEN 1 END) AS reports_with_return_visits,
    COUNT(CASE WHEN conversationCount > 0 THEN 1 END) AS reports_with_conversations
FROM Report 
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
    AND date <= CURDATE()
GROUP BY YEAR(date), MONTH(date), DATE_FORMAT(date, '%Y-%m')
ORDER BY year DESC, month_number DESC; 