<?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 revenue data by month for the date range
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            SUM(CASE WHEN type = 'income' THEN amount ELSE 0 END) as income,
            SUM(CASE WHEN type = 'expense' THEN amount ELSE 0 END) as expenses,
            SUM(CASE WHEN type = 'income' THEN amount ELSE -amount END) as net_revenue
        FROM transactions 
        WHERE created_at BETWEEN ? AND ?
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month ASC
    ");
    $stmt->execute([$start_date, $end_date]);
    $revenue_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format data for Chart.js
    $labels = [];
    $income_data = [];
    $expense_data = [];
    $net_data = [];
    
    foreach ($revenue_data as $row) {
        $labels[] = date('M Y', strtotime($row['month'] . '-01'));
        $income_data[] = (float)$row['income'];
        $expense_data[] = (float)$row['expenses'];
        $net_data[] = (float)$row['net_revenue'];
    }
    
    echo json_encode([
        'success' => true,
        'data' => [
            'labels' => $labels,
            'values' => $net_data
        ],
        'chart_data' => [
            'labels' => $labels,
            'datasets' => [
                [
                    'label' => 'Income',
                    'data' => $income_data,
                    'backgroundColor' => 'rgba(40, 167, 69, 0.6)',
                    'borderColor' => 'rgba(40, 167, 69, 1)',
                    'borderWidth' => 2
                ],
                [
                    'label' => 'Expenses',
                    'data' => $expense_data,
                    'backgroundColor' => 'rgba(220, 53, 69, 0.6)',
                    'borderColor' => 'rgba(220, 53, 69, 1)',
                    'borderWidth' => 2
                ],
                [
                    'label' => 'Net Revenue',
                    'data' => $net_data,
                    'backgroundColor' => 'rgba(0, 123, 255, 0.6)',
                    'borderColor' => 'rgba(0, 123, 255, 1)',
                    'borderWidth' => 2
                ]
            ]
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
