<?php
require_once __DIR__.'/bootstrap.php';
if(user())redirect('index.php'); $error='';
if($_SERVER['REQUEST_METHOD']==='POST')try{check_csrf();$st=db()->prepare("SELECT u.*,r.nombre rol FROM usuarios u JOIN roles r ON r.id=u.rol_id WHERE u.usuario=? AND u.activo=1 AND r.activo=1");$login=trim($_POST['usuario']??'');$st->bind_param('s',$login);$st->execute();$u=$st->get_result()->fetch_assoc();if(!$u||!password_verify($_POST['password']??'',$u['password']))throw new RuntimeException('Usuario o contraseña incorrectos.');session_regenerate_id(true);$_SESSION['user']=['id'=>(int)$u['id'],'rol_id'=>(int)$u['rol_id'],'nombre'=>$u['nombre'],'usuario'=>$u['usuario'],'rol'=>$u['rol']];sync_permissions();audit('LOGIN');redirect('index.php');}catch(mysqli_sql_exception $e){$error='El sistema aún no está instalado. Use el enlace de instalación.';}catch(Throwable $e){$error=$e->getMessage();}
?><!doctype html><html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Acceso - <?=e(APP_NAME)?></title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"><link href="<?=url('assets/style.css')?>" rel="stylesheet"><link href="<?=url('assets/branding.css')?>" rel="stylesheet"></head><body><div class="min-vh-100 d-flex align-items-center justify-content-center p-3"><div class="card" style="width:100%;max-width:430px"><div class="card-body p-5 text-center"><img class="login-brand-logo" src="<?=url('assets/img/logo_principal.png')?>" alt="Logo de <?=e(APP_NAME)?>"><h3 class="mt-3"><?=e(APP_NAME)?></h3><p class="text-muted"><?=e(APP_TAGLINE)?></p><?php if($error):?><div class="alert alert-danger text-start"><?=e($error)?></div><?php endif;?><form method="post" class="text-start"><input type="hidden" name="csrf" value="<?=csrf()?>"><label class="form-label">Usuario</label><input class="form-control mb-3" name="usuario" autofocus required><label class="form-label">Contraseña</label><input class="form-control mb-4" type="password" name="password" required><button class="btn btn-primary w-100">Ingresar</button></form><a class="small d-block mt-3" href="<?=url('install.php')?>">Instalar sistema</a></div></div></div></body></html>
