<?php
/**
 * Script pour trouver et corriger toutes les redirections vers dashboard.php
 */

echo "<h2>🔍 Recherche et Correction des Redirections dashboard.php</h2>\n";

// Fonction pour rechercher récursivement dans les fichiers
function findFilesWithPattern($directory, $pattern) {
    $files = [];
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
    
    foreach ($iterator as $file) {
        if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
            $content = file_get_contents($file->getPathname());
            if (strpos($content, $pattern) !== false) {
                $files[] = $file->getPathname();
            }
        }
    }
    
    return $files;
}

// Fonction pour analyser un fichier et trouver les redirections
function analyzeFile($filePath) {
    $content = file_get_contents($filePath);
    $issues = [];
    
    // Rechercher les patterns de redirection vers dashboard.php
    $patterns = [
        'redirect(getBaseUrl() . \'/dashboard.php\')',
        'redirect(getBaseUrl() . "/dashboard.php")',
        'header(\'Location: dashboard.php\')',
        'header("Location: dashboard.php")',
        'window.location.href = \'dashboard.php\'',
        'window.location.href = "dashboard.php"',
        'href="dashboard.php"',
        'href=\'dashboard.php\'',
        'action="dashboard.php"',
        'action=\'dashboard.php\''
    ];
    
    foreach ($patterns as $pattern) {
        if (strpos($content, $pattern) !== false) {
            $issues[] = [
                'type' => 'dashboard_redirect',
                'pattern' => $pattern,
                'line' => findLineNumber($content, $pattern)
            ];
        }
    }
    
    return $issues;
}

// Fonction pour trouver le numéro de ligne
function findLineNumber($content, $pattern) {
    $lines = explode("\n", $content);
    foreach ($lines as $lineNum => $line) {
        if (strpos($line, $pattern) !== false) {
            return $lineNum + 1;
        }
    }
    return null;
}

// Fonction pour corriger un fichier
function fixFile($filePath) {
    $content = file_get_contents($filePath);
    $originalContent = $content;
    $changes = [];
    
    // Remplacer toutes les occurrences de dashboard.php par dashboard_dynamic.php
    $replacements = [
        'redirect(getBaseUrl() . \'/dashboard.php\')' => 'redirect(getBaseUrl() . \'/dashboard_dynamic.php\')',
        'redirect(getBaseUrl() . "/dashboard.php")' => 'redirect(getBaseUrl() . "/dashboard_dynamic.php")',
        'header(\'Location: dashboard.php\')' => 'header(\'Location: dashboard_dynamic.php\')',
        'header("Location: dashboard.php")' => 'header("Location: dashboard_dynamic.php")',
        'window.location.href = \'dashboard.php\'' => 'window.location.href = \'dashboard_dynamic.php\'',
        'window.location.href = "dashboard.php"' => 'window.location.href = "dashboard_dynamic.php"',
        'href="dashboard.php"' => 'href="dashboard_dynamic.php"',
        'href=\'dashboard.php\'' => 'href=\'dashboard_dynamic.php\'',
        'action="dashboard.php"' => 'action="dashboard_dynamic.php"',
        'action=\'dashboard.php\'' => 'action=\'dashboard_dynamic.php\''
    ];
    
    foreach ($replacements as $old => $new) {
        if (strpos($content, $old) !== false) {
            $content = str_replace($old, $new, $content);
            $changes[] = "Remplacé: {$old} → {$new}";
        }
    }
    
    return [
        'content' => $content,
        'original' => $originalContent,
        'changes' => $changes,
        'modified' => $content !== $originalContent
    ];
}

echo "<h3>1. Recherche des fichiers avec des redirections dashboard.php</h3>\n";

// Rechercher tous les fichiers PHP contenant dashboard.php
$projectRoot = __DIR__;
$filesWithDashboard = findFilesWithPattern($projectRoot, 'dashboard.php');

echo "<p>📁 Fichiers trouvés contenant 'dashboard.php' : " . count($filesWithDashboard) . "</p>\n";

if (empty($filesWithDashboard)) {
    echo "<p>✅ Aucun fichier trouvé avec des redirections vers dashboard.php</p>\n";
} else {
    echo "<ul>\n";
    foreach ($filesWithDashboard as $file) {
        $relativePath = str_replace($projectRoot . '/', '', $file);
        echo "<li><a href='{$relativePath}' target='_blank'>{$relativePath}</a></li>\n";
    }
    echo "</ul>\n";
}

echo "<h3>2. Analyse détaillée des fichiers</h3>\n";

$allIssues = [];
$filesToFix = [];

foreach ($filesWithDashboard as $file) {
    $relativePath = str_replace($projectRoot . '/', '', $file);
    
    // Ignorer les fichiers de sauvegarde
    if (strpos($relativePath, '.backup.') !== false) {
        continue;
    }
    
    echo "<h4>📄 {$relativePath}</h4>\n";
    
    $issues = analyzeFile($file);
    
    if (!empty($issues)) {
        $allIssues[$relativePath] = $issues;
        $filesToFix[] = $file;
        
        echo "<p>⚠️ Problèmes trouvés :</p>\n";
        echo "<ul>\n";
        foreach ($issues as $issue) {
            $lineInfo = $issue['line'] ? " (ligne {$issue['line']})" : "";
            echo "<li>{$issue['pattern']}{$lineInfo}</li>\n";
        }
        echo "</ul>\n";
    } else {
        echo "<p>ℹ️ Aucun problème de redirection trouvé</p>\n";
    }
}

echo "<h3>3. Correction des fichiers</h3>\n";

$fixResults = [];

foreach ($filesToFix as $file) {
    $relativePath = str_replace($projectRoot . '/', '', $file);
    
    echo "<h4>🔧 Correction de {$relativePath}</h4>\n";
    
    try {
        $fixResult = fixFile($file);
        
        if ($fixResult['modified']) {
            // Créer une sauvegarde
            $backupPath = $file . '.backup.' . date('Y-m-d_H-i-s');
            file_put_contents($backupPath, $fixResult['original']);
            
            // Appliquer les changements
            file_put_contents($file, $fixResult['content']);
            
            $fixResults[$relativePath] = [
                'status' => 'success',
                'backup' => basename($backupPath),
                'changes' => $fixResult['changes']
            ];
            
            echo "<p>✅ Fichier corrigé - Sauvegarde créée : " . basename($backupPath) . "</p>\n";
            echo "<p>Changements appliqués :</p>\n";
            echo "<ul>\n";
            foreach ($fixResult['changes'] as $change) {
                echo "<li>{$change}</li>\n";
            }
            echo "</ul>\n";
        } else {
            $fixResults[$relativePath] = [
                'status' => 'no_changes',
                'backup' => null,
                'changes' => 'Aucun changement nécessaire'
            ];
            
            echo "<p>ℹ️ Aucun changement nécessaire</p>\n";
        }
        
    } catch (Exception $e) {
        $fixResults[$relativePath] = [
            'status' => 'error',
            'backup' => null,
            'changes' => 'Erreur : ' . $e->getMessage()
        ];
        
        echo "<p>❌ Erreur lors de la correction : " . $e->getMessage() . "</p>\n";
    }
}

echo "<h3>4. Résumé des Corrections</h3>\n";

$successCount = 0;
$noChangesCount = 0;
$errorCount = 0;

foreach ($fixResults as $file => $result) {
    switch ($result['status']) {
        case 'success':
            $successCount++;
            break;
        case 'no_changes':
            $noChangesCount++;
            break;
        case 'error':
            $errorCount++;
            break;
    }
}

echo "<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 10px 0;'>\n";
echo "<p><strong>Statistiques des corrections :</strong></p>\n";
echo "<ul>\n";
echo "<li>✅ Corrections réussies : {$successCount}</li>\n";
echo "<li>ℹ️ Aucun changement nécessaire : {$noChangesCount}</li>\n";
echo "<li>❌ Erreurs : {$errorCount}</li>\n";
echo "</ul>\n";
echo "</div>\n";

// Détails des résultats
echo "<h3>📋 Détails des Résultats</h3>\n";
echo "<table border='1' style='border-collapse: collapse; width: 100%;'>\n";
echo "<tr><th>Fichier</th><th>Statut</th><th>Changements</th></tr>\n";

foreach ($fixResults as $file => $result) {
    $statusColor = '';
    $statusIcon = '';
    
    switch ($result['status']) {
        case 'success':
            $statusColor = 'color: green;';
            $statusIcon = '✅';
            break;
        case 'no_changes':
            $statusColor = 'color: blue;';
            $statusIcon = 'ℹ️';
            break;
        case 'error':
            $statusColor = 'color: red;';
            $statusIcon = '❌';
            break;
    }
    
    echo "<tr>\n";
    echo "<td>{$file}</td>\n";
    echo "<td style='{$statusColor}'>{$statusIcon} {$result['status']}</td>\n";
    echo "<td>" . implode(', ', $result['changes']) . "</td>\n";
    echo "</tr>\n";
}

echo "</table>\n";

// Vérification finale
echo "<h3>5. Vérification Finale</h3>\n";

$remainingFiles = findFilesWithPattern($projectRoot, 'dashboard.php');
$remainingCount = 0;

foreach ($remainingFiles as $file) {
    $relativePath = str_replace($projectRoot . '/', '', $file);
    if (strpos($relativePath, '.backup.') === false) {
        $remainingCount++;
    }
}

if ($remainingCount === 0) {
    echo "<p>✅ Aucune redirection vers dashboard.php trouvée !</p>\n";
} else {
    echo "<p>⚠️ {$remainingCount} fichier(s) contiennent encore 'dashboard.php'</p>\n";
    echo "<p>Vérifiez manuellement ces fichiers :</p>\n";
    echo "<ul>\n";
    foreach ($remainingFiles as $file) {
        $relativePath = str_replace($projectRoot . '/', '', $file);
        if (strpos($relativePath, '.backup.') === false) {
            echo "<li><a href='{$relativePath}' target='_blank'>{$relativePath}</a></li>\n";
        }
    }
    echo "</ul>\n";
}

// Instructions post-correction
echo "<h3>🚀 Instructions Post-Correction</h3>\n";
echo "<div style='background: #d1ecf1; padding: 15px; border-radius: 5px; margin: 10px 0; border: 1px solid #bee5eb;'>\n";
echo "<p><strong>Étapes suivantes :</strong></p>\n";
echo "<ol>\n";
echo "<li><strong>Testez la connexion réceptionniste</strong> : Allez sur <a href='login.php'>http://localhost:81/StayManager/login.php</a></li>\n";
echo "<li><strong>Connectez-vous avec cedric</strong> : cedric / [mot de passe]</li>\n";
echo "<li><strong>Vérifiez toutes les pages</strong> : Aucune ne devrait rediriger vers dashboard.php</li>\n";
echo "<li><strong>Testez les actions</strong> : Créer, modifier, supprimer des clients</li>\n";
echo "<li><strong>Vérifiez les redirections</strong> : Toutes devraient aller vers dashboard_dynamic.php</li>\n";
echo "</ol>\n";
echo "</div>\n";

// Sauvegarde des résultats
$correctionLog = [
    'date' => date('Y-m-d H:i:s'),
    'files_found' => count($filesWithDashboard),
    'files_fixed' => count($filesToFix),
    'results' => $fixResults,
    'summary' => [
        'success' => $successCount,
        'no_changes' => $noChangesCount,
        'errors' => $errorCount
    ]
];

$logFile = __DIR__ . '/logs/dashboard_redirects_fix_' . date('Y-m-d_H-i-s') . '.json';
if (!is_dir(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0755, true);
}

file_put_contents($logFile, json_encode($correctionLog, JSON_PRETTY_PRINT));

echo "<p>📝 Log de correction sauvegardé : " . basename($logFile) . "</p>\n";

echo "<div style='background: #d4edda; padding: 15px; border-radius: 5px; margin: 10px 0; border: 1px solid #c3e6cb;'>\n";
echo "<p><strong>🎉 Recherche et correction terminées !</strong></p>\n";
echo "<p>Toutes les redirections vers dashboard.php ont été identifiées et corrigées.</p>\n";
echo "<p>Vous pouvez maintenant profiter de :</p>\n";
echo "<ul>\n";
echo "<li>✅ Redirections cohérentes vers dashboard_dynamic.php</li>\n";
echo "<li>✅ Interface moderne et dynamique</li>\n";
echo "<li>✅ Meilleure expérience utilisateur</li>\n";
echo "<li>✅ Système de permissions unifié</li>\n";
echo "</ul>\n";
echo "</div>\n";
?>
