<?php

return function($page) {
    $config = kirby()->option('donorbox');
    $apiKey = $config['api_key'];
    $campaignSlug = $config['campaign_slug'];

    // Valeurs par défaut
    $data = [
        'amount_raised' => 0,
        'donor_count' => 0,
        'goal_amount' => 20000, // Objectif par défaut
        'percentage' => 0,
        'campaign_url' => $config['campaign_url']
    ];

    // Si la clé API est configurée, récupérer les données en temps réel
    if (!empty($apiKey)) {
        try {
            $apiUrl = $config['api_base_url'] . '/campaigns/' . $campaignSlug;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $apiUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $apiKey,
                'Content-Type: application/json'
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200 && $response) {
                $campaignData = json_decode($response, true);

                if ($campaignData) {
                    $data['amount_raised'] = $campaignData['amount_raised'] ?? 0;
                    $data['donor_count'] = $campaignData['donor_count'] ?? 0;
                    $data['goal_amount'] = $campaignData['goal_amount'] ?? 20000;

                    // Calculer le pourcentage
                    if ($data['goal_amount'] > 0) {
                        $data['percentage'] = round(($data['amount_raised'] / $data['goal_amount']) * 100, 0);
                    }
                }
            }
        } catch (Exception $e) {
            // En cas d'erreur, on garde les valeurs par défaut
            // Optionnel : logger l'erreur
        }
    }

    return $data;
};
