<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/conexao.php';
require_once __DIR__ . '/telecom_helpers.php';

date_default_timezone_set('America/Sao_Paulo');

telecomExigirAcesso();

if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('Conexão com o banco indisponível.');
}

$mysqli->set_charset('utf8mb4');

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

/*
|--------------------------------------------------------------------------
| Pop-up institucional Android e iOS
|--------------------------------------------------------------------------
| Exibido uma vez por sessão autenticada. Para testar novamente, use:
| ?novidade_mobile=1
*/
$popupMobileVersao = 'android-ios-2026-07-v1';
$popupMobileForcado = (
    isset($_GET['novidade_mobile']) &&
    (string) $_GET['novidade_mobile'] === '1'
);
$popupMobileChave = 'popup_mobile_' . $popupMobileVersao;
$mostrarPopupMobile = $popupMobileForcado ||
    empty($_SESSION[$popupMobileChave]);

if ($mostrarPopupMobile) {
    $_SESSION[$popupMobileChave] = true;
}

try {
    telecomGarantirEstrutura($mysqli);
} catch (Throwable $excecao) {
    http_response_code(500);
    exit(telecomE($excecao->getMessage()));
}

function dcE(mixed $valor): string
{
    return htmlspecialchars(
        (string) $valor,
        ENT_QUOTES,
        'UTF-8'
    );
}

function dcTabelaExiste(
    mysqli $mysqli,
    string $tabela
): bool {
    $nome = $mysqli->real_escape_string($tabela);

    $resultado = $mysqli->query(
        "SHOW TABLES LIKE '{$nome}'"
    );

    return $resultado instanceof mysqli_result &&
        $resultado->num_rows > 0;
}

function dcColunaExiste(
    mysqli $mysqli,
    string $tabela,
    string $coluna
): bool {
    $stmt = $mysqli->prepare("
        SELECT COUNT(*) AS total
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");

    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('ss', $tabela, $coluna);
    $stmt->execute();

    $linha = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return (int) ($linha['total'] ?? 0) > 0;
}

function dcData(?string $data): string
{
    if (!$data) {
        return 'Agora';
    }

    $timestamp = strtotime($data);

    if ($timestamp === false) {
        return $data;
    }

    if (date('Y-m-d', $timestamp) === date('Y-m-d')) {
        return 'Hoje, ' . date('H:i', $timestamp);
    }

    return date('d/m/Y H:i', $timestamp);
}

$usuarioLogado = telecomUsuarioAtual() ?: 'Cynthia';

$horaAtual = (int) date('H');

$saudacao = match (true) {
    $horaAtual >= 5 && $horaAtual < 12 => 'Bom dia',
    $horaAtual >= 12 && $horaAtual < 18 => 'Boa tarde',
    default => 'Boa noite'
};

/*
|--------------------------------------------------------------------------
| Indicadores de chips
|--------------------------------------------------------------------------
*/

$chips = [
    'total' => 0,
    'em_uso' => 0,
    'disponiveis' => 0,
    'sem_identificacao' => 0,
    'problemas' => 0,
    'sem_responsavel' => 0
];

$resultado = $mysqli->query("
    SELECT
        COUNT(*) AS total,
        COALESCE(SUM(status = 'EM_USO'), 0) AS em_uso,
        COALESCE(SUM(status = 'DISPONIVEL'), 0) AS disponiveis,
        COALESCE(
            SUM(
                status = 'SEM_IDENTIFICACAO'
                OR numero_linha IS NULL
                OR TRIM(numero_linha) = ''
            ),
            0
        ) AS sem_identificacao,
        COALESCE(
            SUM(status IN ('BLOQUEADO', 'EXTRAVIADO')),
            0
        ) AS problemas,
        COALESCE(
            SUM(
                status = 'EM_USO'
                AND (
                    responsavel_nome IS NULL
                    OR TRIM(responsavel_nome) = ''
                    OR setor IS NULL
                    OR TRIM(setor) = ''
                )
            ),
            0
        ) AS sem_responsavel
    FROM telecom_chips
");

if ($resultado) {
    $linha = $resultado->fetch_assoc() ?: [];

    foreach ($chips as $chave => $valor) {
        $chips[$chave] = (int) ($linha[$chave] ?? 0);
    }

    $resultado->free();
}

/*
|--------------------------------------------------------------------------
| Indicadores de smartphones
|--------------------------------------------------------------------------
*/

$smartphones = [
    'total' => 0,
    'em_uso' => 0,
    'disponiveis' => 0,
    'manutencao' => 0,
    'sem_identificacao' => 0,
    'problemas' => 0,
    'sem_responsavel' => 0
];

$resultado = $mysqli->query("
    SELECT
        COUNT(*) AS total,
        COALESCE(SUM(status = 'EM_USO'), 0) AS em_uso,
        COALESCE(SUM(status = 'DISPONIVEL'), 0) AS disponiveis,
        COALESCE(SUM(status = 'MANUTENCAO'), 0) AS manutencao,
        COALESCE(
            SUM(status = 'SEM_IDENTIFICACAO'),
            0
        ) AS sem_identificacao,
        COALESCE(
            SUM(status IN ('EXTRAVIADO', 'BAIXADO')),
            0
        ) AS problemas,
        COALESCE(
            SUM(
                status = 'EM_USO'
                AND (
                    responsavel_nome IS NULL
                    OR TRIM(responsavel_nome) = ''
                    OR setor IS NULL
                    OR TRIM(setor) = ''
                )
            ),
            0
        ) AS sem_responsavel
    FROM telecom_smartphones
");

if ($resultado) {
    $linha = $resultado->fetch_assoc() ?: [];

    foreach ($smartphones as $chave => $valor) {
        $smartphones[$chave] =
            (int) ($linha[$chave] ?? 0);
    }

    $resultado->free();
}

/*
|--------------------------------------------------------------------------
| Indicadores de toner
|--------------------------------------------------------------------------
*/

$toner = [
    'modelos' => 0,
    'unidades' => 0,
    'criticos' => 0,
    'zerados' => 0,
    'saidas_mes' => 0
];

if (dcTabelaExiste($mysqli, 'tonner_estoque')) {
    $campoMinimo = dcColunaExiste(
        $mysqli,
        'tonner_estoque',
        'estoque_minimo'
    )
        ? 'estoque_minimo'
        : '2';

    $resultado = $mysqli->query("
        SELECT
            COUNT(*) AS modelos,
            COALESCE(SUM(quantidade), 0) AS unidades,
            COALESCE(
                SUM(
                    quantidade > 0
                    AND quantidade <= {$campoMinimo}
                ),
                0
            ) AS criticos,
            COALESCE(SUM(quantidade <= 0), 0) AS zerados
        FROM tonner_estoque
    ");

    if ($resultado) {
        $linha = $resultado->fetch_assoc() ?: [];

        $toner['modelos'] =
            (int) ($linha['modelos'] ?? 0);

        $toner['unidades'] =
            (int) ($linha['unidades'] ?? 0);

        $toner['criticos'] =
            (int) ($linha['criticos'] ?? 0);

        $toner['zerados'] =
            (int) ($linha['zerados'] ?? 0);

        $resultado->free();
    }
}

if (dcTabelaExiste($mysqli, 'tonner_movimentacoes')) {
    $resultado = $mysqli->query("
        SELECT
            COALESCE(SUM(quantidade), 0) AS total
        FROM tonner_movimentacoes
        WHERE tipo = 'SAIDA'
          AND YEAR(criado_em) = YEAR(CURRENT_DATE())
          AND MONTH(criado_em) = MONTH(CURRENT_DATE())
    ");

    if ($resultado) {
        $linha = $resultado->fetch_assoc() ?: [];

        $toner['saidas_mes'] =
            (int) ($linha['total'] ?? 0);

        $resultado->free();
    }
}

/*
|--------------------------------------------------------------------------
| Pendências
|--------------------------------------------------------------------------
*/

$pendencias = [];

if ($chips['sem_identificacao'] > 0) {
    $pendencias[] = [
        'tipo' => 'warning',
        'icone' => 'bi-question-circle-fill',
        'titulo' => (
            $chips['sem_identificacao'] .
            ' chip(s) sem número ou identificação completa'
        ),
        'texto' => (
            'Revise o número da linha, ICCID e a situação cadastral.'
        ),
        'url' => 'chips.php'
    ];
}

if ($chips['sem_responsavel'] > 0) {
    $pendencias[] = [
        'tipo' => 'danger',
        'icone' => 'bi-person-exclamation',
        'titulo' => (
            $chips['sem_responsavel'] .
            ' chip(s) em uso sem responsável ou setor'
        ),
        'texto' => (
            'Vincule a pessoa e o setor para manter a rastreabilidade.'
        ),
        'url' => 'chips.php'
    ];
}

if ($smartphones['sem_identificacao'] > 0) {
    $pendencias[] = [
        'tipo' => 'warning',
        'icone' => 'bi-phone-fill',
        'titulo' => (
            $smartphones['sem_identificacao'] .
            ' smartphone(s) sem identificação completa'
        ),
        'texto' => (
            'Informe patrimônio, IMEI, número de série ou situação.'
        ),
        'url' => 'smartphones.php'
    ];
}

if ($smartphones['sem_responsavel'] > 0) {
    $pendencias[] = [
        'tipo' => 'danger',
        'icone' => 'bi-person-exclamation',
        'titulo' => (
            $smartphones['sem_responsavel'] .
            ' smartphone(s) em uso sem responsável ou setor'
        ),
        'texto' => (
            'Atualize quem está utilizando cada aparelho.'
        ),
        'url' => 'smartphones.php'
    ];
}

$tonerAtencao = $toner['criticos'] + $toner['zerados'];

if ($tonerAtencao > 0) {
    $pendencias[] = [
        'tipo' => 'danger',
        'icone' => 'bi-printer-fill',
        'titulo' => (
            $tonerAtencao .
            ' modelo(s) de toner em situação crítica'
        ),
        'texto' => (
            $toner['zerados'] .
            ' zerado(s) e ' .
            $toner['criticos'] .
            ' abaixo ou no estoque mínimo.'
        ),
        'url' => 'tonner.php'
    ];
}

/*
|--------------------------------------------------------------------------
| Últimas movimentações
|--------------------------------------------------------------------------
*/

$movimentacoes = [];

$resultado = $mysqli->query("
    SELECT
        m.tipo_item,
        m.acao,
        m.responsavel_anterior,
        m.responsavel_novo,
        m.setor_anterior,
        m.setor_novo,
        m.usuario,
        m.criado_em,
        CASE
            WHEN m.tipo_item = 'CHIP' THEN
                COALESCE(
                    NULLIF(c.numero_linha, ''),
                    c.codigo_interno,
                    'Chip'
                )
            ELSE
                COALESCE(
                    NULLIF(
                        TRIM(CONCAT(s.marca, ' ', s.modelo)),
                        ''
                    ),
                    s.codigo_interno,
                    'Smartphone'
                )
        END AS item_nome
    FROM telecom_movimentacoes AS m
    LEFT JOIN telecom_chips AS c
        ON m.tipo_item = 'CHIP'
       AND c.id = m.item_id
    LEFT JOIN telecom_smartphones AS s
        ON m.tipo_item = 'SMARTPHONE'
       AND s.id = m.item_id
    ORDER BY m.criado_em DESC, m.id DESC
    LIMIT 8
");

if ($resultado) {
    while ($linha = $resultado->fetch_assoc()) {
        $movimentacoes[] = [
            'origem' => (string) $linha['tipo_item'],
            'titulo' => (string) (
                $linha['item_nome'] ??
                $linha['tipo_item']
            ),
            'acao' => str_replace(
                '_',
                ' ',
                (string) $linha['acao']
            ),
            'detalhe' => trim(
                implode(
                    ' → ',
                    array_filter([
                        $linha['responsavel_anterior'] ?? '',
                        $linha['responsavel_novo'] ?? ''
                    ])
                )
            ),
            'usuario' => (string) (
                $linha['usuario'] ?? ''
            ),
            'data' => (string) (
                $linha['criado_em'] ?? ''
            ),
            'url' => $linha['tipo_item'] === 'CHIP'
                ? 'chips.php'
                : 'smartphones.php'
        ];
    }

    $resultado->free();
}

if (dcTabelaExiste($mysqli, 'tonner_movimentacoes')) {
    $resultado = $mysqli->query("
        SELECT
            modelo,
            tipo,
            quantidade,
            responsavel,
            destino,
            usuario_sistema,
            criado_em
        FROM tonner_movimentacoes
        ORDER BY criado_em DESC, id DESC
        LIMIT 6
    ");

    if ($resultado) {
        while ($linha = $resultado->fetch_assoc()) {
            $movimentacoes[] = [
                'origem' => 'TONER',
                'titulo' => (string) (
                    $linha['modelo'] ?? 'Toner'
                ),
                'acao' => (string) (
                    $linha['tipo'] ?? 'MOVIMENTAÇÃO'
                ),
                'detalhe' => trim(
                    implode(
                        ' • ',
                        array_filter([
                            (
                                (int) ($linha['quantidade'] ?? 0)
                            ) . ' unidade(s)',
                            $linha['destino'] ?? ''
                        ])
                    )
                ),
                'usuario' => (string) (
                    $linha['usuario_sistema'] ??
                    $linha['responsavel'] ??
                    ''
                ),
                'data' => (string) (
                    $linha['criado_em'] ?? ''
                ),
                'url' => 'tonner.php'
            ];
        }

        $resultado->free();
    }
}

usort(
    $movimentacoes,
    static function (array $a, array $b): int {
        return strtotime($b['data'] ?? '') <=>
            strtotime($a['data'] ?? '');
    }
);

$movimentacoes = array_slice($movimentacoes, 0, 10);

$totalItensControlados =
    $chips['total'] +
    $smartphones['total'] +
    $toner['unidades'];

$totalPendencias = count($pendencias);
?>
<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">

    <meta
        name="viewport"
        content="width=device-width,initial-scale=1,viewport-fit=cover"
    >

    <meta name="theme-color" content="#08396f">

    <meta
        name="description"
        content="Painel exclusivo da Cynthia para controle de chips, smartphones e toner."
    >

    <title>Painel da Cynthia | Manutenção TI</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
        rel="stylesheet"
    >

    <link
        href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"
        rel="stylesheet"
    >

    <style>
        :root{
            --blue:#08396f;
            --blue-dark:#05294f;
            --blue-light:#1764ad;
            --green:#087f5b;
            --green-dark:#00664b;
            --gold:#e8ad16;
            --red:#bf263d;
            --orange:#d17a00;
            --purple:#5d46b5;
            --cyan:#087f9c;
            --bg:#edf3f8;
            --surface:#fff;
            --soft:#f5f9fc;
            --text:#172438;
            --muted:#62738a;
            --light:#8795a8;
            --border:#dce6ee;
            --shadow:0 20px 58px rgba(8,57,111,.1);
            --shadow-lg:0 34px 90px rgba(5,41,79,.18);
        }

        *{box-sizing:border-box}

        html{
            min-height:100%;
            scroll-behavior:smooth;
        }

        body{
            margin:0;
            min-height:100vh;
            overflow-x:hidden;
            font-family:"Inter",system-ui,-apple-system,"Segoe UI",sans-serif;
            color:var(--text);
            background:
                radial-gradient(circle at 3% 4%,rgba(23,100,173,.16),transparent 31rem),
                radial-gradient(circle at 96% 88%,rgba(8,127,91,.11),transparent 31rem),
                linear-gradient(145deg,#f9fbfd 0%,var(--bg) 52%,#e7eff6 100%);
        }

        a{text-decoration:none;color:inherit}
        button{font:inherit}

        .top-line{
            position:fixed;
            z-index:1000;
            top:0;
            right:0;
            left:0;
            height:6px;
            background:linear-gradient(
                90deg,
                var(--blue) 0 58%,
                #008b66 58% 88%,
                var(--gold) 88%
            );
        }

        .grid-bg{
            position:fixed;
            inset:0;
            pointer-events:none;
            background-image:
                linear-gradient(rgba(8,57,111,.028) 1px,transparent 1px),
                linear-gradient(90deg,rgba(8,57,111,.028) 1px,transparent 1px);
            background-size:54px 54px;
            mask-image:linear-gradient(to bottom,#000,transparent 93%);
        }

        .app{
            position:relative;
            z-index:2;
            min-height:100vh;
            padding:6px 20px 30px;
        }

        .header{
            position:relative;
            overflow:hidden;
            max-width:1720px;
            margin:20px auto 0;
            padding:23px;
            border:1px solid rgba(255,255,255,.18);
            border-radius:30px;
            color:#fff;
            background:
                radial-gradient(circle at 84% 0,rgba(255,255,255,.14),transparent 24rem),
                radial-gradient(circle at 0 100%,rgba(0,139,102,.24),transparent 27rem),
                linear-gradient(145deg,var(--blue-dark),var(--blue) 58%,#07537c);
            box-shadow:var(--shadow-lg);
        }

        .header::after{
            content:"";
            position:absolute;
            right:-150px;
            bottom:-260px;
            width:480px;
            height:480px;
            border:52px solid rgba(255,255,255,.04);
            border-radius:50%;
        }

        .header-inner{
            position:relative;
            z-index:2;
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:22px;
        }

        .brand{
            min-width:0;
            display:flex;
            align-items:center;
            gap:16px;
        }

        .logo{
            width:72px;
            height:72px;
            flex:0 0 72px;
            display:grid;
            place-items:center;
            overflow:hidden;
            padding:5px;
            border-radius:22px;
            background:#fff;
            box-shadow:0 18px 38px rgba(0,0,0,.18);
        }

        .logo img{
            width:100%;
            height:100%;
            object-fit:contain;
            border-radius:17px;
        }

        .eyebrow{
            display:inline-flex;
            align-items:center;
            gap:7px;
            margin-bottom:8px;
            padding:6px 10px;
            border:1px solid rgba(255,255,255,.15);
            border-radius:999px;
            color:rgba(255,255,255,.84);
            background:rgba(255,255,255,.08);
            font-size:9px;
            font-weight:850;
            letter-spacing:.65px;
            text-transform:uppercase;
        }

        .header h1{
            margin:0;
            font-size:clamp(26px,3.2vw,43px);
            line-height:1;
            letter-spacing:-1.4px;
            font-weight:950;
        }

        .header p{
            max-width:770px;
            margin:9px 0 0;
            color:rgba(255,255,255,.7);
            font-size:10px;
            line-height:1.55;
        }

        .user-area{
            flex:0 0 auto;
            display:flex;
            align-items:center;
            gap:10px;
        }

        .user-copy{
            text-align:right;
        }

        .user-copy strong{
            display:block;
            font-size:11px;
            font-weight:900;
        }

        .user-copy span{
            display:block;
            margin-top:4px;
            color:rgba(255,255,255,.66);
            font-size:8px;
        }

        .avatar{
            width:45px;
            height:45px;
            display:grid;
            place-items:center;
            border-radius:15px;
            color:var(--blue-dark);
            background:#fff;
            box-shadow:0 13px 25px rgba(0,0,0,.17);
            font-size:18px;
        }

        .logout{
            min-height:42px;
            display:inline-flex;
            align-items:center;
            justify-content:center;
            gap:7px;
            padding:0 13px;
            border:1px solid rgba(255,255,255,.16);
            border-radius:13px;
            color:#fff;
            background:rgba(191,38,61,.24);
            font-size:8px;
            font-weight:900;
            text-transform:uppercase;
            transition:.2s ease;
        }

        .logout:hover{
            color:#fff;
            transform:translateY(-2px);
            background:rgba(191,38,61,.38);
        }

        .main{
            width:100%;
            max-width:1720px;
            margin:auto;
            padding-top:16px;
        }

        .access-alert{
            display:flex;
            align-items:center;
            gap:11px;
            margin-bottom:14px;
            padding:14px 15px;
            border:1px solid #efd09a;
            border-radius:17px;
            color:#805400;
            background:#fff7e6;
            box-shadow:0 12px 28px rgba(209,122,0,.08);
            font-size:9px;
            line-height:1.5;
            font-weight:750;
        }

        .welcome{
            display:grid;
            grid-template-columns:minmax(0,1.4fr) minmax(300px,.6fr);
            gap:15px;
        }

        .welcome-main,
        .scope-card{
            overflow:hidden;
            padding:24px;
            border:1px solid rgba(255,255,255,.94);
            border-radius:28px;
            background:rgba(255,255,255,.88);
            backdrop-filter:blur(20px);
            box-shadow:var(--shadow);
        }

        .welcome-main h2{
            margin:0;
            max-width:900px;
            font-size:clamp(29px,3.3vw,46px);
            line-height:1.02;
            letter-spacing:-1.7px;
            font-weight:950;
        }

        .welcome-main h2 span{color:var(--blue)}

        .welcome-main p{
            max-width:840px;
            margin:13px 0 0;
            color:var(--muted);
            font-size:11px;
            line-height:1.68;
        }

        .welcome-tags{
            display:flex;
            flex-wrap:wrap;
            gap:7px;
            margin-top:17px;
        }

        .tag{
            display:inline-flex;
            align-items:center;
            gap:6px;
            padding:7px 9px;
            border:1px solid var(--border);
            border-radius:999px;
            color:#536277;
            background:#fff;
            font-size:8px;
            font-weight:800;
        }

        .scope-card{
            color:#fff;
            background:
                radial-gradient(circle at 90% 0,rgba(255,255,255,.16),transparent 13rem),
                linear-gradient(145deg,var(--green-dark),var(--green));
        }

        .scope-card small{
            color:rgba(255,255,255,.7);
            font-size:8px;
            font-weight:900;
            letter-spacing:.6px;
            text-transform:uppercase;
        }

        .scope-card strong{
            display:block;
            margin-top:12px;
            font-size:45px;
            line-height:1;
            font-weight:950;
        }

        .scope-card p{
            margin:9px 0 0;
            color:rgba(255,255,255,.72);
            font-size:9px;
            line-height:1.55;
        }

        .modules{
            display:grid;
            grid-template-columns:repeat(3,minmax(0,1fr));
            gap:14px;
            margin-top:15px;
        }

        .module{
            position:relative;
            isolation:isolate;
            overflow:hidden;
            min-height:260px;
            display:flex;
            flex-direction:column;
            justify-content:space-between;
            padding:21px;
            border:1px solid rgba(255,255,255,.94);
            border-radius:27px;
            color:var(--text);
            background:rgba(255,255,255,.91);
            box-shadow:var(--shadow);
            transition:
                transform .22s ease,
                box-shadow .22s ease,
                border-color .22s ease;
        }

        .module::after{
            content:"";
            position:absolute;
            z-index:-1;
            right:-95px;
            bottom:-120px;
            width:250px;
            height:250px;
            border:34px solid rgba(8,57,111,.035);
            border-radius:50%;
        }

        .module:hover{
            color:var(--text);
            border-color:#bfd0df;
            transform:translateY(-6px);
            box-shadow:0 28px 70px rgba(8,57,111,.16);
        }

        .module-top{
            display:flex;
            align-items:flex-start;
            justify-content:space-between;
            gap:12px;
        }

        .module-icon{
            width:58px;
            height:58px;
            display:grid;
            place-items:center;
            border-radius:19px;
            color:#fff;
            background:linear-gradient(145deg,var(--blue-dark),var(--blue-light));
            box-shadow:0 15px 30px rgba(8,57,111,.2);
            font-size:25px;
        }

        .module.toner .module-icon{
            background:linear-gradient(145deg,#6d4900,var(--orange));
            box-shadow:0 15px 30px rgba(209,122,0,.2);
        }

        .module.smart .module-icon{
            background:linear-gradient(145deg,#3f2d82,var(--purple));
            box-shadow:0 15px 30px rgba(93,70,181,.2);
        }

        .module-arrow{
            width:38px;
            height:38px;
            display:grid;
            place-items:center;
            border:1px solid var(--border);
            border-radius:13px;
            color:var(--blue);
            background:#fff;
            font-size:15px;
        }

        .module h3{
            margin:20px 0 0;
            font-size:22px;
            line-height:1.1;
            letter-spacing:-.6px;
            font-weight:950;
        }

        .module p{
            margin:8px 0 0;
            color:var(--muted);
            font-size:9px;
            line-height:1.55;
        }

        .module-metrics{
            display:grid;
            grid-template-columns:repeat(3,1fr);
            gap:7px;
            margin-top:18px;
        }

        .module-metric{
            padding:10px;
            border:1px solid var(--border);
            border-radius:14px;
            background:var(--soft);
        }

        .module-metric strong{
            display:block;
            color:var(--blue);
            font-size:18px;
            line-height:1;
            font-weight:950;
        }

        .module.toner .module-metric strong{color:var(--orange)}
        .module.smart .module-metric strong{color:var(--purple)}

        .module-metric span{
            display:block;
            margin-top:5px;
            color:var(--light);
            font-size:6.5px;
            line-height:1.35;
            font-weight:850;
            text-transform:uppercase;
        }

        .content-grid{
            display:grid;
            grid-template-columns:minmax(0,1.05fr) minmax(0,.95fr);
            gap:14px;
            margin-top:15px;
        }

        .panel{
            overflow:hidden;
            border:1px solid rgba(255,255,255,.94);
            border-radius:27px;
            background:rgba(255,255,255,.91);
            box-shadow:var(--shadow);
        }

        .panel-head{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:12px;
            padding:17px 18px;
            border-bottom:1px solid var(--border);
            background:linear-gradient(180deg,#fff,#f8fbfd);
        }

        .panel-title{
            display:flex;
            align-items:center;
            gap:10px;
        }

        .panel-title i{
            width:39px;
            height:39px;
            display:grid;
            place-items:center;
            border-radius:13px;
            color:#fff;
            background:linear-gradient(145deg,var(--blue),var(--blue-light));
            font-size:16px;
        }

        .panel-title strong{
            display:block;
            font-size:12px;
            font-weight:900;
        }

        .panel-title span{
            display:block;
            margin-top:3px;
            color:var(--muted);
            font-size:7px;
        }

        .panel-count{
            padding:6px 9px;
            border-radius:999px;
            color:var(--blue);
            background:#eaf4fc;
            font-size:7px;
            font-weight:900;
        }

        .panel-body{padding:14px}

        .pending-list,
        .movement-list{
            display:flex;
            flex-direction:column;
            gap:8px;
        }

        .pending{
            display:grid;
            grid-template-columns:auto minmax(0,1fr) auto;
            align-items:center;
            gap:10px;
            padding:11px;
            border:1px solid var(--border);
            border-radius:15px;
            background:var(--soft);
            transition:.18s ease;
        }

        .pending:hover{
            color:var(--text);
            transform:translateY(-2px);
            background:#fff;
            box-shadow:0 12px 25px rgba(8,57,111,.08);
        }

        .pending-icon{
            width:39px;
            height:39px;
            display:grid;
            place-items:center;
            border-radius:13px;
            color:#805400;
            background:#fff1cb;
            font-size:16px;
        }

        .pending.danger .pending-icon{
            color:#fff;
            background:var(--red);
        }

        .pending strong{
            display:block;
            font-size:8px;
            line-height:1.45;
            font-weight:900;
        }

        .pending span{
            display:block;
            margin-top:3px;
            color:var(--muted);
            font-size:7px;
            line-height:1.45;
        }

        .pending-arrow{color:var(--blue)}

        .all-good{
            padding:30px 16px;
            text-align:center;
            color:var(--muted);
        }

        .all-good i{
            display:block;
            margin-bottom:10px;
            color:var(--green);
            font-size:35px;
        }

        .all-good strong{
            display:block;
            color:var(--text);
            font-size:11px;
            font-weight:900;
        }

        .all-good span{
            display:block;
            margin-top:5px;
            font-size:8px;
        }

        .movement{
            display:grid;
            grid-template-columns:auto minmax(0,1fr) auto;
            align-items:start;
            gap:10px;
            padding:10px 2px 11px;
            border-bottom:1px solid var(--border);
        }

        .movement:last-child{border-bottom:0}

        .movement-icon{
            width:36px;
            height:36px;
            display:grid;
            place-items:center;
            border-radius:12px;
            color:var(--blue);
            background:#eaf4fc;
            font-size:15px;
        }

        .movement-icon.toner{
            color:var(--orange);
            background:#fff4d6;
        }

        .movement-icon.smart{
            color:var(--purple);
            background:#f0edfb;
        }

        .movement strong{
            display:block;
            font-size:8px;
            line-height:1.4;
            font-weight:900;
        }

        .movement span{
            display:block;
            margin-top:3px;
            color:var(--muted);
            font-size:7px;
            line-height:1.42;
        }

        .movement time{
            color:var(--light);
            font-size:6.5px;
            white-space:nowrap;
        }

        .footer{
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:14px;
            margin-top:15px;
            padding:13px 16px;
            border:1px solid rgba(255,255,255,.94);
            border-radius:18px;
            color:var(--light);
            background:rgba(255,255,255,.78);
            font-size:7px;
            line-height:1.5;
            font-weight:650;
        }

        .footer strong{color:var(--blue)}

        @media(max-width:1100px){
            .header-inner{
                align-items:flex-start;
                flex-direction:column;
            }

            .user-area{width:100%}

            .welcome{grid-template-columns:1fr}
            .modules{grid-template-columns:1fr 1fr}
            .content-grid{grid-template-columns:1fr}
        }

        @media(max-width:720px){
            .app{padding-right:9px;padding-left:9px}

            .header{
                margin-top:12px;
                padding:17px;
                border-radius:23px;
            }

            .brand{align-items:flex-start}
            .logo{width:60px;height:60px;flex-basis:60px}
            .user-area{flex-wrap:wrap}
            .user-copy{text-align:left;margin-right:auto}

            .welcome-main,
            .scope-card{
                padding:18px;
                border-radius:23px;
            }

            .modules{grid-template-columns:1fr}
            .module{min-height:235px}
            .footer{align-items:flex-start;flex-direction:column}
        }

        @media(max-width:520px){
            .header h1{font-size:28px}
            .module-metrics{grid-template-columns:1fr 1fr}
            .pending{grid-template-columns:auto 1fr}
            .pending-arrow{display:none}
            .movement{grid-template-columns:auto 1fr}
            .movement time{grid-column:2}
        }

        @media(prefers-reduced-motion:reduce){
            *,
            *::before,
            *::after{
                animation-duration:.01ms!important;
                animation-iteration-count:1!important;
                transition-duration:.01ms!important;
            }
        }


        /* ================================================================
           POP-UP INSTITUCIONAL — ANDROID E IOS
           ================================================================ */
        html.mobile-app-popup-open,
        body.mobile-app-popup-open {
            overflow: hidden !important;
            overscroll-behavior: none;
        }

        .mobile-app-popup {
            --popup-blue: #063b78;
            --popup-cyan: #1bb7ff;
            --popup-green: #20d798;
            position: fixed;
            z-index: 999999;
            inset: 0;
            display: grid;
            place-items: center;
            padding: clamp(10px, 2.4vw, 28px);
            opacity: 0;
            visibility: hidden;
            transition:
                opacity .35s ease,
                visibility .35s ease;
            isolation: isolate;
        }

        .mobile-app-popup.is-visible {
            opacity: 1;
            visibility: visible;
        }

        .mobile-app-popup.is-closing {
            opacity: 0;
        }

        .mobile-app-popup__backdrop {
            position: absolute;
            z-index: 0;
            inset: 0;
            border: 0;
            cursor: pointer;
            background:
                radial-gradient(
                    circle at 16% 12%,
                    rgba(27, 183, 255, .20),
                    transparent 34rem
                ),
                radial-gradient(
                    circle at 86% 88%,
                    rgba(32, 215, 152, .16),
                    transparent 33rem
                ),
                rgba(1, 12, 32, .84);
            -webkit-backdrop-filter: blur(14px) saturate(120%);
            backdrop-filter: blur(14px) saturate(120%);
        }

        .mobile-app-popup__backdrop::before,
        .mobile-app-popup__backdrop::after {
            content: '';
            position: absolute;
            width: min(54vw, 680px);
            aspect-ratio: 1;
            border-radius: 50%;
            filter: blur(85px);
            opacity: .34;
            pointer-events: none;
            animation: mobilePopupAura 7s ease-in-out infinite alternate;
        }

        .mobile-app-popup__backdrop::before {
            top: -28%;
            left: -18%;
            background: #087cff;
        }

        .mobile-app-popup__backdrop::after {
            right: -18%;
            bottom: -30%;
            background: #00b78a;
            animation-delay: -2.7s;
        }

        .mobile-app-popup__card {
            position: relative;
            z-index: 1;
            width: min(94vw, 620px);
            max-height: 94vh;
            max-height: min(94dvh, 900px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            border: 1px solid rgba(150, 213, 255, .32);
            border-radius: clamp(20px, 3vw, 32px);
            color: #fff;
            background:
                linear-gradient(
                    145deg,
                    rgba(5, 32, 75, .98),
                    rgba(2, 17, 45, .99)
                );
            box-shadow:
                0 42px 120px rgba(0, 0, 0, .56),
                0 0 0 1px rgba(255, 255, 255, .05) inset,
                0 0 75px rgba(27, 183, 255, .16);
            transform: translateY(38px) scale(.91) rotateX(5deg);
            transform-origin: center bottom;
            opacity: 0;
            transition:
                transform .72s cubic-bezier(.16, 1, .3, 1),
                opacity .42s ease;
        }

        .mobile-app-popup.is-visible .mobile-app-popup__card {
            transform: translateY(0) scale(1) rotateX(0);
            opacity: 1;
        }

        .mobile-app-popup.is-closing .mobile-app-popup__card {
            transform: translateY(26px) scale(.96);
            opacity: 0;
            transition-duration: .28s;
        }

        .mobile-app-popup__card::before {
            content: '';
            position: absolute;
            z-index: 5;
            top: -70%;
            left: -40%;
            width: 34%;
            height: 240%;
            pointer-events: none;
            background: linear-gradient(
                90deg,
                transparent,
                rgba(255, 255, 255, .20),
                transparent
            );
            transform: rotate(22deg);
            animation: mobilePopupShine 4.8s 1.1s ease-in-out infinite;
        }

        .mobile-app-popup__topbar {
            position: relative;
            z-index: 8;
            min-height: 54px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 10px 11px 10px 16px;
            border-bottom: 1px solid rgba(255, 255, 255, .10);
            background: rgba(1, 18, 48, .90);
            -webkit-backdrop-filter: blur(14px);
            backdrop-filter: blur(14px);
        }

        .mobile-app-popup__badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            min-width: 0;
            color: rgba(255, 255, 255, .94);
            font-size: 10px;
            font-weight: 900;
            letter-spacing: .65px;
            text-transform: uppercase;
        }

        .mobile-app-popup__badge-dot {
            width: 10px;
            height: 10px;
            flex: 0 0 10px;
            border-radius: 50%;
            background: var(--popup-green);
            box-shadow: 0 0 0 5px rgba(32, 215, 152, .12),
                        0 0 18px rgba(32, 215, 152, .9);
            animation: mobilePopupPulse 1.8s ease-in-out infinite;
        }

        .mobile-app-popup__close {
            width: 38px;
            height: 38px;
            flex: 0 0 38px;
            display: grid;
            place-items: center;
            border: 1px solid rgba(255, 255, 255, .17);
            border-radius: 13px;
            color: #fff;
            background: rgba(255, 255, 255, .09);
            cursor: pointer;
            font-size: 21px;
            line-height: 1;
            transition:
                transform .2s ease,
                background .2s ease,
                border-color .2s ease;
        }

        .mobile-app-popup__close:hover,
        .mobile-app-popup__close:focus-visible {
            border-color: rgba(255, 255, 255, .45);
            background: rgba(255, 255, 255, .18);
            transform: rotate(8deg) scale(1.06);
            outline: none;
        }

        .mobile-app-popup__media {
            position: relative;
            min-height: 0;
            flex: 1 1 auto;
            display: grid;
            place-items: center;
            overflow: hidden;
            background: #031b45;
        }

        .mobile-app-popup__picture {
            width: 100%;
            min-height: 0;
            display: grid;
            place-items: center;
        }

        .mobile-app-popup__image {
            display: block;
            width: 100%;
            height: auto;
            max-height: calc(94vh - 126px);
            max-height: calc(94dvh - 126px);
            object-fit: contain;
            object-position: center;
            user-select: none;
            -webkit-user-drag: none;
            filter: saturate(1.03) contrast(1.015);
            animation: mobilePopupImageFloat 5.2s ease-in-out infinite;
        }

        .mobile-app-popup__footer {
            position: relative;
            z-index: 8;
            display: grid;
            grid-template-columns: minmax(0, 1fr) auto;
            align-items: center;
            gap: 13px;
            padding: 12px 14px;
            border-top: 1px solid rgba(255, 255, 255, .10);
            background:
                linear-gradient(
                    180deg,
                    rgba(2, 25, 62, .96),
                    rgba(1, 15, 39, .98)
                );
        }

        .mobile-app-popup__footer-copy {
            min-width: 0;
        }

        .mobile-app-popup__footer-copy strong,
        .mobile-app-popup__footer-copy span {
            display: block;
        }

        .mobile-app-popup__footer-copy strong {
            color: #fff;
            font-size: 10px;
            font-weight: 900;
        }

        .mobile-app-popup__footer-copy span {
            margin-top: 3px;
            color: rgba(255, 255, 255, .61);
            font-size: 8px;
            line-height: 1.4;
        }

        .mobile-app-popup__confirm {
            min-height: 42px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 7px;
            padding: 0 15px;
            border: 0;
            border-radius: 13px;
            color: #03234f;
            background: linear-gradient(135deg, #fff, #bfeaff);
            box-shadow: 0 12px 28px rgba(14, 165, 233, .24);
            cursor: pointer;
            font-size: 8px;
            font-weight: 950;
            letter-spacing: .35px;
            text-transform: uppercase;
            white-space: nowrap;
            transition:
                transform .2s ease,
                box-shadow .2s ease;
        }

        .mobile-app-popup__confirm:hover,
        .mobile-app-popup__confirm:focus-visible {
            transform: translateY(-2px);
            box-shadow: 0 16px 32px rgba(14, 165, 233, .34);
            outline: none;
        }

        @keyframes mobilePopupShine {
            0%, 58% { left: -45%; opacity: 0; }
            67% { opacity: .75; }
            85%, 100% { left: 125%; opacity: 0; }
        }

        @keyframes mobilePopupPulse {
            0%, 100% { transform: scale(.92); opacity: .75; }
            50% { transform: scale(1.1); opacity: 1; }
        }

        @keyframes mobilePopupAura {
            from { transform: translate3d(-2%, -2%, 0) scale(.92); }
            to { transform: translate3d(4%, 3%, 0) scale(1.08); }
        }

        @keyframes mobilePopupImageFloat {
            0%, 100% { transform: translateY(0) scale(1); }
            50% { transform: translateY(-3px) scale(1.003); }
        }

        @media (max-width: 640px) {
            .mobile-app-popup {
                padding: 8px;
                align-items: center;
            }

            .mobile-app-popup__card {
                width: min(96vw, 500px);
                max-height: 96vh;
                max-height: 96dvh;
                border-radius: 22px;
            }

            .mobile-app-popup__topbar {
                min-height: 48px;
                padding: 7px 8px 7px 13px;
            }

            .mobile-app-popup__badge {
                font-size: 8px;
                letter-spacing: .35px;
            }

            .mobile-app-popup__close {
                width: 35px;
                height: 35px;
                flex-basis: 35px;
                border-radius: 12px;
            }

            .mobile-app-popup__image {
                max-height: calc(96vh - 118px);
                max-height: calc(96dvh - 118px);
            }

            .mobile-app-popup__footer {
                grid-template-columns: 1fr;
                gap: 8px;
                padding: 10px;
                text-align: center;
            }

            .mobile-app-popup__footer-copy span {
                display: none;
            }

            .mobile-app-popup__confirm {
                width: 100%;
            }
        }

        @media (max-height: 620px) and (orientation: landscape) {
            .mobile-app-popup__card {
                width: min(94vw, 470px);
                max-height: 94vh;
                max-height: 94dvh;
            }

            .mobile-app-popup__topbar {
                min-height: 42px;
                padding: 5px 7px 5px 12px;
            }

            .mobile-app-popup__close {
                width: 32px;
                height: 32px;
                flex-basis: 32px;
            }

            .mobile-app-popup__footer {
                display: none;
            }

            .mobile-app-popup__image {
                max-height: calc(94vh - 42px);
                max-height: calc(94dvh - 42px);
            }
        }

        @media (prefers-reduced-motion: reduce) {
            .mobile-app-popup,
            .mobile-app-popup__card,
            .mobile-app-popup__image,
            .mobile-app-popup__badge-dot,
            .mobile-app-popup__backdrop::before,
            .mobile-app-popup__backdrop::after,
            .mobile-app-popup__card::before {
                animation: none !important;
                transition-duration: .01ms !important;
            }
        }

    </style>
</head>
<body>

<?php if ($mostrarPopupMobile): ?>
<div
    class="mobile-app-popup"
    id="mobileAppPopup"
    role="dialog"
    aria-modal="true"
    aria-labelledby="mobileAppPopupTitle"
    aria-describedby="mobileAppPopupDescription"
>
    <button
        type="button"
        class="mobile-app-popup__backdrop"
        data-mobile-popup-close
        aria-label="Fechar novidade"
    ></button>

    <section class="mobile-app-popup__card" role="document">
        <header class="mobile-app-popup__topbar">
            <div class="mobile-app-popup__badge">
                <span class="mobile-app-popup__badge-dot"></span>
                <span id="mobileAppPopupTitle">
                    Novidade no sistema
                </span>
            </div>

            <button
                type="button"
                class="mobile-app-popup__close"
                data-mobile-popup-close
                aria-label="Fechar pop-up"
                title="Fechar"
            >
                <i class="bi bi-x-lg" aria-hidden="true"></i>
            </button>
        </header>

        <div class="mobile-app-popup__media">
            <picture class="mobile-app-popup__picture">
                <source
                    srcset="assets/novidade_android_ios.webp"
                    type="image/webp"
                >
                <img
                    class="mobile-app-popup__image"
                    src="assets/novidade_android_ios.jpg"
                    width="1080"
                    height="1350"
                    alt="O sistema de Manutenção de TI agora possui versão para Android e iOS."
                    decoding="async"
                    fetchpriority="high"
                >
            </picture>
        </div>

        <footer class="mobile-app-popup__footer">
            <div class="mobile-app-popup__footer-copy">
                <strong id="mobileAppPopupDescription">
                    Acesse também pelo smartphone
                </strong>
                <span>
                    Use na Prefeitura ou durante atendimentos externos.
                </span>
            </div>

            <button
                type="button"
                class="mobile-app-popup__confirm"
                data-mobile-popup-close
            >
                <i class="bi bi-check-circle-fill" aria-hidden="true"></i>
                Entendi, continuar
            </button>
        </footer>
    </section>
</div>
<?php endif; ?>


<div class="top-line"></div>
<div class="grid-bg"></div>

<div class="app">

    <header class="header">

        <div class="header-inner">

            <div class="brand">

                <div class="logo">
                    <img
                        src="assets/logo_pref.jpg"
                        alt="Prefeitura de Extrema"
                    >
                </div>

                <div>
                    <span class="eyebrow">
                        <i class="bi bi-shield-lock-fill"></i>
                        Área exclusiva da Cynthia
                    </span>

                    <h1>Painel de Gestão Operacional</h1>

                    <p>
                        Controle centralizado de chips móveis,
                        smartphones corporativos e estoque de toner.
                    </p>
                </div>

            </div>

            <div class="user-area">

                <div class="user-copy">
                    <strong>
                        <?= dcE($saudacao) ?>,
                        <?= dcE($usuarioLogado) ?>
                    </strong>

                    <span id="currentDateTime">
                        Carregando data e horário...
                    </span>
                </div>

                <span class="avatar">
                    <i class="bi bi-person-fill"></i>
                </span>

                <a href="logout.php" class="logout">
                    <i class="bi bi-box-arrow-right"></i>
                    Sair
                </a>

            </div>

        </div>

    </header>

    <main class="main">

        <?php if (isset($_GET['acesso_restrito'])): ?>
            <div class="access-alert">
                <i class="bi bi-shield-lock-fill"></i>

                <span>
                    A tela solicitada não faz parte das suas permissões.
                    Você pode utilizar somente
                    <strong>Chips, Toner e Smartphones</strong>.
                </span>
            </div>
        <?php endif; ?>

        <section class="welcome">

            <article class="welcome-main">

                <h2>
                    Controle total
                    <span>em um só lugar.</span>
                </h2>

                <p>
                    Este painel apresenta somente os três módulos
                    autorizados para o seu perfil. Os indicadores abaixo
                    ajudam a localizar linhas sem responsável, aparelhos
                    não identificados e modelos de toner em estoque crítico.
                </p>

                <div class="welcome-tags">

                    <span class="tag">
                        <i class="bi bi-sim-fill"></i>
                        CHIPS E LINHAS MÓVEIS
                    </span>

                    <span class="tag">
                        <i class="bi bi-phone-fill"></i>
                        SMARTPHONES
                    </span>

                    <span class="tag">
                        <i class="bi bi-printer-fill"></i>
                        ESTOQUE DE TONER
                    </span>

                    <span class="tag">
                        <i class="bi bi-clock-history"></i>
                        HISTÓRICO RASTREÁVEL
                    </span>

                </div>

            </article>

            <aside class="scope-card">
                <small>Itens sob controle</small>

                <strong><?= $totalItensControlados ?></strong>

                <p>
                    Soma de chips, smartphones e unidades de toner
                    atualmente registradas no sistema.
                </p>
            </aside>

        </section>

        <section
            class="modules"
            aria-label="Módulos autorizados"
        >

            <a href="chips.php" class="module">

                <div>

                    <div class="module-top">
                        <span class="module-icon">
                            <i class="bi bi-sim-fill"></i>
                        </span>

                        <span class="module-arrow">
                            <i class="bi bi-arrow-up-right"></i>
                        </span>
                    </div>

                    <h3>CONTROLE DE CHIPS</h3>

                    <p>
                        Cadastre linhas, identifique responsáveis,
                        registre setores, transferências, devoluções
                        e aparelhos vinculados.
                    </p>

                </div>

                <div class="module-metrics">

                    <span class="module-metric">
                        <strong><?= $chips['total'] ?></strong>
                        <span>Total</span>
                    </span>

                    <span class="module-metric">
                        <strong><?= $chips['em_uso'] ?></strong>
                        <span>Em uso</span>
                    </span>

                    <span class="module-metric">
                        <strong>
                            <?= $chips['sem_identificacao'] ?>
                        </strong>
                        <span>Sem identificação</span>
                    </span>

                </div>

            </a>

            <a href="tonner.php" class="module toner">

                <div>

                    <div class="module-top">
                        <span class="module-icon">
                            <i class="bi bi-printer-fill"></i>
                        </span>

                        <span class="module-arrow">
                            <i class="bi bi-arrow-up-right"></i>
                        </span>
                    </div>

                    <h3>ESTOQUE DE TONER</h3>

                    <p>
                        Controle entradas, saídas, responsáveis,
                        destinos, níveis mínimos e movimentações
                        dos suprimentos de impressão.
                    </p>

                </div>

                <div class="module-metrics">

                    <span class="module-metric">
                        <strong><?= $toner['unidades'] ?></strong>
                        <span>Unidades</span>
                    </span>

                    <span class="module-metric">
                        <strong><?= $toner['modelos'] ?></strong>
                        <span>Modelos</span>
                    </span>

                    <span class="module-metric">
                        <strong><?= $tonerAtencao ?></strong>
                        <span>Em atenção</span>
                    </span>

                </div>

            </a>

            <a href="smartphones.php" class="module smart">

                <div>

                    <div class="module-top">
                        <span class="module-icon">
                            <i class="bi bi-phone-fill"></i>
                        </span>

                        <span class="module-arrow">
                            <i class="bi bi-arrow-up-right"></i>
                        </span>
                    </div>

                    <h3>SMARTPHONES</h3>

                    <p>
                        Organize patrimônio, IMEI, modelo,
                        responsável, setor, acessórios,
                        manutenção e linha utilizada.
                    </p>

                </div>

                <div class="module-metrics">

                    <span class="module-metric">
                        <strong>
                            <?= $smartphones['total'] ?>
                        </strong>
                        <span>Total</span>
                    </span>

                    <span class="module-metric">
                        <strong>
                            <?= $smartphones['em_uso'] ?>
                        </strong>
                        <span>Em uso</span>
                    </span>

                    <span class="module-metric">
                        <strong>
                            <?= $smartphones['manutencao'] ?>
                        </strong>
                        <span>Manutenção</span>
                    </span>

                </div>

            </a>

        </section>

        <section class="content-grid">

            <article class="panel">

                <header class="panel-head">

                    <div class="panel-title">
                        <i class="bi bi-exclamation-triangle-fill"></i>

                        <div>
                            <strong>Pendências prioritárias</strong>
                            <span>
                                Itens que precisam de conferência.
                            </span>
                        </div>
                    </div>

                    <span class="panel-count">
                        <?= $totalPendencias ?>
                        pendência<?= $totalPendencias !== 1 ? 's' : '' ?>
                    </span>

                </header>

                <div class="panel-body">

                    <?php if (empty($pendencias)): ?>

                        <div class="all-good">
                            <i class="bi bi-shield-check"></i>

                            <strong>Tudo sob controle</strong>

                            <span>
                                Nenhuma pendência crítica foi
                                encontrada neste momento.
                            </span>
                        </div>

                    <?php else: ?>

                        <div class="pending-list">

                            <?php foreach ($pendencias as $pendencia): ?>

                                <a
                                    href="<?= dcE($pendencia['url']) ?>"
                                    class="pending <?= dcE(
                                        $pendencia['tipo']
                                    ) ?>"
                                >

                                    <span class="pending-icon">
                                        <i class="bi <?= dcE(
                                            $pendencia['icone']
                                        ) ?>"></i>
                                    </span>

                                    <span>
                                        <strong>
                                            <?= dcE(
                                                $pendencia['titulo']
                                            ) ?>
                                        </strong>

                                        <span>
                                            <?= dcE(
                                                $pendencia['texto']
                                            ) ?>
                                        </span>
                                    </span>

                                    <i
                                        class="bi bi-chevron-right pending-arrow"
                                    ></i>

                                </a>

                            <?php endforeach; ?>

                        </div>

                    <?php endif; ?>

                </div>

            </article>

            <article class="panel">

                <header class="panel-head">

                    <div class="panel-title">
                        <i class="bi bi-clock-history"></i>

                        <div>
                            <strong>Últimas movimentações</strong>
                            <span>
                                Alterações recentes nos três módulos.
                            </span>
                        </div>
                    </div>

                    <span class="panel-count">
                        <?= count($movimentacoes) ?> registros
                    </span>

                </header>

                <div class="panel-body">

                    <?php if (empty($movimentacoes)): ?>

                        <div class="all-good">
                            <i class="bi bi-clock-history"></i>

                            <strong>Sem movimentações recentes</strong>

                            <span>
                                Novas entregas, transferências e saídas
                                aparecerão aqui.
                            </span>
                        </div>

                    <?php else: ?>

                        <div class="movement-list">

                            <?php foreach ($movimentacoes as $movimento): ?>
                                <?php
                                $origem = strtoupper(
                                    (string) $movimento['origem']
                                );

                                $icone = match ($origem) {
                                    'TONER' => 'bi-printer-fill',
                                    'SMARTPHONE' => 'bi-phone-fill',
                                    default => 'bi-sim-fill'
                                };

                                $classeIcone = match ($origem) {
                                    'TONER' => 'toner',
                                    'SMARTPHONE' => 'smart',
                                    default => ''
                                };
                                ?>

                                <a
                                    href="<?= dcE($movimento['url']) ?>"
                                    class="movement"
                                >

                                    <span
                                        class="movement-icon <?= dcE(
                                            $classeIcone
                                        ) ?>"
                                    >
                                        <i class="bi <?= dcE($icone) ?>"></i>
                                    </span>

                                    <span>
                                        <strong>
                                            <?= dcE(
                                                $movimento['titulo']
                                            ) ?>
                                            •
                                            <?= dcE(
                                                $movimento['acao']
                                            ) ?>
                                        </strong>

                                        <?php if (
                                            trim(
                                                (string) $movimento['detalhe']
                                            ) !== ''
                                        ): ?>
                                            <span>
                                                <?= dcE(
                                                    $movimento['detalhe']
                                                ) ?>
                                            </span>
                                        <?php endif; ?>

                                        <span>
                                            Registrado por
                                            <?= dcE(
                                                $movimento['usuario']
                                                    ?: 'usuário do sistema'
                                            ) ?>
                                        </span>
                                    </span>

                                    <time>
                                        <?= dcE(
                                            dcData(
                                                $movimento['data']
                                            )
                                        ) ?>
                                    </time>

                                </a>

                            <?php endforeach; ?>

                        </div>

                    <?php endif; ?>

                </div>

            </article>

        </section>

        <footer class="footer">

            <span>
                Prefeitura de Extrema • Gerência de Tecnologia<br>
                Painel interno de telecomunicações e suprimentos.
            </span>

            <span>
                <i class="bi bi-shield-lock-fill"></i>
                Perfil autorizado:
                <strong>Chips, Toner e Smartphones</strong>
            </span>

        </footer>

    </main>

</div>

<script>
function atualizarDataHora() {
    const elemento = document.getElementById('currentDateTime');

    if (!elemento) {
        return;
    }

    const agora = new Date();

    const data = agora.toLocaleDateString('pt-BR', {
        weekday: 'long',
        day: '2-digit',
        month: 'long',
        year: 'numeric'
    });

    const hora = agora.toLocaleTimeString('pt-BR', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });

    elemento.textContent =
        `${data.charAt(0).toUpperCase()}${data.slice(1)} • ${hora}`;
}

atualizarDataHora();
window.setInterval(atualizarDataHora, 1000);
</script>

<script src="alerta_global_cliente.js?v=7"></script>



<?php if ($mostrarPopupMobile): ?>
<script>
(() => {
    'use strict';

    const popup = document.getElementById('mobileAppPopup');

    if (!popup) {
        return;
    }

    const closeButtons = popup.querySelectorAll(
        '[data-mobile-popup-close]'
    );

    const focusable = popup.querySelector(
        '.mobile-app-popup__close'
    );

    let closed = false;
    const previousFocus = document.activeElement;

    const closePopup = () => {
        if (closed) {
            return;
        }

        closed = true;
        popup.classList.add('is-closing');
        popup.classList.remove('is-visible');
        document.documentElement.classList.remove(
            'mobile-app-popup-open'
        );
        document.body.classList.remove(
            'mobile-app-popup-open'
        );

        window.setTimeout(() => {
            popup.remove();

            if (
                previousFocus &&
                typeof previousFocus.focus === 'function'
            ) {
                previousFocus.focus({ preventScroll: true });
            }
        }, 330);
    };

    closeButtons.forEach(button => {
        button.addEventListener('click', closePopup);
    });

    popup.addEventListener('keydown', event => {
        if (event.key === 'Escape') {
            event.preventDefault();
            closePopup();
            return;
        }

        if (event.key !== 'Tab') {
            return;
        }

        const elements = [...popup.querySelectorAll(
            'button:not([disabled]), a[href]'
        )].filter(element => element.offsetParent !== null);

        if (elements.length === 0) {
            return;
        }

        const first = elements[0];
        const last = elements[elements.length - 1];

        if (event.shiftKey && document.activeElement === first) {
            event.preventDefault();
            last.focus();
        } else if (
            !event.shiftKey &&
            document.activeElement === last
        ) {
            event.preventDefault();
            first.focus();
        }
    });

    document.documentElement.classList.add(
        'mobile-app-popup-open'
    );
    document.body.classList.add('mobile-app-popup-open');

    window.setTimeout(() => {
        window.requestAnimationFrame(() => {
            popup.classList.add('is-visible');
            focusable?.focus({ preventScroll: true });
        });
    }, 420);
})();
</script>
<?php endif; ?>

</body>
</html>
