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

// Vérifier si l'ID est fourni
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'ID d\'objectif non valide ou manquant'
    ]);
    exit;
}

$goalId = (int)$_GET['id'];

try {
    $db = getDB2Connection();
    
    // Récupérer les détails de l'objectif
    $stmt = $db->prepare("
        SELECT id, title, type, target, current, start_date, end_date, notes, completed, created_at, updated_at
        FROM finance_goals
        WHERE id = :id
    ");
    
    $stmt->bindParam(':id', $goalId);
    $stmt->execute();
    
    $goal = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$goal) {
        echo json_encode([
            'success' => false,
            'message' => 'Objectif non trouvé'
        ]);
        exit;
    }
    
    // Formater les valeurs si nécessaire
    $goal['target'] = (float)$goal['target'];
    $goal['current'] = (float)$goal['current'];
    $goal['start_date'] = date('Y-m-d', strtotime($goal['start_date']));
    $goal['end_date'] = date('Y-m-d', strtotime($goal['end_date']));
    $goal['completed'] = (bool)$goal['completed'];
    
    // Calculer le pourcentage de progression
    if ($goal['target'] > 0) {
        $progress = min(100, round(($goal['current'] / $goal['target']) * 100));
    } else {
        $progress = 0;
    }
    
    $goal['progress'] = $progress;
    
    echo json_encode([
        'success' => true,
        'goal' => $goal
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Erreur de base de données: ' . $e->getMessage()
    ]);
}
?>