<?php
// File: /fuelpos/admin_login.php
// Login page (project root). Detecta rol de administrador y redirige acorde.
// Actualizado para funcionar tras cambiar users.role a VARCHAR.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/init.php';
if (session_status() === PHP_SESSION_NONE) session_start();

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

try {
    $pdo = pdo();
} catch (Throwable $e) {
    http_response_code(500);
    echo "<h3>Error inicializando la aplicación</h3><pre>" . esc($e->getMessage()) . "</pre>";
    exit;
}

/**
 * Encuentra la primera columna tipo "password" disponible
 */
function first_existing_col_local(PDO $pdo, array $names) {
    foreach ($names as $n) {
        $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='users' AND COLUMN_NAME = ?");
        $st->execute([$n]);
        if ((int)$st->fetchColumn() > 0) return $n;
    }
    return null;
}
$pwdCol = first_existing_col_local($pdo, ['password','password_hash','passwd','pass']);

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username === '' || $password === '') {
        $err = 'Usuario y contraseña son requeridos.';
    } else {
        // Selecciona usando la columna de password detectada (si existe)
        if ($pwdCol) {
            $sql = "SELECT id, username, {$pwdCol} AS pwd FROM users WHERE username = ? LIMIT 1";
        } else {
            $sql = "SELECT id, username, '' AS pwd FROM users WHERE username = ? LIMIT 1";
        }

        try {
            $st = $pdo->prepare($sql);
            $st->execute([$username]);
            $u = $st->fetch(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            error_log("admin_login.php DB error: " . $e->getMessage());
            $u = false;
            $err = 'Error consultando la base de datos.';
        }

        if (!$u) {
            $err = $err ?: 'Usuario no encontrado.';
        } else {
            $hash = $u['pwd'] ?? '';
            $ok = false;

            if ($pwdCol && $hash) {
                // Si parece ser un hash bcrypt/argon2 => password_verify
                if (is_string($hash) && (strpos($hash, '$2y$') === 0 || strpos($hash, '$2a$') === 0 || stripos($hash,'argon2') !== false)) {
                    if (password_verify($password, $hash)) $ok = true;
                } else {
                    // Fallback: comparación directa (legacy)
                    if ($password === $hash) $ok = true;
                }
            } else {
                $err = 'La tabla users no tiene columna de contraseñas configurada.';
            }

            if ($ok) {
                // Cargar roles desde user_roles (recomendado)
                $roles = [];
                try {
                    $ridSt = $pdo->prepare("SELECT r.id, r.name FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?");
                    $ridSt->execute([$u['id']]);
                    $roles = $ridSt->fetchAll(PDO::FETCH_ASSOC);
                } catch (Throwable $e) {
                    error_log("admin_login.php roles load error: " . $e->getMessage());
                }

                // Guardar sesión
                session_regenerate_id(true);
                $_SESSION['user_id'] = (int)$u['id'];
                $_SESSION['username'] = $u['username'];
                $_SESSION['roles'] = $roles;

                // Determinar si es administrador:
                // 1) Revisa roles asociados (user_roles -> roles)
                // 2) Fallback: revisa columna users.role (ahora VARCHAR)
                $isAdmin = false;
                foreach ($roles as $r) {
                    $n = strtolower($r['name'] ?? '');
                    if (in_array($n, ['administrator','admin','administrador'])) { $isAdmin = true; break; }
                }
                if (!$isAdmin) {
                    // fallback: leer users.role (texto) y comparar
                    try {
                        $st2 = $pdo->prepare("SELECT COALESCE(role, '') AS role_text FROM users WHERE id = ? LIMIT 1");
                        $st2->execute([$u['id']]);
                        $roleText = (string)$st2->fetchColumn();
                        if ($roleText !== '') {
                            $parts = array_map('trim', explode(',', strtolower($roleText)));
                            foreach ($parts as $p) {
                                if (in_array($p, ['administrator','admin','administrador'])) { $isAdmin = true; break; }
                            }
                        }
                    } catch (Throwable $e) {
                        // ignore fallback error but log it
                        error_log("admin_login.php fallback role_text error: " . $e->getMessage());
                    }
                }

                $_SESSION['is_admin'] = $isAdmin ? 1 : 0;

                // Redirige: admin -> admin/index.php ; otros -> index.php
                if ($isAdmin) {
                    header('Location: ' . site('admin/index.php'));
                    exit;
                } else {
                    header('Location: ' . site('index.php'));
                    exit;
                }
            } else {
                $err = $err ?: 'Contraseña inválida.';
            }
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Admin - Login</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>body{background:#f8f9fa}</style>
</head>
<body>
  <div class="container py-5">
    <div class="row justify-content-center">
      <div class="col-md-5">
        <div class="card shadow-sm">
          <div class="card-body">
            <h4 class="card-title mb-3">Acceso</h4>
            <?php if (!empty($err)): ?>
              <div class="alert alert-danger"><?= esc($err) ?></div>
            <?php endif; ?>
            <form method="post" autocomplete="off">
              <div class="mb-3">
                <label class="form-label">Usuario</label>
                <input class="form-control" name="username" value="<?= esc($_POST['username'] ?? '') ?>" required>
              </div>
              <div class="mb-3">
                <label class="form-label">Contraseña</label>
                <input class="form-control" name="password" type="password" required>
              </div>
              <div>
                <button class="btn btn-primary w-100" type="submit">Entrar</button>
              </div>
            </form>
            <div class="mt-3 small text-muted">
              <?php if (!$pwdCol): ?>
                Nota: la tabla users no parece tener una columna de contraseñas (password). Añade la columna <code>password</code> para habilitar acceso por contraseña.
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</body>
</html>