<?php
/**
 * Login ERP — Laboratorio Ximena Caicedo
 * Con protección contra ataques de fuerza bruta.
 */

require_once 'config/config.php';

if (isUserLoggedIn()) {
    header('Location: index.php');
    exit;
}

$error   = '';
$success = '';
$loginBlocked = false;
$clientIp = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

if (isset($_GET['logged_out']) && $_GET['logged_out'] == '1') {
    $success = 'Sesión cerrada correctamente.';
}
if (isset($_GET['session_expired']) && $_GET['session_expired'] == '1') {
    $error = 'Su sesión ha expirado por inactividad. Por favor, inicie sesión nuevamente.';
}

if (!checkLoginAttempts($clientIp)) {
    $loginBlocked = true;
    $error = 'Demasiados intentos de login. Inténtalo en ' . (LOGIN_LOCKOUT_TIME / 60) . ' minutos.';
}

if ($_POST && !$loginBlocked) {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $adminUser = authenticateUser($username, $password);

    if ($adminUser) {
        clearLoginAttempts($clientIp);
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user']      = $adminUser;
        $_SESSION['last_activity']   = time();
        $_SESSION['login_ip']        = $clientIp;
        $_SESSION['login_time']      = time();

        // Tablet fija: redirigir al lugar asignado por token o IP
        try {
            $_pdo2  = Database::getInstance()->getConnection();
            $_disp  = null;
            $_devToken = trim($_COOKIE['turnero_token'] ?? '');
            if ($_devToken) {
                $_s = $_pdo2->prepare(
                    "SELECT td.lugar_id, td.nombre, tl.tipo
                       FROM turnero_dispositivos td
                       JOIN turnero_lugares tl ON tl.id = td.lugar_id
                      WHERE td.token = ? AND td.activo = 1 LIMIT 1"
                );
                $_s->execute([$_devToken]);
                $_disp = $_s->fetch(PDO::FETCH_ASSOC) ?: null;
            }
            if (!$_disp) {
                $_s = $_pdo2->prepare(
                    "SELECT td.lugar_id, td.nombre, tl.tipo
                       FROM turnero_dispositivos td
                       JOIN turnero_lugares tl ON tl.id = td.lugar_id
                      WHERE td.ip = ? AND td.activo = 1 LIMIT 1"
                );
                $_s->execute([$clientIp]);
                $_disp = $_s->fetch(PDO::FETCH_ASSOC) ?: null;
            }
            if ($_disp) {
                $_SESSION['turnero_dispositivo'] = $_disp;
                $url = $_disp['tipo'] === 'recepcion'
                    ? BASE_URL . 'erp.php?m=turnero&v=recepcion&desk_id=' . $_disp['lugar_id']
                    : BASE_URL . 'erp.php?m=turnero&v=lugar&lugar_id='   . $_disp['lugar_id'];
                header('Location: ' . $url); exit;
            }
        } catch (\Throwable $_) {}

        $roleSlug = $adminUser['role'] ?? 'admin';
        $modules  = $adminUser['modules'] ?? [];

        if (!empty($adminUser['home_page'])) {
            $safePath = filter_var($adminUser['home_page'], FILTER_SANITIZE_URL);
            if (str_starts_with($safePath, '/') && !str_starts_with($safePath, '//')) {
                header('Location: ' . $safePath);
                exit;
            }
        }
        // Usuario con lugar fijo asignado (sin IP registrada)
        $_userLugarId = (int)($adminUser['turnero_lugar_id'] ?? 0);
        if ($_userLugarId && in_array('turnero', $modules, true)) {
            // Determinar si ese lugar es recepción o toma de muestras
            try {
                $_lugarTipo = Database::getInstance()->getConnection()
                    ->prepare("SELECT tipo FROM turnero_lugares WHERE id = ? LIMIT 1");
                $_lugarTipo->execute([$_userLugarId]);
                $_tipo = $_lugarTipo->fetchColumn() ?: 'muestras';
            } catch (\Throwable $_) { $_tipo = 'muestras'; }
            $url = $_tipo === 'recepcion'
                ? BASE_URL . 'erp.php?m=turnero&v=recepcion&desk_id=' . $_userLugarId
                : BASE_URL . 'erp.php?m=turnero&v=lugar&lugar_id='    . $_userLugarId;
            header('Location: ' . $url); exit;
        }

        if ($roleSlug === 'enfermero') {
            header('Location: enfermero_portal.php');
        } elseif (in_array('turnero', $modules, true)) {
            if ($roleSlug === 'bacteriologo') {
                header('Location: erp.php?m=turnero&v=dashboard');
            } elseif (in_array($roleSlug, ['superadmin', 'admin', 'supervisor'], true)) {
                header('Location: erp.php?m=turnero&v=dashboard');
            } else {
                header('Location: erp.php?m=turnero&v=recepcion');
            }
        } elseif (in_array('lab_dashboard', $modules, true)) {
            header('Location: lab_dashboard.php');
        } elseif (in_array('lab_formularios', $modules, true)) {
            header('Location: lab_formularios.php');
        } elseif (in_array('lab_ordenes', $modules, true)) {
            header('Location: lab_ordenes.php');
        } elseif (in_array('whatsapp', $modules, true)) {
            header('Location: index.php');
        } else {
            header('Location: index.php');
        }
        exit;
    } else {
        recordFailedLogin($clientIp);
        $error = 'Usuario o contraseña incorrectos.';
        if (!checkLoginAttempts($clientIp)) {
            $loginBlocked = true;
            $error = 'Demasiados intentos de login. Cuenta bloqueada por ' . (LOGIN_LOCKOUT_TIME / 60) . ' minutos.';
        }
    }
}

// ── Cargar configuración de la empresa para el branding ────────────────────
$cfg = [];
try {
    $db   = Database::getInstance();
    $rows = $db->fetchAll('SELECT clave, valor FROM lab_config ORDER BY clave');
    foreach ($rows as $r) {
        $cfg[$r['clave']] = $r['valor'];
    }
} catch (Exception $e) {
    // BD no disponible: continuar con defaults
}

$empresa  = htmlspecialchars($cfg['empresa_nombre']    ?? 'Laboratorio Clínico', ENT_QUOTES, 'UTF-8');
$subtitulo= htmlspecialchars($cfg['empresa_subtitulo'] ?? 'Sistema de Gestión ERP',  ENT_QUOTES, 'UTF-8');
$color    = preg_match('/^#[0-9a-fA-F]{3,8}$/', $cfg['doc_color'] ?? '') ? $cfg['doc_color'] : '#1565c0';
$logo     = $cfg['doc_logo_base64'] ?? '';

// Calcular color derivado más oscuro para el gradiente
function adjustColor(string $hex, int $amount): string {
    $hex = ltrim($hex, '#');
    $r   = max(0, min(255, hexdec(substr($hex, 0, 2)) + $amount));
    $g   = max(0, min(255, hexdec(substr($hex, 2, 2)) + $amount));
    $b   = max(0, min(255, hexdec(substr($hex, 4, 2)) + $amount));
    return sprintf('#%02x%02x%02x', $r, $g, $b);
}
$colorDark = adjustColor($color, -40);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iniciar Sesión — <?= $empresa ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --brand:      <?= htmlspecialchars($color,     ENT_QUOTES, 'UTF-8') ?>;
            --brand-dark: <?= htmlspecialchars($colorDark, ENT_QUOTES, 'UTF-8') ?>;
        }

        * { box-sizing: border-box; }

        body {
            margin: 0;
            min-height: 100vh;
            font-family: 'Segoe UI', system-ui, sans-serif;
            display: flex;
            overflow: hidden;
        }

        /* ── Panel izquierdo — branding ─────────────────────── */
        .brand-panel {
            flex: 1;
            background: #fff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 3rem 2.5rem;
            position: relative;
            overflow: hidden;
        }

        /* Círculos decorativos animados */
        .brand-panel::before,
        .brand-panel::after {
            content: '';
            position: absolute;
            border-radius: 50%;
            background: color-mix(in srgb, var(--brand) 7%, transparent);
            animation: float 8s ease-in-out infinite;
        }
        .brand-panel::before {
            width: 420px; height: 420px;
            top: -120px; right: -100px;
            animation-delay: 0s;
        }
        .brand-panel::after {
            width: 280px; height: 280px;
            bottom: -80px; left: -60px;
            animation-delay: 3.5s;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0) scale(1); }
            50%       { transform: translateY(-20px) scale(1.04); }
        }

        .brand-logo {
            max-height: 90px;
            max-width: 200px;
            object-fit: contain;
            margin-bottom: 1.6rem;
            animation: logoIn 0.7s ease both;
        }
        @keyframes logoIn {
            from { opacity: 0; transform: translateY(-20px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        .brand-icon-fallback {
            width: 90px; height: 90px;
            border-radius: 22px;
            background: color-mix(in srgb, var(--brand) 12%, transparent);
            display: flex; align-items: center; justify-content: center;
            margin-bottom: 1.6rem;
            font-size: 2.6rem;
            color: var(--brand);
            animation: logoIn 0.7s ease both;
        }

        .brand-name {
            font-size: 1.7rem;
            font-weight: 800;
            color: var(--brand);
            text-align: center;
            line-height: 1.2;
            letter-spacing: -0.01em;
            animation: slideUp 0.6s 0.1s ease both;
        }
        .brand-sub {
            font-size: 1rem;
            color: var(--brand-dark);
            text-align: center;
            margin-top: 0.5rem;
            animation: slideUp 0.6s 0.2s ease both;
        }
        .brand-badges {
            display: flex;
            gap: 0.6rem;
            flex-wrap: wrap;
            justify-content: center;
            margin-top: 2.5rem;
            animation: slideUp 0.6s 0.35s ease both;
        }
        .brand-badge {
            background: color-mix(in srgb, var(--brand) 10%, transparent);
            color: var(--brand-dark);
            border: 1px solid color-mix(in srgb, var(--brand) 30%, transparent);
            padding: 5px 14px;
            border-radius: 100px;
            font-size: 0.78rem;
            font-weight: 600;
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(16px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        /* ── Panel derecho — formulario ─────────────────────── */
        .form-panel {
            width: 420px;
            min-width: 340px;
            background: linear-gradient(145deg, var(--brand-dark) 0%, var(--brand) 60%, color-mix(in srgb, var(--brand) 70%, #fff) 100%);
            display: flex;
            flex-direction: column;
            justify-content: center;
            padding: 3rem 2.6rem;
            box-shadow: 6px 0 40px rgba(0,0,0,0.18);
            position: relative;
            overflow: hidden;
            animation: slideIn 0.5s ease both;
        }
        .form-panel::before,
        .form-panel::after {
            content: '';
            position: absolute;
            border-radius: 50%;
            background: rgba(255,255,255,0.07);
            animation: float 8s ease-in-out infinite;
            pointer-events: none;
            z-index: 0;
        }
        .form-panel::before {
            width: 320px; height: 320px;
            bottom: -110px; right: -90px;
            animation-delay: 1.5s;
        }
        .form-panel::after {
            width: 200px; height: 200px;
            top: -70px; left: -50px;
            animation-delay: 4.5s;
        }

        @keyframes slideIn {
            from { opacity: 0; transform: translateX(30px); }
            to   { opacity: 1; transform: translateX(0); }
        }

        .form-label {
            font-size: 0.87rem;
            font-weight: 600;
            color: rgba(255,255,255,0.9);
            position: relative; z-index: 1;
        }
        .form-control {
            padding: 0.72rem 1rem;
            border-radius: 10px;
            border: 1.5px solid rgba(255,255,255,0.35);
            background: rgba(255,255,255,0.18);
            color: #fff;
            font-size: 0.95rem;
            transition: border-color .2s, box-shadow .2s, background .2s;
        }
        .form-control::placeholder { color: rgba(255,255,255,0.5); }
        .form-control:focus {
            border-color: rgba(255,255,255,0.85);
            box-shadow: 0 0 0 3px rgba(255,255,255,0.15);
            outline: none;
            background: rgba(255,255,255,0.25);
            color: #fff;
        }
        .input-group .form-control { border-right: none; border-radius: 10px 0 0 10px; }
        .input-group .btn-eye {
            border: 1.5px solid rgba(255,255,255,0.35);
            border-left: none;
            background: rgba(255,255,255,0.18);
            border-radius: 0 10px 10px 0;
            color: rgba(255,255,255,0.7);
            padding: 0 14px;
            transition: color .2s;
        }
        .input-group .btn-eye:hover { color: #fff; }

        .btn-login {
            background: rgba(255,255,255,0.95);
            border: none;
            color: var(--brand-dark);
            width: 100%;
            padding: 0.82rem;
            border-radius: 12px;
            font-weight: 700;
            font-size: 1rem;
            letter-spacing: 0.02em;
            transition: transform .18s, box-shadow .18s, background .18s;
            position: relative; z-index: 1;
            overflow: hidden;
        }
        .btn-login:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 8px 28px rgba(0,0,0,0.3);
            background: #fff;
        }
        .btn-login:disabled { opacity: 0.65; cursor: not-allowed; }

        .form-title {
            font-size: 1.5rem;
            font-weight: 800;
            color: #fff;
            margin-bottom: 0.2rem;
            position: relative; z-index: 1;
        }
        .form-subtitle {
            font-size: 0.88rem;
            color: rgba(255,255,255,0.78);
            margin-bottom: 2rem;
            position: relative; z-index: 1;
        }

        .form-panel .alert {
            background: rgba(255,255,255,0.18);
            border-color: rgba(255,255,255,0.3);
            color: #fff;
            position: relative; z-index: 1;
        }
        .form-panel .form-group,
        .form-panel .mb-3,
        .form-panel .mb-4 { position: relative; z-index: 1; }

        .dev-footer {
            position: absolute;
            bottom: 1rem;
            left: 0; right: 0;
            text-align: center;
            font-size: 0.75rem;
            color: rgba(255,255,255,0.4);
            z-index: 1;
        }
        .dev-footer a { color: rgba(255,255,255,0.6); text-decoration: none; }
        .dev-footer a:hover { color: #fff; }

        /* Mobile */
        @media (max-width: 700px) {
            body { flex-direction: column; overflow: auto; }
            .brand-panel { flex: none; padding: 2.5rem 1.5rem 2rem; min-height: 220px; }
            .brand-panel::before { width: 200px; height: 200px; }
            .brand-panel::after  { width: 150px; height: 150px; }
            .brand-name  { font-size: 1.3rem; }
            .form-panel  { width: 100%; min-width: 0; box-shadow: none; padding: 2rem 1.5rem 3.5rem; }
        }
    </style>
</head>
<body>

<!-- ══ Panel izquierdo — branding ═══════════════════════════════════════ -->
<div class="brand-panel">
    <?php if ($logo): ?>
    <img src="<?= htmlspecialchars($logo, ENT_QUOTES, 'UTF-8') ?>" alt="Logo" class="brand-logo">
    <?php else: ?>
    <div class="brand-icon-fallback">
        <i class="fas fa-flask"></i>
    </div>
    <?php endif; ?>

    <div class="brand-name"><?= $empresa ?></div>
    <div class="brand-sub"><?= $subtitulo ?></div>

    <div class="brand-badges">
        <span class="brand-badge"><i class="fas fa-vials me-1"></i>Análisis Clínicos</span>
        <span class="brand-badge"><i class="fas fa-house-medical me-1"></i>Domicilios</span>
        <span class="brand-badge"><i class="fas fa-file-invoice me-1"></i>Documentos PDF</span>
        <span class="brand-badge"><i class="fas fa-chart-bar me-1"></i>Reportes</span>
    </div>
</div>

<!-- ══ Panel derecho — formulario ═══════════════════════════════════════ -->
<div class="form-panel">
    <p class="form-title">Bienvenido</p>
    <p class="form-subtitle">Inicia sesión en el sistema ERP</p>

    <?php if ($loginBlocked): ?>
    <div class="alert alert-danger d-flex align-items-center gap-2 mb-4" role="alert">
        <i class="fas fa-ban fa-lg"></i>
        <div><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
    </div>
    <?php endif; ?>

    <?php if ($success): ?>
    <div class="alert alert-success d-flex align-items-center gap-2 mb-4">
        <i class="fas fa-check-circle"></i>
        <div><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></div>
    </div>
    <?php endif; ?>

    <?php if ($error && !$loginBlocked): ?>
    <div class="alert alert-danger d-flex align-items-center gap-2 mb-4">
        <i class="fas fa-exclamation-triangle"></i>
        <div><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
    </div>
    <?php endif; ?>

    <form method="POST" id="loginForm" autocomplete="on">
        <div class="mb-3">
            <label for="username" class="form-label">
                <i class="fas fa-user me-1" style="color:var(--brand)"></i> Usuario
            </label>
            <input type="text" class="form-control" id="username" name="username"
                   required <?= $loginBlocked ? 'disabled' : '' ?>
                   placeholder="Tu usuario"
                   value="<?= htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
                   autofocus>
        </div>

        <div class="mb-4">
            <label for="password" class="form-label">
                <i class="fas fa-lock me-1" style="color:var(--brand)"></i> Contraseña
            </label>
            <div class="input-group">
                <input type="password" class="form-control" id="password" name="password"
                       required <?= $loginBlocked ? 'disabled' : '' ?>
                       placeholder="Tu contraseña">
                <button class="btn-eye" type="button" id="togglePwd" <?= $loginBlocked ? 'disabled' : '' ?>>
                    <i class="fas fa-eye"></i>
                </button>
            </div>
        </div>

        <button type="submit" class="btn-login" <?= $loginBlocked ? 'disabled' : '' ?>>
            <?php if ($loginBlocked): ?>
                <i class="fas fa-ban me-2"></i>Acceso bloqueado
            <?php else: ?>
                <i class="fas fa-arrow-right-to-bracket me-2"></i>Iniciar sesión
            <?php endif; ?>
        </button>
    </form>

    <div class="dev-footer">
        Desarrollado por <a href="https://u-site.app" target="_blank" rel="noopener">usite.app</a>
    </div>
</div>

<script>
    document.getElementById('togglePwd').addEventListener('click', function () {
        const pwd  = document.getElementById('password');
        const icon = this.querySelector('i');
        if (pwd.type === 'password') {
            pwd.type = 'text';
            icon.classList.replace('fa-eye', 'fa-eye-slash');
        } else {
            pwd.type = 'password';
            icon.classList.replace('fa-eye-slash', 'fa-eye');
        }
    });
    <?php if ($loginBlocked): ?>
    document.getElementById('loginForm').addEventListener('submit', e => e.preventDefault());
    <?php endif; ?>
</script>
</body>
</html>
