<?php
require_once __DIR__ . '/../includes/config.php';

requireAuth();

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'GET') {
    jsonResponse(['error' => 'Método não permitido'], 405);
}

$startDate = $_GET['startDate'] ?? date('Y-m-01');
$endDate = $_GET['endDate'] ?? date('Y-m-t');

// Total income
$stmt = $pdo->prepare("SELECT COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total FROM transactions WHERE type = 'income' AND transaction_date >= ? AND transaction_date <= ?");
$stmt->execute([$startDate, $endDate]);
$totalIncome = (float) $stmt->fetch()['total'];

// Total expenses
$stmt = $pdo->prepare("SELECT COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total FROM transactions WHERE type = 'expense' AND transaction_date >= ? AND transaction_date <= ?");
$stmt->execute([$startDate, $endDate]);
$totalExpenses = (float) $stmt->fetch()['total'];

// Balance
$balance = $totalIncome - $totalExpenses;

// Pending bills
$stmt = $pdo->query("SELECT COUNT(*) as count FROM bills WHERE status = 'pending'");
$pendingBills = (int) $stmt->fetch()['count'];

// Overdue bills
$stmt = $pdo->prepare("SELECT COUNT(*) as count FROM bills WHERE status = 'pending' AND due_date < ?");
$stmt->execute([date('Y-m-d')]);
$overdueBills = (int) $stmt->fetch()['count'];

// Partner loans
$stmt = $pdo->prepare("
    SELECT COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total 
    FROM transactions 
    WHERE type = 'income' 
    AND partner_id IS NOT NULL 
    AND transaction_date >= ? 
    AND transaction_date <= ?
");
$stmt->execute([$startDate, $endDate]);
$partnerLoans = (float) $stmt->fetch()['total'];

// Income by payment method
$stmt = $pdo->prepare("
    SELECT payment_method, COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total 
    FROM transactions 
    WHERE type = 'income' 
    AND transaction_date >= ? 
    AND transaction_date <= ?
    GROUP BY payment_method
");
$stmt->execute([$startDate, $endDate]);
$incomeByPaymentMethod = [];
while ($row = $stmt->fetch()) {
    if ($row['payment_method']) {
        $incomeByPaymentMethod[$row['payment_method']] = (float) $row['total'];
    }
}

// Monthly data for last 6 months
$monthlyData = [];
for ($i = 5; $i >= 0; $i--) {
    $date = new DateTime();
    $date->modify("-$i months");
    $monthStart = $date->format('Y-m-01');
    $monthEnd = $date->format('Y-m-t');
    $monthLabel = $date->format('M');
    
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total FROM transactions WHERE type = 'income' AND transaction_date >= ? AND transaction_date <= ?");
    $stmt->execute([$monthStart, $monthEnd]);
    $monthIncome = (float) $stmt->fetch()['total'];
    
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(CAST(amount AS DECIMAL)), 0) as total FROM transactions WHERE type = 'expense' AND transaction_date >= ? AND transaction_date <= ?");
    $stmt->execute([$monthStart, $monthEnd]);
    $monthExpense = (float) $stmt->fetch()['total'];
    
    $monthlyData[] = [
        'month' => $monthLabel,
        'income' => $monthIncome,
        'expense' => $monthExpense
    ];
}

jsonResponse([
    'totalIncome' => $totalIncome,
    'totalExpenses' => $totalExpenses,
    'balance' => $balance,
    'pendingBills' => $pendingBills,
    'overdueBills' => $overdueBills,
    'partnerLoans' => $partnerLoans,
    'incomeByPaymentMethod' => $incomeByPaymentMethod,
    'monthlyData' => $monthlyData
]);
