<?php
/**
 * Antara — shared admin layout.
 * Each admin page does:
 *   $page = 'users'; $pageTitle = '...'; require __DIR__ . '/../_layout.php';
 *   ...content...
 *   require __DIR__ . '/../_layout_footer.php';
 */

require_once __DIR__ . '/../includes/install_public.php';
antara_install_redirect_if_active();

require_once __DIR__ . '/../core/auth/bootstrap_auth.php';
require_once __DIR__ . '/../core/auth/profile_image.php';
require_once __DIR__ . '/../core/auth/profile_image_ops.php';

$script = $_SERVER['SCRIPT_NAME'] ?? '';
$scriptNorm = str_replace('\\', '/', $script);
// admin pages live at /…/admin/users/*.php → project root is three levels up from the script file.
$projectBase = rtrim(dirname($scriptNorm, 3), '/');

try {
    $cfg = AntaraStore::configRead();
} catch (\RuntimeException $e) {
    require_once __DIR__ . '/../core/auth/vault_config_recovery.php';
    antara_vault_config_recovery_respond_and_exit($e);
}
$loginGloballyRequired = !empty($cfg['login_required']);

$adminActiveUserCount = 0;
foreach ((AntaraStore::usersAll()['users'] ?? []) as $_au) {
    if (empty($_au['deletedAt'])) {
        $adminActiveUserCount++;
    }
}
$adminNeedsFirstWizard = !$loginGloballyRequired && $adminActiveUserCount === 0;

$adminWorkspaceBranches = [];
$adminDeploymentKind = 'personal';
require_once dirname(__DIR__) . '/includes/grid_default_settings.php';
require_once dirname(__DIR__) . '/includes/settings_helpers.php';
$__settingsPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'settings.json';
$__settingsBak = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'settings.json.bak';
$__swAdmin = grid_read_settings_for_api($__settingsPath, $__settingsBak, grid_app_default_settings());
$adminWorkspaceBranches = isset($__swAdmin['branches']) && is_array($__swAdmin['branches']) ? $__swAdmin['branches'] : [];
$adminDeploymentKind = in_array(($__swAdmin['deploymentKind'] ?? ''), ['personal', 'company'], true)
    ? (string)$__swAdmin['deploymentKind']
    : 'personal';

$adminClientLogoRel = trim((string)($__swAdmin['clientLogoRel'] ?? ''));
$adminClientLogoFrame = isset($__swAdmin['clientLogoMediaFrame']) && is_array($__swAdmin['clientLogoMediaFrame'])
    ? $__swAdmin['clientLogoMediaFrame']
    : null;
$adminClientLogoKind = null;
$adminClientLogoUrl = '';
if ($adminClientLogoRel !== '' && strpos($adminClientLogoRel, '..') === false) {
    $adminClientLogoKind = antara_user_profile_media_kind('/' . ltrim($adminClientLogoRel, '/'));
    $adminClientLogoUrl = ($projectBase === '' ? '' : $projectBase) . '/' . ltrim(str_replace('\\', '/', $adminClientLogoRel), '/');
}

$user = null;

if (AntaraSession::isLoggedIn()) {
    $user = AntaraStore::findUserById(AntaraSession::user()['id']);
    if ($user && AntaraSession::isExpired((int)$cfg['session_timeout_minutes'])) {
        AntaraSession::destroy();
        $user = null;
        if ($loginGloballyRequired) {
            $back = antara_public_auth_entry_url() . (antara_install_is_active() ? '' : ('?reason=expired&next=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '')));
            header('Location: ' . $back, true, 302);
            exit;
        }
    }
    if (AntaraSession::isLoggedIn()) {
        $user = AntaraStore::findUserById(AntaraSession::user()['id']);
    } else {
        $user = null;
    }
    if ($user) {
        if (!empty($user['deletedAt']) || empty($user['active']) || !empty($user['blocked'])) {
            AntaraSession::destroy();
            $user = null;
            if ($loginGloballyRequired) {
                $loginUrl = antara_public_auth_entry_url() . (antara_install_is_active() ? '' : '?reason=blocked');
                header('Location: ' . $loginUrl, true, 302);
                exit;
            }
        } elseif (!in_array($user['role'] ?? '', [AntaraStore::ROLE_SUPER, AntaraStore::ROLE_ADMIN], true)) {
            require_once dirname(__DIR__) . '/includes/install_public.php';
            antara_install_render_help_page([
                'title' => '403 — Panel de administración',
                'message' => 'No tienes permisos para entrar al panel de administración. Solo cuentas con rol de administrador pueden acceder.',
                'show_install_link' => true,
                'http_status' => 403,
            ]);
        }
    }
} elseif ($loginGloballyRequired) {
    // Con login obligatorio en todo el sistema, el panel admin también exige sesión.
    $back = antara_public_auth_entry_url() . (antara_install_is_active() ? '' : ('?reason=login_required&next=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '')));
    header('Location: ' . $back, true, 302);
    exit;
}

// Sin sesión y escritorio público (login_required=false): se muestra el panel para configurar;
// las acciones API siguen exigiendo rol admin/super_admin tras iniciar sesión aquí.

$csrf = AntaraCsrf::token();

if ($user) {
    AntaraSession::touch();
}

$apiUrl = ($projectBase === '' ? '' : $projectBase) . '/core/auth/api.php';
$logoutUrl = antara_public_auth_entry_url();

function admin_asset_url(string $rel): string {
    global $projectBase;
    $relClean = ltrim($rel, '/');
    $full = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relClean);
    $v = @filemtime($full) ?: time();
    $base = $projectBase ?? '';
    return ($base === '' ? '' : $base) . '/' . $relClean . '?v=' . rawurlencode((string)$v);
}

$page = $page ?? 'users';
$pageTitle = $pageTitle ?? 'Antara — Admin';
$adminBase = ($projectBase === '' ? '' : $projectBase) . '/admin';
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="color-scheme" content="dark" />
  <meta name="referrer" content="same-origin" />
  <title><?php echo htmlspecialchars($pageTitle); ?></title>
  <link rel="stylesheet" href="<?php echo htmlspecialchars(admin_asset_url('assets/auth/admin.css'), ENT_QUOTES); ?>" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(antara_vendor_asset_url(ANTARA_VENDOR_CROPPER_CSS, $projectBase), ENT_QUOTES); ?>" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(admin_asset_url('assets/auth/image_editor.css'), ENT_QUOTES); ?>" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(admin_asset_url('assets/css/app-dialog.css'), ENT_QUOTES); ?>" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(admin_asset_url('assets/css/tooltips.css'), ENT_QUOTES); ?>" />
</head>
<body>
  <div class="admin-shell">
    <aside class="admin-sidebar">
      <div class="admin-brand">
        <?php if ($adminClientLogoUrl !== ''): ?>
        <div class="admin-brand__logo-wrap" data-antara-client-logo-wrap<?php if ($adminClientLogoFrame !== null): ?> data-client-logo-frame="<?php echo htmlspecialchars(json_encode($adminClientLogoFrame, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8'); ?>"<?php endif; ?>>
          <img class="admin-brand__logo" data-antara-profile-img src="<?php echo htmlspecialchars($adminClientLogoUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="" width="36" height="36" loading="lazy" decoding="async" <?php echo $adminClientLogoKind === 'video' ? 'hidden' : ''; ?> />
          <span class="admin-brand__logo-ph" data-antara-profile-ph aria-hidden="true" hidden><?php echo htmlspecialchars(strtoupper(substr((string)($cfg['rp_name'] ?? 'F'), 0, 1)), ENT_QUOTES, 'UTF-8'); ?></span>
        </div>
        <?php endif; ?>
        <span class="admin-brand__text"><?php echo htmlspecialchars($cfg['rp_name'] ?? 'FLEXIA'); ?></span>
      </div>
      <nav class="admin-nav">
        <a href="<?php echo htmlspecialchars($adminBase . '/users/'); ?>" class="<?php echo $page === 'users' ? 'is-active' : ''; ?>">Usuarios</a>
        <?php if ($adminDeploymentKind === 'company'): ?>
          <a href="<?php echo htmlspecialchars($adminBase . '/users/org.php'); ?>" class="<?php echo $page === 'org' ? 'is-active' : ''; ?>">Organización</a>
        <?php endif; ?>
        <?php if ($user && ($user['role'] ?? '') === AntaraStore::ROLE_SUPER): ?>
          <a href="<?php echo htmlspecialchars($adminBase . '/users/config.php'); ?>" class="<?php echo $page === 'config' ? 'is-active' : ''; ?>">Configuración de acceso</a>
        <?php elseif ($user): ?>
          <a class="is-disabled" title="Solo super_admin">Configuración (super_admin)</a>
        <?php else: ?>
          <a href="<?php echo htmlspecialchars($adminBase . '/users/config.php'); ?>" class="<?php echo $page === 'config' ? 'is-active' : ''; ?>">Configuración de acceso</a>
        <?php endif; ?>
        <a href="<?php echo htmlspecialchars($adminBase . '/users/logs.php'); ?>" class="<?php echo $page === 'logs' ? 'is-active' : ''; ?>">Logs de seguridad</a>
        <a href="<?php echo htmlspecialchars(($projectBase === '' ? '' : $projectBase) . '/index.php'); ?>">Cerrar ventana de usuario</a>
      </nav>
      <div class="admin-user">
        <?php if ($user): ?>
        <?php
        $__prof = antara_user_profile_image_rel($user);
        $__base = ($projectBase === '' ? '' : $projectBase);
        $__src = '';
        if ($__prof !== null && $__prof !== '') {
            $__src = preg_match('#^https?://#i', $__prof) ? $__prof : $__base . ($__prof[0] === '/' ? $__prof : '/' . $__prof);
        }
        $__initial = strtoupper(substr((string)($user['username'] ?: $user['email'] ?: '?'), 0, 1));
        ?>
        <div class="admin-user__row">
          <div class="admin-user__avatar-wrap" data-antara-profile-wrap="<?php echo htmlspecialchars((string)($user['id'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>">
            <img class="admin-user__avatar" data-antara-profile-img src="<?php echo $__src !== '' ? htmlspecialchars($__src, ENT_QUOTES, 'UTF-8') : ''; ?>" alt="" width="40" height="40" loading="lazy" decoding="async" <?php echo $__src === '' ? 'hidden' : ''; ?> />
            <span class="admin-user__avatar admin-user__avatar--placeholder" data-antara-profile-ph aria-hidden="true" <?php echo $__src !== '' ? 'hidden' : ''; ?>><?php echo htmlspecialchars($__initial, ENT_QUOTES, 'UTF-8'); ?></span>
          </div>
          <div class="admin-user__meta">
        <strong><?php echo htmlspecialchars($user['username'] ?: $user['email']); ?></strong>
        <?php echo htmlspecialchars($user['email']); ?><br>
        <span class="badge role-<?php echo htmlspecialchars($user['role']); ?>"><?php echo htmlspecialchars($user['role']); ?></span>
          </div>
        </div>
        <button type="button" class="logout" data-logout="<?php echo htmlspecialchars($logoutUrl); ?>">Cerrar sesión</button>
        <?php else: ?>
        <p class="admin-user__anon-hint">Escritorio público: puedes revisar este panel. Para <strong>editar</strong> usuarios o políticas, inicia sesión con una cuenta <strong>admin</strong> o <strong>super_admin</strong>.</p>
        <form id="admin-anon-login" class="admin-anon-login" method="post" action="#">
          <label for="admin-anon-user">Usuario o correo</label>
          <input type="text" id="admin-anon-user" name="username" autocomplete="username" required />
          <label for="admin-anon-pass">Contraseña</label>
          <input type="password" id="admin-anon-pass" name="password" autocomplete="current-password" required />
          <button type="submit" class="btn btn-primary admin-anon-login__btn">Entrar</button>
          <p id="admin-anon-login-feedback" class="admin-anon-login__feedback" role="status"></p>
        </form>
        <?php endif; ?>
      </div>
    </aside>
    <main class="admin-main">
<?php if (!$user && !$loginGloballyRequired): ?>
      <div class="admin-anon-banner" role="region" aria-label="Modo sin sesión">
        <strong>Panel de administración</strong> — El acceso al escritorio principal no exige login. Las acciones de esta pantalla (listar, crear usuarios, guardar políticas) requieren iniciar sesión con un administrador (formulario a la izquierda). Cuando actives <em>Requerir login para usar el sistema</em>, este panel pedirá sesión siempre.
      </div>
<?php endif; ?>
<?php
// page content is included by the calling file after this require.
