<?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 l'objectif à mettre à jour
    $goalId = isset($_POST['goal-id']) ? (int)$_POST['goal-id'] : 0;
    
    // Vérifier si l'objectif existe
    $checkStmt = $db->prepare("SELECT id FROM finance_goals WHERE id = :id");
    $checkStmt->bindParam(':id', $goalId);
    $checkStmt->execute();
    
    if ($checkStmt->rowCount() === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Objectif non trouvé'
        ]);
        exit;
    }
    
    // Récupérer les données du formulaire
    $title = $_POST['title'] ?? '';
    $type = $_POST['type'] ?? '';
    $target = $_POST['target'] ?? 0;
    $startDate = $_POST['start_date'] ?? '';
    $endDate = $_POST['end_date'] ?? '';
    $notes = $_POST['notes'] ?? '';
    
    // Valider les données
    if (empty($title) || empty($type) || empty($target) || empty($startDate) || empty($endDate)) {
        echo json_encode([
            'success' => false,
            'message' => 'Tous les champs obligatoires doivent être remplis'
        ]);
        exit;
    }
    
    // Valider le type
    $validTypes = ['revenue', 'expense', 'profit', 'savings'];
    if (!in_array($type, $validTypes)) {
        echo json_encode([
            'success' => false,
            'message' => 'Type d\'objectif invalide'
        ]);
        exit;
    }
    
    // Valider le montant cible
    $target = (float)$target;
    if ($target <= 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Le montant cible doit être supérieur à zéro'
        ]);
        exit;
    }
    
    // Valider les dates
    if (strtotime($endDate) <= strtotime($startDate)) {
        echo json_encode([
            'success' => false,
            'message' => 'La date d\'échéance doit être ultérieure à la date de début'
        ]);
        exit;
    }
    
    // Calculer la valeur actuelle en fonction du type d'objectif
    $current = calculateCurrentProgress($db, $type, $startDate, $endDate);
    
    // Déterminer si l'objectif est atteint
    $completed = ($current >= $target) ? 1 : 0;
    
    // Mettre à jour l'objectif
    $stmt = $db->prepare("
        UPDATE finance_goals 
        SET title = :title, 
            type = :type, 
            target = :target, 
            current = :current, 
            start_date = :start_date, 
            end_date = :end_date, 
            notes = :notes, 
            completed = :completed,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = :id
    ");
    
    $stmt->bindParam(':id', $goalId);
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':type', $type);
    $stmt->bindParam(':target', $target);
    $stmt->bindParam(':current', $current);
    $stmt->bindParam(':start_date', $startDate);
    $stmt->bindParam(':end_date', $endDate);
    $stmt->bindParam(':notes', $notes);
    $stmt->bindParam(':completed', $completed);
    
    $stmt->execute();
    
    echo json_encode([
        'success' => true,
        'message' => 'Objectif mis à jour avec succès',
        'goal' => [
            'id' => $goalId,
            'title' => $title,
            'type' => $type,
            'target' => $target,
            'current' => $current,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'notes' => $notes,
            'completed' => (bool)$completed
        ]
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erreur de base de données: ' . $e->getMessage()
    ]);
}

// Calculer la progression actuelle en fonction du type d'objectif
function calculateCurrentProgress($db, $type, $startDate, $endDate) {
    try {
        if ($type === 'revenue') {
            // Pour objectif de revenu, somme des revenus dans la période
            $stmt = $db->prepare("
                SELECT SUM(amount) as total
                FROM finance_transactions
                WHERE type = 'revenue' AND date BETWEEN :start AND :end
            ");
            
            $stmt->bindParam(':start', $startDate);
            $stmt->bindParam(':end', $endDate);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (float)($result['total'] ?? 0);
            
        } elseif ($type === 'expense') {
            // Pour objectif de dépense, somme des dépenses dans la période
            $stmt = $db->prepare("
                SELECT SUM(amount) as total
                FROM finance_transactions
                WHERE type = 'expense' AND date BETWEEN :start AND :end
            ");
            
            $stmt->bindParam(':start', $startDate);
            $stmt->bindParam(':end', $endDate);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (float)($result['total'] ?? 0);
            
        } elseif ($type === 'profit') {
            // Pour objectif de bénéfice, différence entre revenus et 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);
            
            return $revenue - $expense;
            
        } elseif ($type === 'savings') {
            // Pour objectif d'épargne, récupérer la valeur actuelle 
            // (il n'y a pas de calcul automatique, mais on pourrait récupérer une valeur existante)
            $stmt = $db->prepare("
                SELECT current
                FROM finance_goals
                WHERE id = :id
            ");
            
            $stmt->bindParam(':id', $_POST['goal-id']);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (float)($result['current'] ?? 0);
        }
        
        return 0;
        
    } catch (PDOException $e) {
        error_log('Erreur lors du calcul de la progression: ' . $e->getMessage());
        return 0;
    }
}
?>