<?php
session_start();
require_once '../../vippanneladmin56329803/config.php';

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

if (!isset($_SESSION['agent_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$agent_id = $_SESSION['agent_id'];

$type = $_GET['type'] ?? 'purchases';

if ($type == 'purchases') {
    $range = $_GET['range'] ?? 'daily';
    
    if ($range == 'daily') {
        // 7 روز اخیر
        $labels = [];
        $data = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            // فرمت میلادی ساده
            $labels[] = date('d/m', strtotime($date));
            
            $stmt = $pdo->prepare("
                SELECT COALESCE(SUM(price), 0) as total 
                FROM agent_servers 
                WHERE agent_id = ? AND DATE(created_at) = ?
            ");
            $stmt->execute([$agent_id, $date]);
            $total = $stmt->fetchColumn();
            $data[] = (float)$total;
        }
        
        echo json_encode([
            'labels' => $labels,
            'data' => $data,
            'title' => 'میزان خرید روزانه (7 روز اخیر)',
            'total' => array_sum($data)
        ]);
        
    } else if ($range == 'weekly') {
        // 4 هفته اخیر - محاسبه صحیح هفته‌ها
        $labels = [];
        $data = [];
        
        // هفته جاری را پیدا می‌کنیم (از دوشنبه تا یکشنبه)
        $current_week_start = strtotime('last monday');
        if (date('N') == 1) { // اگر امروز دوشنبه است
            $current_week_start = strtotime('today');
        }
        
        for ($i = 3; $i >= 0; $i--) {
            $week_start = strtotime("-$i weeks", $current_week_start);
            $week_end = strtotime("+6 days", $week_start);
            
            $start_date = date('Y-m-d', $week_start);
            $end_date = date('Y-m-d', $week_end);
            
            $week_number = 4 - $i;
            $labels[] = "هفته {$week_number} (" . date('d/m', $week_start) . " - " . date('d/m', $week_end) . ")";
            
            $stmt = $pdo->prepare("
                SELECT COALESCE(SUM(price), 0) as total 
                FROM agent_servers 
                WHERE agent_id = ? AND DATE(created_at) BETWEEN ? AND ?
            ");
            $stmt->execute([$agent_id, $start_date, $end_date]);
            $total = $stmt->fetchColumn();
            $data[] = (float)$total;
        }
        
        echo json_encode([
            'labels' => $labels,
            'data' => $data,
            'title' => 'میزان خرید هفتگی (4 هفته اخیر)',
            'total' => array_sum($data)
        ]);
        
    } else {
        // ماهانه - 6 ماه اخیر
        $labels = [];
        $data = [];
        
        for ($i = 5; $i >= 0; $i--) {
            $month_year = date('F Y', strtotime("-$i months"));
            $labels[] = $month_year;
            
            $start_time = date('Y-m-01 00:00:00', strtotime("-$i months"));
            $end_time = date('Y-m-t 23:59:59', strtotime("-$i months"));
            
            $stmt = $pdo->prepare("
                SELECT COALESCE(SUM(price), 0) as total 
                FROM agent_servers 
                WHERE agent_id = ? AND created_at BETWEEN ? AND ?
            ");
            $stmt->execute([$agent_id, $start_time, $end_time]);
            $total = $stmt->fetchColumn();
            $data[] = (float)$total;
        }
        
        echo json_encode([
            'labels' => $labels,
            'data' => $data,
            'title' => 'میزان خرید ماهانه (6 ماه اخیر)',
            'total' => array_sum($data)
        ]);
    }
    
} else if ($type == 'top_panels') {
    // نمایش پنل‌های پرفروش برای این نماینده
    $stmt = $pdo->prepare("
        SELECT p.name, COUNT(*) as count, COALESCE(SUM(asv.price), 0) as total_price
        FROM agent_servers asv
        JOIN panels p ON asv.panel_id = p.id
        WHERE asv.agent_id = ?
        GROUP BY asv.panel_id
        ORDER BY count DESC
        LIMIT 5
    ");
    $stmt->execute([$agent_id]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $labels = [];
    $data = [];
    $total_servers = 0;
    
    foreach ($results as $row) {
        $labels[] = $row['name'];
        $data[] = (int)$row['count'];
        $total_servers += $row['count'];
    }
    
    // اگر هیچ داده‌ای وجود ندارد
    if (empty($labels)) {
        $labels = ['هیچ سرویسی وجود ندارد'];
        $data = [0];
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'پنل‌های پرفروش',
        'total' => $total_servers
    ]);
}
?>