<?php
// api/dashboard.php - Dashboard API Endpoint

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

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/auth_check.php';
require_once __DIR__ . '/../src/Database.php';
require_once __DIR__ . '/../src/AdMobAPI.php';

$action = $_GET['action'] ?? 'summary';

try {
    $db = Database::getInstance();
    
    switch ($action) {
        case 'summary':
            // Get today's summary
            $today = date('Y-m-d');
            
            $stmt = $db->prepare("
                SELECT 
                    COALESCE(SUM(earnings), 0) as today_earnings,
                    COALESCE(SUM(impressions), 0) as today_impressions,
                    COALESCE(SUM(clicks), 0) as today_clicks,
                    COALESCE(AVG(ecpm), 0) as today_ecpm
                FROM reports
                WHERE report_date = :today
            ");
            $stmt->execute([':today' => $today]);
            $today_stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Get yesterday's data for comparison
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            $stmt = $db->prepare("
                SELECT 
                    COALESCE(SUM(earnings), 0) as yesterday_earnings,
                    COALESCE(SUM(impressions), 0) as yesterday_impressions
                FROM reports
                WHERE report_date = :yesterday
            ");
            $stmt->execute([':yesterday' => $yesterday]);
            $yesterday_stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Calculate changes
            $earnings_change = 0;
            $impressions_change = 0;
            
            if ($yesterday_stats['yesterday_earnings'] > 0) {
                $earnings_change = (($today_stats['today_earnings'] - $yesterday_stats['yesterday_earnings']) / $yesterday_stats['yesterday_earnings']) * 100;
            }
            
            if ($yesterday_stats['yesterday_impressions'] > 0) {
                $impressions_change = (($today_stats['today_impressions'] - $yesterday_stats['yesterday_impressions']) / $yesterday_stats['yesterday_impressions']) * 100;
            }
            
            // Get last 7 days data
            $stmt = $db->prepare("
                SELECT 
                    report_date,
                    SUM(earnings) as earnings,
                    SUM(impressions) as impressions
                FROM reports
                WHERE report_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                GROUP BY report_date
                ORDER BY report_date ASC
            ");
            $stmt->execute();
            $chart_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Get total apps count
            $stmt = $db->query("SELECT COUNT(*) as count FROM apps");
            $apps_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
            
            // Get total ad units count
            $stmt = $db->query("SELECT COUNT(*) as count FROM ad_units");
            $ad_units_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
            
            // Get this month's earnings
            $stmt = $db->prepare("
                SELECT COALESCE(SUM(earnings), 0) as month_earnings
                FROM reports
                WHERE YEAR(report_date) = YEAR(CURDATE()) 
                AND MONTH(report_date) = MONTH(CURDATE())
            ");
            $stmt->execute();
            $month_stats = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => [
                    'today_earnings' => floatval($today_stats['today_earnings']),
                    'today_impressions' => intval($today_stats['today_impressions']),
                    'today_clicks' => intval($today_stats['today_clicks']),
                    'today_ecpm' => floatval($today_stats['today_ecpm']),
                    'earnings_change' => round($earnings_change, 2),
                    'impressions_change' => round($impressions_change, 2),
                    'month_earnings' => floatval($month_stats['month_earnings']),
                    'apps_count' => intval($apps_count),
                    'ad_units_count' => intval($ad_units_count),
                    'chart_data' => $chart_data
                ]
            ]);
            break;
            
        case 'top_apps':
            // Get top performing apps
            $stmt = $db->prepare("
                SELECT 
                    a.app_id,
                    a.app_name,
                    a.platform,
                    COALESCE(SUM(r.earnings), 0) as total_earnings,
                    COALESCE(SUM(r.impressions), 0) as total_impressions
                FROM apps a
                LEFT JOIN reports r ON a.app_id = r.app_id
                WHERE r.report_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY a.app_id, a.app_name, a.platform
                ORDER BY total_earnings DESC
                LIMIT 5
            ");
            $stmt->execute();
            $top_apps = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => $top_apps
            ]);
            break;
            
        case 'top_ad_units':
            // Get top performing ad units
            $stmt = $db->prepare("
                SELECT 
                    au.ad_unit_id,
                    au.ad_unit_name,
                    au.format,
                    a.app_name,
                    COALESCE(SUM(r.earnings), 0) as total_earnings,
                    COALESCE(SUM(r.impressions), 0) as total_impressions
                FROM ad_units au
                LEFT JOIN apps a ON au.app_id = a.app_id
                LEFT JOIN reports r ON au.ad_unit_id = r.ad_unit_id
                WHERE r.report_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY au.ad_unit_id, au.ad_unit_name, au.format, a.app_name
                ORDER BY total_earnings DESC
                LIMIT 5
            ");
            $stmt->execute();
            $top_ad_units = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => $top_ad_units
            ]);
            break;
            
        case 'recent_activity':
            // Get recent sync logs
            $stmt = $db->prepare("
                SELECT 
                    sync_type,
                    status,
                    items_synced,
                    started_at,
                    completed_at
                FROM sync_logs
                ORDER BY started_at DESC
                LIMIT 10
            ");
            $stmt->execute();
            $activity = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'data' => $activity
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'error' => 'Invalid action'
            ]);
            break;
    }
    
} catch (Exception $e) {
    error_log('Dashboard API Error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>