<?php
header('Content-Type: application/json');
require_once 'db.php';

$db = getDB2Connection();

// Récupérer les jours depuis la requête
$days = isset($_GET['days']) ? (int)$_GET['days'] : 30;

// Valider les jours
if ($days <= 0 || $days > 365) {
    $days = 30;
}

// Calcul de la date de début
$startDate = date('Y-m-d', strtotime("-$days days"));
$endDate = date('Y-m-d');

try {
    // Requête pour obtenir les revenus quotidiens
    $revenueQuery = $db->prepare("
        SELECT DATE(date) as day, SUM(amount) as total 
        FROM finance_transactions 
        WHERE type = 'revenue' AND date BETWEEN :start AND :end 
        GROUP BY DATE(date) 
        ORDER BY day ASC
    ");
    $revenueQuery->bindParam(':start', $startDate);
    $revenueQuery->bindParam(':end', $endDate);
    $revenueQuery->execute();
    $revenueResults = $revenueQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Requête pour obtenir les dépenses quotidiennes
    $expenseQuery = $db->prepare("
        SELECT DATE(date) as day, SUM(amount) as total 
        FROM finance_transactions 
        WHERE type = 'expense' AND date BETWEEN :start AND :end 
        GROUP BY DATE(date) 
        ORDER BY day ASC
    ");
    $expenseQuery->bindParam(':start', $startDate);
    $expenseQuery->bindParam(':end', $endDate);
    $expenseQuery->execute();
    $expenseResults = $expenseQuery->fetchAll(PDO::FETCH_ASSOC);
    
    // Création de l'ensemble de dates complet
    $dates = [];
    $revenues = [];
    $expenses = [];
    $profit = [];
    
    // Remplir avec toutes les dates dans la plage
    $currentDate = new DateTime($startDate);
    $lastDate = new DateTime($endDate);
    $interval = new DateInterval('P1D');
    
    while ($currentDate <= $lastDate) {
        $dateStr = $currentDate->format('Y-m-d');
        $dateDisplay = $currentDate->format('j M'); // Format "15 Jan"
        
        // Ajouter la date formatée
        $dates[] = $dateDisplay;
        
        // Trouver les revenus pour cette date
        $revenueAmount = 0;
        foreach ($revenueResults as $rev) {
            if ($rev['day'] === $dateStr) {
                $revenueAmount = (float)$rev['total'];
                break;
            }
        }
        $revenues[] = $revenueAmount;
        
        // Trouver les dépenses pour cette date
        $expenseAmount = 0;
        foreach ($expenseResults as $exp) {
            if ($exp['day'] === $dateStr) {
                $expenseAmount = (float)$exp['total'];
                break;
            }
        }
        $expenses[] = $expenseAmount;
        
        // Calculer le profit
        $profit[] = $revenueAmount - $expenseAmount;
        
        // Passer au jour suivant
        $currentDate->add($interval);
    }
    
    // Construire les données de réponse
    $responseData = [
        'success' => true,
        'data' => [
            'dates' => $dates,
            'revenues' => $revenues,
            'expenses' => $expenses,
            'profit' => $profit
        ]
    ];
    
    echo json_encode($responseData);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erreur de base de données: ' . $e->getMessage()
    ]);
}
?>