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

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

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

$type = $_GET['type'] ?? 'daily';
$range = (int)($_GET['range'] ?? 5);

if ($type == 'hourly') {
    // نمایش ساعات اخیر (پیش‌فرض 6 ساعت)
    $hours = $range > 0 ? $range : 6;
    
    $labels = [];
    $data = [];
    
    for ($i = $hours - 1; $i >= 0; $i--) {
        $hour_num = (int)date('H', strtotime("-$i hours"));
        $labels[] = $hour_num . ':00';
        
        $start_time = date('Y-m-d H:00:00', strtotime("-$i hours"));
        $end_time = date('Y-m-d H:59:59', strtotime("-$i hours"));
        
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(price), 0) as total 
            FROM agent_servers 
            WHERE created_at BETWEEN ? AND ?
        ");
        $stmt->execute([$start_time, $end_time]);
        $total = $stmt->fetchColumn();
        $data[] = (float)$total;
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'فروش ساعتی (' . $hours . ' ساعت اخیر)',
        'total' => array_sum($data)
    ]);
    
} else if ($type == 'daily') {
    // نمایش روزهای اخیر (پیش‌فرض 5 روز)
    $days = $range > 0 ? $range : 5;
    
    $labels = [];
    $data = [];
    
    for ($i = $days - 1; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        // فرمت میلادی: 15/12
        $labels[] = date('d/m', strtotime($date));
        
        $start_time = $date . ' 00:00:00';
        $end_time = $date . ' 23:59:59';
        
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(price), 0) as total 
            FROM agent_servers 
            WHERE created_at BETWEEN ? AND ?
        ");
        $stmt->execute([$start_time, $end_time]);
        $total = $stmt->fetchColumn();
        $data[] = (float)$total;
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'فروش روزانه (' . $days . ' روز اخیر)',
        'total' => array_sum($data)
    ]);
    
} else if ($type == 'weekly') {
    // نمایش هفته‌های اخیر (پیش‌فرض 4 هفته)
    $weeks = $range > 0 ? $range : 4;
    
    $labels = [];
    $data = [];
    
    // پیدا کردن دوشنبه این هفته
    $current_week_start = strtotime('last monday');
    if (date('N') == 1) {
        $current_week_start = strtotime('today');
    }
    
    for ($i = $weeks - 1; $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_num = $weeks - $i;
        $labels[] = "هفته {$week_num} (" . date('d/m', $week_start) . " - " . date('d/m', $week_end) . ")";
        
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(price), 0) as total 
            FROM agent_servers 
            WHERE DATE(created_at) BETWEEN ? AND ?
        ");
        $stmt->execute([$start_date, $end_date]);
        $total = $stmt->fetchColumn();
        $data[] = (float)$total;
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'فروش هفتگی (' . $weeks . ' هفته اخیر)',
        'total' => array_sum($data)
    ]);
    
} else if ($type == 'monthly') {
    // نمایش ماه‌های اخیر (پیش‌فرض 6 ماه)
    $months = $range > 0 ? $range : 6;
    
    $labels = [];
    $data = [];
    
    for ($i = $months - 1; $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 created_at BETWEEN ? AND ?
        ");
        $stmt->execute([$start_time, $end_time]);
        $total = $stmt->fetchColumn();
        $data[] = (float)$total;
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'فروش ماهانه (' . $months . ' ماه اخیر)',
        'total' => array_sum($data)
    ]);
    
} else if ($type == 'yearly') {
    // نمایش سال‌های اخیر
    $years = $range > 0 ? $range : 5;
    $current_year = date('Y');
    
    $labels = [];
    $data = [];
    
    for ($i = $years - 1; $i >= 0; $i--) {
        $year = $current_year - $i;
        $labels[] = $year;
        
        $start_time = $year . '-01-01 00:00:00';
        $end_time = $year . '-12-31 23:59:59';
        
        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(price), 0) as total 
            FROM agent_servers 
            WHERE created_at BETWEEN ? AND ?
        ");
        $stmt->execute([$start_time, $end_time]);
        $total = $stmt->fetchColumn();
        $data[] = (float)$total;
    }
    
    echo json_encode([
        'labels' => $labels,
        'data' => $data,
        'title' => 'فروش سالانه (' . $years . ' سال اخیر)',
        'total' => array_sum($data)
    ]);
}
?>