<?php
/**
 * Script de Reparación Crítica
 */
require_once 'includes/db.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>Reparación Crítica de Tablas</h1>";

$tables = [
    'companies' => "CREATE TABLE companies (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        user_id INT NOT NULL UNIQUE, 
        company_name VARCHAR(100) NOT NULL, 
        description TEXT, 
        website VARCHAR(255), 
        address VARCHAR(255), 
        phone VARCHAR(20), 
        logo VARCHAR(255), 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    )",
    'students' => "CREATE TABLE students (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        user_id INT NOT NULL UNIQUE, 
        career_id INT, 
        dni VARCHAR(20), 
        birth_date DATE, 
        address TEXT, 
        phone VARCHAR(20), 
        graduation_year YEAR, 
        resume TEXT, 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    )",
    'teachers' => "CREATE TABLE teachers (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        user_id INT NOT NULL UNIQUE, 
        career_id INT, 
        bio TEXT, 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    )",
    'graduates' => "CREATE TABLE graduates (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        user_id INT NOT NULL UNIQUE, 
        career_id INT, 
        status ENUM('active', 'inactive') DEFAULT 'active', 
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    )"
];

foreach ($tables as $name => $sql) {
    try {
        $pdo->exec($sql);
        echo "<p style='color:green'>✅ Tabla <strong>$name</strong> creada exitosamente.</p>";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'already exists') !== false || strpos($e->getMessage(), 'exists') !== false) {
            echo "<p style='color:blue'>✔ Tabla <strong>$name</strong> ya existe.</p>";
        } else {
            echo "<p style='color:red'>❌ Error en $name: " . $e->getMessage() . "</p>";
        }
    }
}

echo "<h2>Finalizado. Prueba el Dashboard ahora.</h2>";
?>
