<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

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

try {
    $database = new Database();
    $pdo = $database->getConnection();
    
    $start_date = $_GET['start_date'] ?? date('Y-m-01');
    $end_date = $_GET['end_date'] ?? date('Y-m-t');
    
    // Get payment data by method and month
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            payment_method,
            COUNT(*) as transaction_count,
            SUM(amount) as total_amount
        FROM transactions 
        WHERE created_at BETWEEN ? AND ?
        AND payment_method IS NOT NULL
        GROUP BY DATE_FORMAT(created_at, '%Y-%m'), payment_method
        ORDER BY month ASC, payment_method ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $payment_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get unique payment methods and months
    $payment_methods = [];
    $months = [];
    $data_by_month = [];
    
    foreach ($payment_data as $row) {
        $method = $row['payment_method'] ?: 'Unknown';
        $month = $row['month'];
        
        if (!in_array($method, $payment_methods)) {
            $payment_methods[] = $method;
        }
        
        if (!in_array($month, $months)) {
            $months[] = $month;
        }
        
        if (!isset($data_by_month[$month])) {
            $data_by_month[$month] = [];
        }
        
        $data_by_month[$month][$method] = [
            'count' => (int)$row['transaction_count'],
            'amount' => (float)$row['total_amount']
        ];
    }
    
    // Format labels
    $labels = [];
    foreach ($months as $month) {
        $labels[] = date('M Y', strtotime($month . '-01'));
    }
    
    // Create datasets for each payment method
    $datasets = [];
    $colors = [
        'cash' => ['rgba(40, 167, 69, 0.6)', 'rgba(40, 167, 69, 1)'],
        'card' => ['rgba(0, 123, 255, 0.6)', 'rgba(0, 123, 255, 1)'],
        'bank_transfer' => ['rgba(108, 117, 125, 0.6)', 'rgba(108, 117, 125, 1)'],
        'online' => ['rgba(255, 193, 7, 0.6)', 'rgba(255, 193, 7, 1)'],
        'check' => ['rgba(220, 53, 69, 0.6)', 'rgba(220, 53, 69, 1)']
    ];
    
    $colorIndex = 0;
    $defaultColors = [
        ['rgba(54, 162, 235, 0.6)', 'rgba(54, 162, 235, 1)'],
        ['rgba(255, 99, 132, 0.6)', 'rgba(255, 99, 132, 1)'],
        ['rgba(255, 206, 86, 0.6)', 'rgba(255, 206, 86, 1)'],
        ['rgba(75, 192, 192, 0.6)', 'rgba(75, 192, 192, 1)'],
        ['rgba(153, 102, 255, 0.6)', 'rgba(153, 102, 255, 1)']
    ];
    
    foreach ($payment_methods as $method) {
        $method_data = [];
        
        foreach ($months as $month) {
            $amount = isset($data_by_month[$month][$method]) ? $data_by_month[$month][$method]['amount'] : 0;
            $method_data[] = $amount;
        }
        
        $color = $colors[strtolower($method)] ?? $defaultColors[$colorIndex % count($defaultColors)];
        $colorIndex++;
        
        $datasets[] = [
            'label' => ucfirst(str_replace('_', ' ', $method)),
            'data' => $method_data,
            'backgroundColor' => $color[0],
            'borderColor' => $color[1],
            'borderWidth' => 2
        ];
    }
    
    // Calculate total values for simple chart display
    $total_values = [];
    foreach ($months as $month) {
        $total = 0;
        foreach ($payment_methods as $method) {
            $amount = isset($data_by_month[$month][$method]) ? $data_by_month[$month][$method]['amount'] : 0;
            $total += $amount;
        }
        $total_values[] = $total;
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'labels' => $labels,
            'values' => $total_values
        ],
        'chart_data' => [
            'labels' => $labels,
            'datasets' => $datasets
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
