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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false,
        'message' => 'Méthode non autorisée'
    ]);
    exit;
}

try {
    $db = getDB2Connection();
    
    // Récupérer l'ID de la transaction à mettre à jour
    $transactionId = isset($_POST['transaction-id']) ? (int)$_POST['transaction-id'] : 0;
    
    // Vérifier si la transaction existe
    $checkStmt = $db->prepare("SELECT id FROM finance_transactions WHERE id = :id");
    $checkStmt->bindParam(':id', $transactionId);
    $checkStmt->execute();
    
    if ($checkStmt->rowCount() === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Transaction non trouvée'
        ]);
        exit;
    }
    
    // Récupérer les données du formulaire
    $type = $_POST['transaction-type'] ?? '';
    $amount = $_POST['amount'] ?? 0;
    $category = $_POST['category'] ?? '';
    $date = $_POST['date'] ?? '';
    $description = $_POST['description'] ?? '';
    
    // Valider les données
    if (empty($type) || empty($amount) || empty($category) || empty($date)) {
        echo json_encode([
            'success' => false,
            'message' => 'Tous les champs obligatoires doivent être remplis'
        ]);
        exit;
    }
    
    // Valider le type
    if ($type !== 'revenue' && $type !== 'expense') {
        echo json_encode([
            'success' => false,
            'message' => 'Type de transaction invalide'
        ]);
        exit;
    }
    
    // Valider le montant
    $amount = (float)$amount;
    if ($amount <= 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Le montant doit être supérieur à zéro'
        ]);
        exit;
    }
    
    // Mise à jour de la transaction
    $stmt = $db->prepare("
        UPDATE finance_transactions 
        SET type = :type, 
            amount = :amount, 
            category = :category, 
            date = :date, 
            description = :description,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = :id
    ");
    
    $stmt->bindParam(':id', $transactionId);
    $stmt->bindParam(':type', $type);
    $stmt->bindParam(':amount', $amount);
    $stmt->bindParam(':category', $category);
    $stmt->bindParam(':date', $date);
    $stmt->bindParam(':description', $description);
    
    $stmt->execute();
    
    // Mettre à jour les objectifs liés après modification
    updateGoalsProgress($db, $type);
    
    echo json_encode([
        'success' => true,
        'message' => 'Transaction mise à jour avec succès',
        'transaction' => [
            'id' => $transactionId,
            'type' => $type,
            'amount' => $amount,
            'category' => $category,
            'date' => $date,
            'description' => $description
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erreur de base de données: ' . $e->getMessage()
    ]);
}

// Fonction pour mettre à jour les objectifs financiers
function updateGoalsProgress($db, $transactionType) {
    try {
        // Récupérer les objectifs actifs du même type
        $stmt = $db->prepare("
            SELECT id, type, target, start_date, end_date
            FROM finance_goals
            WHERE type = :type AND completed = 0 AND end_date >= CURDATE()
        ");
        
        // Pour les revenus, mettre à jour les objectifs de revenus et de bénéfices
        // Pour les dépenses, mettre à jour les objectifs de dépenses et de bénéfices
        if ($transactionType === 'revenue') {
            $goalType = 'revenue';
        } else {
            $goalType = 'expense';
        }
        
        $stmt->bindParam(':type', $goalType);
        $stmt->execute();
        $goals = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Pour chaque objectif, recalculer le montant actuel
        foreach ($goals as $goal) {
            $startDate = $goal['start_date'];
            $endDate = $goal['end_date'];
            
            // Requête pour calculer le total
            $calcStmt = $db->prepare("
                SELECT SUM(amount) as total
                FROM finance_transactions
                WHERE type = :type AND date BETWEEN :start AND :end
            ");
            
            $calcStmt->bindParam(':type', $transactionType);
            $calcStmt->bindParam(':start', $startDate);
            $calcStmt->bindParam(':end', $endDate);
            $calcStmt->execute();
            
            $result = $calcStmt->fetch(PDO::FETCH_ASSOC);
            $currentAmount = (float)($result['total'] ?? 0);
            
            // Mettre à jour l'objectif
            $updateStmt = $db->prepare("
                UPDATE finance_goals
                SET current = :current, completed = :completed
                WHERE id = :id
            ");
            
            $updateStmt->bindParam(':current', $currentAmount);
            $completed = ($currentAmount >= $goal['target']) ? 1 : 0;
            $updateStmt->bindParam(':completed', $completed);
            $updateStmt->bindParam(':id', $goal['id']);
            $updateStmt->execute();
        }
        
        // Mise à jour des objectifs de profit si nécessaire
        $profitStmt = $db->prepare("
            SELECT id, target, start_date, end_date
            FROM finance_goals
            WHERE type = 'profit' AND completed = 0 AND end_date >= CURDATE()
        ");
        
        $profitStmt->execute();
        $profitGoals = $profitStmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($profitGoals as $goal) {
            $startDate = $goal['start_date'];
            $endDate = $goal['end_date'];
            
            // Calculer le profit (revenus - dépenses)
            $revenueStmt = $db->prepare("
                SELECT SUM(amount) as total
                FROM finance_transactions
                WHERE type = 'revenue' AND date BETWEEN :start AND :end
            ");
            
            $revenueStmt->bindParam(':start', $startDate);
            $revenueStmt->bindParam(':end', $endDate);
            $revenueStmt->execute();
            
            $expenseStmt = $db->prepare("
                SELECT SUM(amount) as total
                FROM finance_transactions
                WHERE type = 'expense' AND date BETWEEN :start AND :end
            ");
            
            $expenseStmt->bindParam(':start', $startDate);
            $expenseStmt->bindParam(':end', $endDate);
            $expenseStmt->execute();
            
            $revenueResult = $revenueStmt->fetch(PDO::FETCH_ASSOC);
            $expenseResult = $expenseStmt->fetch(PDO::FETCH_ASSOC);
            
            $revenue = (float)($revenueResult['total'] ?? 0);
            $expense = (float)($expenseResult['total'] ?? 0);
            $profit = $revenue - $expense;
            
            // Mettre à jour l'objectif de profit
            $updateStmt = $db->prepare("
                UPDATE finance_goals
                SET current = :current, completed = :completed
                WHERE id = :id
            ");
            
            $updateStmt->bindParam(':current', $profit);
            $completed = ($profit >= $goal['target']) ? 1 : 0;
            $updateStmt->bindParam(':completed', $completed);
            $updateStmt->bindParam(':id', $goal['id']);
            $updateStmt->execute();
        }
    } catch (PDOException $e) {
        // Gérer l'erreur silencieusement
        error_log('Erreur lors de la mise à jour des objectifs: ' . $e->getMessage());
    }
}
?>