<?php
/**
 * Script pour corriger toutes les vues avec les permissions incorrectes
 */

echo "<h2>🔧 Correction de Toutes les Vues - Permissions</h2>\n";

// Liste des vues à vérifier et corriger
$viewsToCheck = [
    // Vues clients
    'views/clients/index.php' => ['old_permission' => 'clients', 'new_permission' => 'clients.view'],
    'views/clients/create.php' => ['old_permission' => 'clients', 'new_permission' => 'clients.create'],
    'views/clients/edit.php' => ['old_permission' => 'clients', 'new_permission' => 'clients.edit'],
    'views/clients/show.php' => ['old_permission' => 'clients', 'new_permission' => 'clients.view'],
    
    // Vues room_planning
    'views/room_planning/index.php' => ['old_permission' => 'reservations', 'new_permission' => 'bookings.view'],
    
    // Vues reservations
    'views/reservations/index.php' => ['old_permission' => 'reservations', 'new_permission' => 'bookings.view'],
    'views/reservations/create.php' => ['old_permission' => 'reservations', 'new_permission' => 'bookings.create'],
    'views/reservations/edit.php' => ['old_permission' => 'reservations', 'new_permission' => 'bookings.edit'],
    'views/reservations/show.php' => ['old_permission' => 'reservations', 'new_permission' => 'bookings.view'],
    
    // Vues rooms
    'views/rooms/index.php' => ['old_permission' => 'rooms', 'new_permission' => 'bookings.view'],
    'views/rooms/create.php' => ['old_permission' => 'rooms', 'new_permission' => 'bookings.create'],
    'views/rooms/edit.php' => ['old_permission' => 'rooms', 'new_permission' => 'bookings.edit'],
    'views/rooms/show.php' => ['old_permission' => 'rooms', 'new_permission' => 'bookings.view'],
    
    // Vues events
    'views/events/index.php' => ['old_permission' => 'events', 'new_permission' => 'events.view'],
    'views/events/create.php' => ['old_permission' => 'events', 'new_permission' => 'events.create'],
    'views/events/edit.php' => ['old_permission' => 'events', 'new_permission' => 'events.edit'],
    'views/events/show.php' => ['old_permission' => 'events', 'new_permission' => 'events.view'],
    
    // Vues event_rooms
    'views/event_rooms/index.php' => ['old_permission' => 'events', 'new_permission' => 'events.view'],
    'views/event_rooms/create.php' => ['old_permission' => 'events', 'new_permission' => 'events.create'],
    'views/event_rooms/edit.php' => ['old_permission' => 'events', 'new_permission' => 'events.edit'],
    'views/event_rooms/show.php' => ['old_permission' => 'events', 'new_permission' => 'events.view'],
    
    // Vues event_bookings
    'views/event_bookings/index.php' => ['old_permission' => 'events', 'new_permission' => 'events.view'],
    'views/event_bookings/create.php' => ['old_permission' => 'events', 'new_permission' => 'events.create'],
    'views/event_bookings/edit.php' => ['old_permission' => 'events', 'new_permission' => 'events.edit'],
    'views/event_bookings/show.php' => ['old_permission' => 'events', 'new_permission' => 'events.view']
];

$fixResults = [];

foreach ($viewsToCheck as $view => $config) {
    $filePath = __DIR__ . '/' . $view;
    
    if (file_exists($filePath)) {
        echo "<h3>📁 Traitement de {$view}</h3>\n";
        
        try {
            $content = file_get_contents($filePath);
            $originalContent = $content;
            $changes = [];
            
            // Vérifier si le fichier contient l'ancienne permission
            if (strpos($content, "hasPermission('{$config['old_permission']}')") !== false) {
                // Remplacer l'ancienne permission par la nouvelle
                $content = str_replace(
                    "hasPermission('{$config['old_permission']}')",
                    "hasPermission('{$config['new_permission']}')",
                    $content
                );
                $changes[] = "Permission {$config['old_permission']} → {$config['new_permission']}";
            }
            
            // Vérifier si le fichier redirige vers dashboard.php
            if (strpos($content, "redirect(getBaseUrl() . '/dashboard.php')") !== false) {
                // Remplacer la redirection par dashboard_dynamic.php
                $content = str_replace(
                    "redirect(getBaseUrl() . '/dashboard.php')",
                    "redirect(getBaseUrl() . '/dashboard_dynamic.php')",
                    $content
                );
                $changes[] = "Redirection dashboard.php → dashboard_dynamic.php";
            }
            
            // Vérifier si des changements ont été effectués
            if ($content !== $originalContent) {
                // Créer une sauvegarde
                $backupPath = $filePath . '.backup.' . date('Y-m-d_H-i-s');
                file_put_contents($backupPath, $originalContent);
                
                // Appliquer les changements
                file_put_contents($filePath, $content);
                
                $fixResults[$view] = [
                    'status' => 'success',
                    'backup' => $backupPath,
                    'changes' => $changes
                ];
                
                echo "<p>✅ Corrections appliquées - Sauvegarde créée : " . basename($backupPath) . "</p>\n";
                echo "<p>Changements : " . implode(', ', $changes) . "</p>\n";
            } else {
                $fixResults[$view] = [
                    'status' => 'no_changes',
                    'backup' => null,
                    'changes' => 'Aucun changement nécessaire'
                ];
                
                echo "<p>ℹ️ Aucun changement nécessaire</p>\n";
            }
            
        } catch (Exception $e) {
            $fixResults[$view] = [
                'status' => 'error',
                'backup' => null,
                'changes' => 'Erreur : ' . $e->getMessage()
            ];
            
            echo "<p>❌ Erreur lors de la correction : " . $e->getMessage() . "</p>\n";
        }
    } else {
        $fixResults[$view] = [
            'status' => 'not_found',
            'backup' => null,
            'changes' => 'Fichier non trouvé'
        ];
        
        echo "<p>⚠️ Fichier non trouvé : {$view}</p>\n";
    }
}

// Résumé des corrections
echo "<h3>📊 Résumé des Corrections</h3>\n";

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

foreach ($fixResults as $view => $result) {
    switch ($result['status']) {
        case 'success':
            $successCount++;
            break;
        case 'no_changes':
            $noChangesCount++;
            break;
        case 'error':
            $errorCount++;
            break;
        case 'not_found':
            $notFoundCount++;
            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 "<li>⚠️ Fichiers non trouvés : {$notFoundCount}</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>Vue</th><th>Statut</th><th>Changements</th></tr>\n";

foreach ($fixResults as $view => $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;
        case 'not_found':
            $statusColor = 'color: orange;';
            $statusIcon = '⚠️';
            break;
    }
    
    echo "<tr>\n";
    echo "<td>{$view}</td>\n";
    echo "<td style='{$statusColor}'>{$statusIcon} {$result['status']}</td>\n";
    echo "<td>" . implode(', ', $result['changes']) . "</td>\n";
    echo "</tr>\n";
}

echo "</table>\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>Testez l'accès aux pages</strong> :</li>\n";
echo "<ul>\n";
echo "<li><a href='clients.php' target='_blank'>Clients</a> - devrait fonctionner</li>\n";
echo "<li><a href='clients.php?action=create' target='_blank'>Nouveau Client</a> - devrait maintenant fonctionner</li>\n";
echo "<li><a href='room_planning.php' target='_blank'>Planning Chambres</a> - devrait fonctionner</li>\n";
echo "</ul>\n";
echo "<li><strong>Vérifiez les boutons</strong> : Tous les boutons devraient maintenant fonctionner</li>\n";
echo "<li><strong>Plus de redirections vers dashboard.php</strong> : Toutes les redirections vont 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'),
    'results' => $fixResults,
    'summary' => [
        'success' => $successCount,
        'no_changes' => $noChangesCount,
        'errors' => $errorCount,
        'not_found' => $notFoundCount
    ]
];

$logFile = __DIR__ . '/logs/views_permissions_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>🎉 Correction des vues terminée avec succès !</strong></p>\n";
echo "<p>Toutes les vues utilisent maintenant les bonnes permissions et redirigent vers dashboard_dynamic.php.</p>\n";
echo "<p>Vous pouvez maintenant profiter de :</p>\n";
echo "<ul>\n";
echo "<li>✅ Permissions cohérentes dans toutes les vues</li>\n";
echo "<li>✅ Redirections vers dashboard_dynamic.php</li>\n";
echo "<li>✅ Boutons et actions fonctionnels</li>\n";
echo "<li>✅ Interface moderne et cohérente</li>\n";
echo "</ul>\n";
echo "</div>\n";
?>
