<?php
/**
 * Script para actualizar la tabla user_permissions agregando columnas faltantes
 * Ejecutar una sola vez desde el navegador
 */

require 'backend/bd/Conexion.php';

echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Actualizar Tabla Permisos</title></head>";
echo "<body style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; font-family: Arial;'>";
echo "<div style='max-width: 800px; margin: 0 auto; background: white; border-radius: 16px; padding: 30px; box-shadow: 0 10px 40px rgba(0,0,0,0.2);'>";
echo "<h1 style='color: #667eea; margin-bottom: 20px;'>🔧 Actualizar Tabla user_permissions</h1>";

try {
    // Verificar si la tabla existe
    $tableExists = $connect->query("SHOW TABLES LIKE 'user_permissions'")->rowCount() > 0;
    
    if(!$tableExists) {
        echo "<div style='background: #fee; padding: 20px; border-radius: 8px; border-left: 4px solid #c33; margin-bottom: 20px;'>";
        echo "<p style='margin: 0; color: #721c24;'><strong>❌ La tabla user_permissions no existe</strong></p>";
        echo "<p style='margin: 10px 0 0 0; color: #721c24;'>Ejecuta primero: crear_tabla_permisos.php</p>";
        echo "</div>";
    } else {
        echo "<div style='background: #e6f7ee; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745; margin-bottom: 20px;'>";
        echo "<p style='margin: 0; color: #155724;'><strong>✅ La tabla user_permissions existe</strong></p>";
        echo "</div>";
        
        // Obtener columnas actuales
        $columns = $connect->query("SHOW COLUMNS FROM user_permissions")->fetchAll(PDO::FETCH_COLUMN);
        
        echo "<h3 style='color: #667eea; margin-top: 30px;'>📋 Columnas Actuales</h3>";
        echo "<ul style='background: #f8f9fc; padding: 20px; border-radius: 8px;'>";
        foreach($columns as $col) {
            echo "<li style='padding: 5px 0;'>$col</li>";
        }
        echo "</ul>";
        
        // Columnas que deberían existir
        $requiredColumns = [
            'view_valoracion_riesgo',
            'edit_valoracion_riesgo',
            'view_signos_vitales',
            'edit_signos_vitales',
            'view_medicamentos',
            'edit_medicamentos',
            'view_diagnostico',
            'edit_diagnostico',
            'view_antecedentes',
            'edit_antecedentes',
            'view_examenes',
            'edit_examenes'
        ];
        
        $missingColumns = array_diff($requiredColumns, $columns);
        
        if(empty($missingColumns)) {
            echo "<div style='background: #e6f7ee; padding: 20px; border-radius: 8px; border-left: 4px solid #28a745; margin-top: 20px;'>";
            echo "<p style='margin: 0; color: #155724;'><strong>✅ Todas las columnas necesarias existen</strong></p>";
            echo "</div>";
        } else {
            echo "<h3 style='color: #667eea; margin-top: 30px;'>🔧 Agregando Columnas Faltantes</h3>";
            
            foreach($missingColumns as $column) {
                try {
                    $sql = "ALTER TABLE user_permissions ADD COLUMN `$column` TINYINT(1) DEFAULT 0";
                    $connect->exec($sql);
                    echo "<div style='background: #e6f7ee; padding: 15px; border-radius: 8px; border-left: 4px solid #28a745; margin-bottom: 10px;'>";
                    echo "<p style='margin: 0; color: #155724;'><strong>✅ Columna agregada:</strong> $column</p>";
                    echo "</div>";
                } catch(PDOException $e) {
                    echo "<div style='background: #fee; padding: 15px; border-radius: 8px; border-left: 4px solid #c33; margin-bottom: 10px;'>";
                    echo "<p style='margin: 0; color: #721c24;'><strong>❌ Error al agregar:</strong> $column</p>";
                    echo "<p style='margin: 5px 0 0 0; color: #721c24; font-size: 12px;'>{$e->getMessage()}</p>";
                    echo "</div>";
                }
            }
        }
        
        // Mostrar estructura final
        echo "<h3 style='color: #667eea; margin-top: 30px;'>📊 Estructura Final de la Tabla</h3>";
        $finalColumns = $connect->query("DESCRIBE user_permissions")->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<table style='width: 100%; border-collapse: collapse; margin-top: 15px;'>";
        echo "<thead><tr style='background: #667eea; color: white;'>";
        echo "<th style='padding: 12px; text-align: left;'>Campo</th>";
        echo "<th style='padding: 12px; text-align: left;'>Tipo</th>";
        echo "<th style='padding: 12px; text-align: left;'>Nulo</th>";
        echo "<th style='padding: 12px; text-align: left;'>Default</th>";
        echo "</tr></thead><tbody>";
        
        $i = 0;
        foreach($finalColumns as $col) {
            $bg = $i % 2 == 0 ? '#f8f9fc' : 'white';
            echo "<tr style='background: $bg;'>";
            echo "<td style='padding: 10px;'><strong>{$col['Field']}</strong></td>";
            echo "<td style='padding: 10px; color: #666;'>{$col['Type']}</td>";
            echo "<td style='padding: 10px; color: #666;'>{$col['Null']}</td>";
            echo "<td style='padding: 10px; color: #666;'>" . ($col['Default'] ?? 'NULL') . "</td>";
            echo "</tr>";
            $i++;
        }
        echo "</tbody></table>";
    }
    
    echo "<div style='margin-top: 30px; padding: 15px; background: #fff3cd; border-radius: 8px; border-left: 4px solid #ffc107;'>";
    echo "<p style='margin: 0; color: #856404;'><strong>💡 Nota:</strong> Ahora puedes crear usuarios con permisos personalizados desde medicos/crear.php</p>";
    echo "</div>";
    
    echo "<div style='margin-top: 20px; text-align: center;'>";
    echo "<a href='frontend/medicos/crear.php' style='display: inline-block; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 30px; border-radius: 8px; text-decoration: none; font-weight: 600;'>Ir a Crear Perfil</a>";
    echo "</div>";
    
} catch(PDOException $e) {
    echo "<div style='background: #fee; padding: 20px; border-radius: 8px; border-left: 4px solid #c33;'>";
    echo "<h3 style='color: #c33; margin-top: 0;'>❌ Error</h3>";
    echo "<pre style='background: white; padding: 15px; border-radius: 8px; overflow-x: auto;'>{$e->getMessage()}</pre>";
    echo "</div>";
}

echo "</div></body></html>";
?>
