<?php
session_start();
include('../includes/config.php');

$period = isset($_GET['period']) ? $_GET['period'] : 'this_month';

// Determine date range
switch ($period) {
    case 'today':
        $labels = ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'];
        $dates = array();
        for ($i = 0; $i < 24; $i += 4) {
            $hour = str_pad($i, 2, '0', STR_PAD_LEFT) . ':00';
            $dates[] = date('Y-m-d') . ' ' . $hour . ':00';
        }
        break;
        
    case 'this_week':
        $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        $dates = array();
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', strtotime('monday this week +' . $i . ' days'));
            $dates[] = $date;
        }
        break;
        
    case 'this_month':
    default:
        $days_in_month = date('t');
        $labels = array();
        $dates = array();
        for ($i = 1; $i <= $days_in_month; $i++) {
            $date = date('Y-m-') . str_pad($i, 2, '0', STR_PAD_LEFT);
            if ($i % 5 == 0 || $i == 1 || $i == $days_in_month) {
                $labels[] = date('M j', strtotime($date));
            } else {
                $labels[] = '';
            }
            $dates[] = $date;
        }
        break;
}

$referrals_data = array();
$earnings_data = array();

foreach ($dates as $date) {
    if (strpos($date, ' ') !== false) {
        // Hourly data for today
        list($date_part, $time_part) = explode(' ', $date);
        $next_hour = date('Y-m-d H:i:s', strtotime($date . ' +4 hours'));
        
        $ref_sql = "SELECT COUNT(*) as count FROM referrals 
                    WHERE created_at >= '$date' AND created_at < '$next_hour'";
        $earn_sql = "SELECT COALESCE(SUM(amount), 0) as amount FROM referral_transactions 
                     WHERE created_at >= '$date' AND created_at < '$next_hour'";
    } else {
        // Daily data
        $next_date = date('Y-m-d', strtotime($date . ' +1 day'));
        
        $ref_sql = "SELECT COUNT(*) as count FROM referrals 
                    WHERE DATE(created_at) = '$date'";
        $earn_sql = "SELECT COALESCE(SUM(amount), 0) as amount FROM referral_transactions 
                     WHERE DATE(created_at) = '$date'";
    }
    
    $ref_result = mysqli_query($conn, $ref_sql);
    $ref_row = mysqli_fetch_assoc($ref_result);
    $referrals_data[] = intval($ref_row['count']);
    
    $earn_result = mysqli_query($conn, $earn_sql);
    $earn_row = mysqli_fetch_assoc($earn_result);
    $earnings_data[] = floatval($earn_row['amount']);
}

echo json_encode(array(
    'success' => true,
    'labels' => $labels,
    'referrals' => $referrals_data,
    'earnings' => $earnings_data
));
?>