<?php
require_once 'includes/db.php';

echo "<h1>Restableciendo Administrador</h1>";

try {
    // 1. Asegurar que el rol 'administrador' existe
    $stmt = $pdo->prepare("SELECT id FROM roles WHERE name = 'administrador' LIMIT 1");
    $stmt->execute();
    $role = $stmt->fetch();
    
    if (!$role) {
        $pdo->exec("INSERT INTO roles (name) VALUES ('administrador')");
        $role_id = $pdo->lastInsertId();
    } else {
        $role_id = $role['id'];
    }

    // 2. Crear o actualizar el usuario admin
    $username = 'admin';
    $new_password = 'password'; // Cambiado a 'password' para que sea fácil
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
    $email = 'admin@admin.com';

    $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user) {
        $stmt = $pdo->prepare("UPDATE users SET password = ?, role_id = ? WHERE id = ?");
        $stmt->execute([$hashed_password, $role_id, $user['id']]);
        echo "<p>Contraseña de 'admin' actualizada a: <strong>$new_password</strong></p>";
    } else {
        $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role_id, first_name, last_name) VALUES (?, ?, ?, ?, 'Admin', 'System')");
        $stmt->execute([$username, $hashed_password, $email, $role_id]);
        echo "<p>Usuario 'admin' creado exitosamente con contraseña: <strong>$new_password</strong></p>";
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
?>
