<?php
/**
 * Script pour corriger le problème des paiements mensuels qui ne sont pas comptabilisés dans les revenus totaux
 */

// Inclusion des fichiers nécessaires
require_once 'config.php';
require_once 'database/init.php';
require_once 'includes/functions.php';

// Sauvegarde du fichier functions.php original
$functionsFile = 'includes/functions.php';
$backupFile = 'includes/functions.php.bak';

if (!file_exists($backupFile)) {
    copy($functionsFile, $backupFile);
    echo "<p>Sauvegarde du fichier functions.php créée.</p>";
}

// Lecture du contenu du fichier functions.php
$content = file_get_contents($functionsFile);

// Recherche de la fonction calculateTotalIncome
$pattern = '/function calculateTotalIncome\([^\)]*\)\s*\{[^}]*\}/s';
if (preg_match($pattern, $content, $matches)) {
    $oldFunction = $matches[0];
    
    // Nouvelle fonction qui inclut les paiements mensuels
    $newFunction = <<<'EOT'
function calculateTotalIncome($startDate = null, $endDate = null) {
    global $db;
    
    // Calcul des revenus à partir de la table income
    $incomeParams = [];
    $incomeWhereClause = '';
    
    if ($startDate && $endDate) {
        $incomeWhereClause = "WHERE payment_date BETWEEN ? AND ?";
        $incomeParams = [$startDate, $endDate];
    } elseif ($startDate) {
        $incomeWhereClause = "WHERE payment_date >= ?";
        $incomeParams = [$startDate];
    } elseif ($endDate) {
        $incomeWhereClause = "WHERE payment_date <= ?";
        $incomeParams = [$endDate];
    }
    
    $incomeQuery = "SELECT SUM(amount) as total FROM income {$incomeWhereClause}";
    $stmt = $db->prepare($incomeQuery);
    $stmt->execute($incomeParams);
    $incomeResult = $stmt->fetch(PDO::FETCH_ASSOC);
    $incomeTotal = $incomeResult && $incomeResult['total'] ? (float)$incomeResult['total'] : 0;
    
    // Calcul des revenus à partir des paiements mensuels
    $mpParams = [];
    $mpWhereClause = "WHERE payment_status = 'paid'";
    
    if ($startDate && $endDate) {
        $mpWhereClause .= " AND payment_date BETWEEN ? AND ?";
        $mpParams = [$startDate, $endDate];
    } elseif ($startDate) {
        $mpWhereClause .= " AND payment_date >= ?";
        $mpParams = [$startDate];
    } elseif ($endDate) {
        $mpWhereClause .= " AND payment_date <= ?";
        $mpParams = [$endDate];
    }
    
    $mpQuery = "SELECT SUM(amount_paid) as total FROM monthly_payments {$mpWhereClause}";
    $stmt = $db->prepare($mpQuery);
    $stmt->execute($mpParams);
    $mpResult = $stmt->fetch(PDO::FETCH_ASSOC);
    $monthlyPaymentsTotal = $mpResult && $mpResult['total'] ? (float)$mpResult['total'] : 0;
    
    // Total des revenus = revenus de la table income + revenus des paiements mensuels
    return $incomeTotal + $monthlyPaymentsTotal;
}
EOT;
    
    // Remplacement de l'ancienne fonction par la nouvelle
    $newContent = str_replace($oldFunction, $newFunction, $content);
    file_put_contents($functionsFile, $newContent);
    
    echo "<p>La fonction calculateTotalIncome a été mise à jour pour inclure les paiements mensuels dans le calcul des revenus totaux.</p>";
} else {
    echo "<p>La fonction calculateTotalIncome n'a pas été trouvée dans le fichier functions.php.</p>";
}

// Création d'un fichier pour afficher les revenus par source dans les rapports
$incomeReportFile = 'reports/income_report.php';
$incomeReportContent = <<<'EOT'
<?php
/**
 * Rapport des revenus par source
 */

require_once '../config.php';
require_once '../database/init.php';
require_once '../includes/functions.php';

// Vérification de l'authentification
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Récupération des paramètres de date
$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');

// Calcul des revenus par source
function getIncomeBySource($startDate, $endDate) {
    global $db;
    
    // Revenus de la table income
    $incomeQuery = "SELECT source, SUM(amount) as total FROM income 
                    WHERE payment_date BETWEEN ? AND ? 
                    GROUP BY source";
    $stmt = $db->prepare($incomeQuery);
    $stmt->execute([$startDate, $endDate]);
    $incomeResult = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Revenus des paiements mensuels
    $mpQuery = "SELECT SUM(amount_paid) as total FROM monthly_payments 
                WHERE payment_status = 'paid' AND payment_date BETWEEN ? AND ?";
    $stmt = $db->prepare($mpQuery);
    $stmt->execute([$startDate, $endDate]);
    $mpResult = $stmt->fetch(PDO::FETCH_ASSOC);
    $monthlyPaymentsTotal = $mpResult && $mpResult['total'] ? (float)$mpResult['total'] : 0;
    
    // Regroupement des revenus par source
    $incomeBySource = [];
    foreach ($incomeResult as $row) {
        $incomeBySource[$row['source']] = (float)$row['total'];
    }
    
    // Ajout des revenus des paiements mensuels
    if ($monthlyPaymentsTotal > 0) {
        if (isset($incomeBySource['monthly_subscription'])) {
            $incomeBySource['monthly_subscription'] += $monthlyPaymentsTotal;
        } else {
            $incomeBySource['monthly_subscription'] = $monthlyPaymentsTotal;
        }
    }
    
    return $incomeBySource;
}

// Calcul des revenus par source
$incomeBySource = getIncomeBySource($startDate, $endDate);
$totalIncome = array_sum($incomeBySource);

// Fonction pour formater les montants
function formatAmount($amount) {
    return number_format($amount, 2) . ' د.م.';
}

// Fonction pour traduire les sources de revenus
function translateSource($source) {
    switch ($source) {
        case 'subscription':
            return 'Abonnements annuels';
        case 'monthly_subscription':
            return 'Abonnements mensuels';
        case 'donation':
            return 'Dons';
        case 'event':
            return 'Événements';
        case 'other':
            return 'Autres';
        default:
            return $source;
    }
}

// Affichage du rapport
?>
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rapport des revenus par source</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>
    <?php include_once '../includes/header.php'; ?>
    
    <div class="container mt-4">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i> Rapport des revenus par source</h5>
                    </div>
                    <div class="card-body">
                        <form method="get" class="mb-4">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="start_date">Date de début</label>
                                        <input type="date" id="start_date" name="start_date" class="form-control" value="<?php echo $startDate; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="end_date">Date de fin</label>
                                        <input type="date" id="end_date" name="end_date" class="form-control" value="<?php echo $endDate; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary d-block w-100">Filtrer</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                        
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Source</th>
                                        <th>Montant</th>
                                        <th>Pourcentage</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($incomeBySource as $source => $amount): ?>
                                    <tr>
                                        <td><?php echo translateSource($source); ?></td>
                                        <td><?php echo formatAmount($amount); ?></td>
                                        <td><?php echo number_format(($amount / $totalIncome) * 100, 1) . '%'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot class="table-light">
                                    <tr>
                                        <th>Total</th>
                                        <th><?php echo formatAmount($totalIncome); ?></th>
                                        <th>100%</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        
                        <div class="mt-4">
                            <canvas id="incomeChart" width="400" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php include_once '../includes/footer.php'; ?>
    
    <script src="../assets/js/jquery.min.js"></script>
    <script src="../assets/js/bootstrap.bundle.min.js"></script>
    <script src="../assets/js/chart.min.js"></script>
    <script>
        // Création du graphique des revenus par source
        var ctx = document.getElementById('incomeChart').getContext('2d');
        var incomeChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: [<?php echo "'" . implode("', '", array_map('translateSource', array_keys($incomeBySource))) . "'"; ?>],
                datasets: [{
                    data: [<?php echo implode(', ', array_values($incomeBySource)); ?>],
                    backgroundColor: [
                        'rgba(54, 162, 235, 0.7)',
                        'rgba(255, 99, 132, 0.7)',
                        'rgba(255, 206, 86, 0.7)',
                        'rgba(75, 192, 192, 0.7)',
                        'rgba(153, 102, 255, 0.7)'
                    ],
                    borderColor: [
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 99, 132, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Répartition des revenus par source'
                    }
                }
            }
        });
    </script>
</body>
</html>
EOT;

file_put_contents($incomeReportFile, $incomeReportContent);
echo "<p>Un nouveau rapport des revenus par source a été créé : <a href='reports/income_report.php'>Rapport des revenus</a></p>";

// Test de la fonction calculateTotalIncome
echo "<h2>Test de la fonction calculateTotalIncome</h2>";

// Inclusion du fichier functions.php mis à jour
require_once 'includes/functions.php';

// Calcul des revenus pour le mois en cours
$currentMonth = date('Y-m-01');
$endOfMonth = date('Y-m-t');

// Calcul des revenus avec la fonction mise à jour
$totalIncome = calculateTotalIncome($currentMonth, $endOfMonth);

// Calcul séparé des revenus de la table income
$incomeQuery = "SELECT SUM(amount) as total FROM income WHERE payment_date BETWEEN ? AND ?";
$stmt = $db->prepare($incomeQuery);
$stmt->execute([$currentMonth, $endOfMonth]);
$incomeResult = $stmt->fetch(PDO::FETCH_ASSOC);
$incomeTotal = $incomeResult && $incomeResult['total'] ? (float)$incomeResult['total'] : 0;

// Calcul séparé des revenus des paiements mensuels
$mpQuery = "SELECT SUM(amount_paid) as total FROM monthly_payments WHERE payment_status = 'paid' AND payment_date BETWEEN ? AND ?";
$stmt = $db->prepare($mpQuery);
$stmt->execute([$currentMonth, $endOfMonth]);
$mpResult = $stmt->fetch(PDO::FETCH_ASSOC);
$monthlyPaymentsTotal = $mpResult && $mpResult['total'] ? (float)$mpResult['total'] : 0;

// Affichage des résultats
echo "<p>Période : du " . date('d/m/Y', strtotime($currentMonth)) . " au " . date('d/m/Y', strtotime($endOfMonth)) . "</p>";
echo "<ul>";
echo "<li>Revenus de la table income : " . number_format($incomeTotal, 2) . " د.م.</li>";
echo "<li>Revenus des paiements mensuels : " . number_format($monthlyPaymentsTotal, 2) . " د.م.</li>";
echo "<li>Total des revenus (calculé séparément) : " . number_format($incomeTotal + $monthlyPaymentsTotal, 2) . " د.م.</li>";
echo "<li>Total des revenus (fonction calculateTotalIncome) : " . number_format($totalIncome, 2) . " د.م.</li>";
echo "</ul>";

if ($totalIncome == ($incomeTotal + $monthlyPaymentsTotal)) {
    echo "<p style='color:green;font-weight:bold;'>✓ La fonction calculateTotalIncome fonctionne correctement !</p>";
} else {
    echo "<p style='color:red;font-weight:bold;'>✗ La fonction calculateTotalIncome ne calcule pas correctement le total des revenus.</p>";
}

// Ajout d'un lien vers le tableau de bord
echo "<p><a href='dashboard.php' class='btn btn-primary'>Retour au tableau de bord</a></p>";
?>
