<?php
require_once __DIR__ . '/../app/lib/auth.php';
require_once __DIR__ . '/../app/lib/util.php';

if (file_exists(__DIR__ . '/../app/config.php') === false) { header('Location: install.php'); exit; }

$flash_success = null;
if (isset($_GET['installed'])) $flash_success = "Instalado. Ingresa con tu usuario admin.";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $u = trim($_POST['username'] ?? '');
  $p = (string)($_POST['password'] ?? '');
  if (login($u, $p)) {
    $user = current_user();
    if ($user['role']==='empleado') redirect('my_tasks.php');
    redirect('dashboard.php');
  } else {
    $flash_error = "Usuario/clave incorrectos o usuario inactivo.";
  }
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inventarios - Login</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<style>
  body{ background:#2f5fa3; }
  .card{ border-radius:18px; }
</style>
</head>
<body>
<div class="container" style="max-width:520px; padding-top:80px;">
  <h2 class="text-center text-white mb-4">Inventarios</h2>
  <?php if (!empty($flash_success)): ?><div class="alert alert-success"><?= h($flash_success) ?></div><?php endif; ?>
  <?php if (!empty($flash_error)): ?><div class="alert alert-danger"><?= h($flash_error) ?></div><?php endif; ?>
  <div class="card p-4">
    <form method="post">
      <div class="form-group">
        <label>Usuario</label>
        <input class="form-control" name="username" autofocus required>
      </div>
      <div class="form-group">
        <label>Contraseña</label>
        <input class="form-control" type="password" name="password" required>
      </div>
      <button class="btn btn-success btn-block">Ingresar</button>
    </form>
  </div>
</div>
</body>
</html>
