<?php
/**
 * Script para agregar columnas faltantes a user_permissions
 * Ejecutar desde el navegador
 */

require 'backend/bd/Conexion.php';

echo "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Reparar Tabla</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;'>🔧 Reparar Tabla user_permissions</h1>";

$success = 0;
$errors = 0;

// Lista de columnas a agregar
$columnsToAdd = [
    'view_examenes' => "ALTER TABLE user_permissions ADD COLUMN view_examenes TINYINT(1) DEFAULT 0",
    'edit_examenes' => "ALTER TABLE user_permissions ADD COLUMN edit_examenes TINYINT(1) DEFAULT 0"
];

foreach($columnsToAdd as $columnName => $sql) {
    try {
        $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> $columnName</p>";
        echo "</div>";
        $success++;
    } catch(PDOException $e) {
        if(strpos($e->getMessage(), 'Duplicate column') !== false) {
            echo "<div style='background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #ffc107; margin-bottom: 10px;'>";
            echo "<p style='margin: 0; color: #856404;'><strong>ℹ️ La columna ya existe:</strong> $columnName</p>";
            echo "</div>";
        } else {
            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 con:</strong> $columnName</p>";
            echo "<p style='margin: 5px 0 0 0; color: #721c24; font-size: 12px;'>{$e->getMessage()}</p>";
            echo "</div>";
            $errors++;
        }
    }
}

// Mostrar resumen
echo "<div style='margin-top: 30px; padding: 20px; background: " . ($errors > 0 ? "#fee" : "#e6f7ee") . "; border-radius: 8px; border-left: 4px solid " . ($errors > 0 ? "#c33" : "#28a745") . ";'>";
echo "<h3 style='margin-top: 0; color: " . ($errors > 0 ? "#721c24" : "#155724") . ";'>📊 Resumen</h3>";
echo "<p style='margin: 5px 0; color: " . ($errors > 0 ? "#721c24" : "#155724") . ";'><strong>Columnas agregadas:</strong> $success</p>";
echo "<p style='margin: 5px 0; color: " . ($errors > 0 ? "#721c24" : "#155724") . ";'><strong>Errores:</strong> $errors</p>";
echo "</div>";

// Verificar estructura final
try {
    $columns = $connect->query("SHOW COLUMNS FROM user_permissions")->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3 style='color: #667eea; margin-top: 30px;'>📋 Estructura Actual de la Tabla</h3>";
    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 "</tr></thead><tbody>";
    
    $hasExamenes = false;
    foreach($columns as $i => $col) {
        if($col['Field'] == 'view_examenes' || $col['Field'] == 'edit_examenes') {
            $hasExamenes = true;
        }
        $bg = $i % 2 == 0 ? '#f8f9fc' : 'white';
        $highlight = ($col['Field'] == 'view_examenes' || $col['Field'] == 'edit_examenes') ? 'font-weight: bold; color: #28a745;' : '';
        echo "<tr style='background: $bg;'>";
        echo "<td style='padding: 10px; $highlight'>{$col['Field']}</td>";
        echo "<td style='padding: 10px;'>{$col['Type']}</td>";
        echo "</tr>";
    }
    echo "</tbody></table>";
    
    if($hasExamenes) {
        echo "<div style='margin-top: 20px; padding: 20px; background: #e6f7ee; border-radius: 8px; border-left: 4px solid #28a745;'>";
        echo "<p style='margin: 0; color: #155724;'><strong>✅ ¡Perfecto! Las columnas view_examenes y edit_examenes están presentes.</strong></p>";
        echo "<p style='margin: 10px 0 0 0; color: #155724;'>Ahora puedes crear usuarios con permisos personalizados.</p>";
        echo "</div>";
    }
    
} catch(PDOException $e) {
    echo "<div style='background: #fee; padding: 15px; border-radius: 8px; border-left: 4px solid #c33; margin-top: 20px;'>";
    echo "<p style='margin: 0; color: #721c24;'><strong>❌ Error al verificar estructura:</strong></p>";
    echo "<p style='margin: 5px 0 0 0; color: #721c24; font-size: 12px;'>{$e->getMessage()}</p>";
    echo "</div>";
}

echo "<div style='margin-top: 30px; 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; margin-right: 10px;'>Crear Perfil</a>";
echo "<a href='verificar_permisos.php?username=jrubiano' style='display: inline-block; background: #6c757d; color: white; padding: 12px 30px; border-radius: 8px; text-decoration: none; font-weight: 600;'>Verificar Permisos</a>";
echo "</div>";

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