<?php
/**
 * admin_chart_data.php
 * Returns real-time chart data for admin dashboard
 */

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

requireAdmin(true);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

try {
    $timeRange = isset($_GET['range']) ? $_GET['range'] : 'week';
    
    // Determine date interval
    switch ($timeRange) {
        case 'today':
            $interval = 'INTERVAL 1 DAY';
            $groupBy = 'HOUR(created_at)';
            $labelFormat = 'H:00';
            break;
        case 'week':
            $interval = 'INTERVAL 7 DAY';
            $groupBy = 'DATE(created_at)';
            $labelFormat = 'Y-m-d';
            break;
        case 'month':
            $interval = 'INTERVAL 30 DAY';
            $groupBy = 'DATE(created_at)';
            $labelFormat = 'Y-m-d';
            break;
        case 'year':
            $interval = 'INTERVAL 365 DAY';
            $groupBy = 'DATE_FORMAT(created_at, "%Y-%m")';
            $labelFormat = 'Y-m';
            break;
        default:
            $interval = 'INTERVAL 7 DAY';
            $groupBy = 'DATE(created_at)';
            $labelFormat = 'Y-m-d';
    }
    
    // User growth data
    $userGrowthQuery = "
        SELECT 
            $groupBy as period, 
            COUNT(*) as count
        FROM users
        WHERE created_at >= DATE_SUB(NOW(), $interval)
        GROUP BY period
        ORDER BY period ASC
    ";
    $stmt = $pdo->query($userGrowthQuery);
    $userGrowth = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Revenue data (completed deposits)
    $revenueQuery = "
        SELECT 
            $groupBy as period, 
            COALESCE(SUM(amount), 0) as total
        FROM transactions
        WHERE type = 'deposit' 
        AND status = 'completed'
        AND created_at >= DATE_SUB(NOW(), $interval)
        GROUP BY period
        ORDER BY period ASC
    ";
    $stmt = $pdo->query($revenueQuery);
    $revenueData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Investment data
    $investmentQuery = "
        SELECT 
            $groupBy as period, 
            COUNT(*) as count,
            COALESCE(SUM(amount), 0) as total
        FROM investments
        WHERE created_at >= DATE_SUB(NOW(), $interval)
        GROUP BY period
        ORDER BY period ASC
    ";
    try {
        $stmt = $pdo->query($investmentQuery);
        $investmentData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $investmentData = [];
    }
    
    // Format data for charts
    $userLabels = array_column($userGrowth, 'period');
    $userCounts = array_column($userGrowth, 'count');
    
    $revenueLabels = array_column($revenueData, 'period');
    $revenueTotals = array_column($revenueData, 'total');
    
    $investmentLabels = array_column($investmentData, 'period');
    $investmentCounts = array_column($investmentData, 'count');
    $investmentTotals = array_column($investmentData, 'total');
    
    echo json_encode([
        'success' => true,
        'data' => [
            'userGrowth' => [
                'labels' => $userLabels,
                'data' => array_map('intval', $userCounts)
            ],
            'revenue' => [
                'labels' => $revenueLabels,
                'data' => array_map('floatval', $revenueTotals)
            ],
            'investments' => [
                'labels' => $investmentLabels,
                'counts' => array_map('intval', $investmentCounts),
                'totals' => array_map('floatval', $investmentTotals)
            ],
            'timeRange' => $timeRange
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch chart data: ' . $e->getMessage()
    ]);
}
