<?php
require_once __DIR__.'/bootstrap.php';
$message=''; $error='';
if($_SERVER['REQUEST_METHOD']==='POST'){
  try{
    check_csrf(); $server=db(true); $sql=file_get_contents(__DIR__.'/database/schema.sql')."\n".file_get_contents(__DIR__.'/database/upgrade_finanzas.sql')."\n".file_get_contents(__DIR__.'/database/upgrade_parametros.sql')."\n".file_get_contents(__DIR__.'/database/upgrade_capitales.sql');
    if(!$server->multi_query($sql)) throw new RuntimeException($server->error);
    do { if($r=$server->store_result())$r->free(); } while($server->more_results()&&$server->next_result());
    $cn=db();
    $cn->query("INSERT INTO roles(id,nombre,descripcion,es_admin,activo) VALUES(1,'Administrador','Acceso total permanente',1,1) ON DUPLICATE KEY UPDATE nombre='Administrador',descripcion='Acceso total permanente',es_admin=1,activo=1");
    sync_permissions();
    $username=trim($_POST['usuario']??'admin'); $name=trim($_POST['nombre']??'Administrador'); $password=$_POST['password']??'';
    if(strlen($password)<8) throw new RuntimeException('La contraseña debe tener al menos 8 caracteres.');
    $hash=password_hash($password,PASSWORD_DEFAULT);
    $st=$cn->prepare("INSERT INTO usuarios(rol_id,nombre,usuario,password,activo) VALUES(1,?,?,?,1) ON DUPLICATE KEY UPDATE nombre=VALUES(nombre),password=VALUES(password),activo=1");
    $st->bind_param('sss',$name,$username,$hash);$st->execute();$message='Instalación completada. Ya puede iniciar sesió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>Instalar <?=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="container py-5" style="max-width:650px"><div class="card"><div class="card-body p-4 text-center"><img class="login-brand-logo" src="<?=url('assets/img/logo_principal.png')?>" alt="Logo de <?=e(APP_NAME)?>"><h2 class="mt-3"><?=e(APP_NAME)?></h2><p class="text-muted"><?=e(APP_TAGLINE)?></p><?php if($message):?><div class="alert alert-success text-start"><?=e($message)?></div><a class="btn btn-primary" href="<?=url('login.php')?>">Ir al login</a><?php else:?><?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()?>"><div class="mb-3"><label class="form-label">Nombre del administrador</label><input class="form-control" name="nombre" value="Administrador" required></div><div class="mb-3"><label class="form-label">Usuario</label><input class="form-control" name="usuario" value="admin" required></div><div class="mb-3"><label class="form-label">Contraseña inicial</label><input class="form-control" type="password" name="password" minlength="8" required></div><button class="btn btn-primary">Crear base de datos e instalar</button></form><?php endif;?></div></div></div></body></html>
