<?php
declare(strict_types=1);

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

date_default_timezone_set('America/Sao_Paulo');
impressorasExigirAcesso();
$mysqli->set_charset('utf8mb4');

$csrf = impCsrf();
$setorId = (int) ($_GET['setor_id'] ?? $_POST['setor_id'] ?? 0);
$erro = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        impValidarCsrf();
        $acao = impTexto($_POST['acao'] ?? '', 40);
        $usuario = impressorasUsuarioAtual();

        if ($acao === 'salvar_ambiente') {
            $setor = (int) ($_POST['setor_id'] ?? 0);
            $nome = impTexto($_POST['nome'] ?? '', 150);
            $tipo = impTexto($_POST['tipo'] ?? 'SALA', 50);
            $coluna = max(1, min(12, (int) ($_POST['grid_coluna'] ?? 1)));
            $linha = max(1, (int) ($_POST['grid_linha'] ?? 1));
            $largura = max(1, min(12, (int) ($_POST['grid_largura'] ?? 3)));
            $altura = max(1, min(8, (int) ($_POST['grid_altura'] ?? 1)));
            $cor = impNulo($_POST['cor'] ?? '', 20);

            if ($setor <= 0 || $nome === '') {
                throw new RuntimeException(
                    'Informe o setor e o ambiente.'
                );
            }

            impExecutar(
                $mysqli,
                "INSERT INTO ti_ambientes (
                    setor_id,nome,tipo,grid_coluna,grid_linha,
                    grid_largura,grid_altura,cor,criado_por
                 )
                 VALUES (?,?,?,?,?,?,?,?,?)
                 ON DUPLICATE KEY UPDATE
                    tipo=VALUES(tipo),
                    grid_coluna=VALUES(grid_coluna),
                    grid_linha=VALUES(grid_linha),
                    grid_largura=VALUES(grid_largura),
                    grid_altura=VALUES(grid_altura),
                    cor=VALUES(cor)",
                [
                    $setor,$nome,$tipo,$coluna,$linha,
                    $largura,$altura,$cor,$usuario
                ]
            )->close();

            impFlash(
                'sucesso',
                'Ambiente configurado no mapa.'
            );

            impRedirecionar(
                'mapa_impressoras.php?setor_id=' . $setor
            );
        }

        if ($acao === 'mover') {
            $impressoraId = (int) ($_POST['impressora_id'] ?? 0);
            $novoSetor = (int) ($_POST['novo_setor_id'] ?? 0);
            $ambiente = (int) ($_POST['ambiente_id'] ?? 0);
            $local = impNulo(
                $_POST['localizacao_texto'] ?? '',
                180
            );

            if ($impressoraId <= 0 || $novoSetor <= 0) {
                throw new RuntimeException(
                    'Selecione a impressora e o setor.'
                );
            }

            $mysqli->begin_transaction();

            $impressora = impBuscarImpressora(
                $mysqli,
                $impressoraId,
                true
            );

            if (!$impressora) {
                throw new RuntimeException(
                    'Impressora não encontrada.'
                );
            }

            $novoLocal = 'SETOR / MAPA INTERNO';

            impExecutar(
                $mysqli,
                "UPDATE ti_impressoras
                 SET setor_id=?,
                     ambiente_id=NULLIF(?,0),
                     localizacao_texto=?,
                     local_atual=?,
                     atualizado_por=?
                 WHERE id=?",
                [
                    $novoSetor,$ambiente,$local,
                    $novoLocal,$usuario,$impressoraId
                ]
            )->close();

            $stmt = impExecutar(
                $mysqli,
                'SELECT nome
                 FROM ti_setores
                 WHERE id = ?',
                [$novoSetor]
            );

            $setorNovo = $stmt
                ->get_result()
                ->fetch_assoc()['nome'] ?? null;

            $stmt->close();

            impRegistrarHistorico(
                $mysqli,
                $impressoraId,
                null,
                'LOCALIZACAO_ALTERADA',
                $impressora['status'],
                $impressora['status'],
                $impressora['setor_nome'],
                $setorNovo,
                $impressora['localizacao_texto'],
                $local,
                'Movimentação realizada pelo mapa.'
            );

            $mysqli->commit();

            impFlash(
                'sucesso',
                'Impressora movida no mapa.'
            );

            impRedirecionar(
                'mapa_impressoras.php?setor_id=' . $novoSetor
            );
        }
    } catch (Throwable $e) {
        try {
            $mysqli->rollback();
        } catch (Throwable) {
        }

        $erro = $e->getMessage();
    }
}

$flash = impConsumirFlash();
$setores = [];
$ambientes = [];
$impressoras = [];

$resultado = $mysqli->query(
    'SELECT id,nome,secretaria,predio,andar
     FROM ti_setores
     WHERE ativo=1
     ORDER BY nome'
);

if ($resultado) {
    while ($linha = $resultado->fetch_assoc()) {
        $setores[] = $linha;
    }
}

if ($setorId <= 0 && $setores) {
    $setorId = (int) $setores[0]['id'];
}

if ($setorId > 0) {
    $stmt = impExecutar(
        $mysqli,
        'SELECT *
         FROM ti_ambientes
         WHERE setor_id=?
           AND ativo=1
         ORDER BY ordem,nome',
        [$setorId]
    );

    $resultado = $stmt->get_result();
    while ($linha = $resultado->fetch_assoc()) {
        $ambientes[] = $linha;
    }
    $stmt->close();

    $stmt = impExecutar(
        $mysqli,
        "SELECT i.*,a.nome AS ambiente_nome
         FROM ti_impressoras AS i
         LEFT JOIN ti_ambientes AS a
            ON a.id=i.ambiente_id
         WHERE i.setor_id=?
           AND i.status<>'BAIXADA'
         ORDER BY a.nome,i.marca,i.modelo",
        [$setorId]
    );

    $resultado = $stmt->get_result();
    while ($linha = $resultado->fetch_assoc()) {
        $impressoras[] = $linha;
    }
    $stmt->close();
}

$porAmbiente = [];

foreach ($impressoras as $impressora) {
    $porAmbiente[(int) ($impressora['ambiente_id'] ?? 0)][] = $impressora;
}
?>
<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Mapa de Impressoras</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">
    <link href="impressoras_style.css?v=1" rel="stylesheet">
    <style>
        .map-grid{display:grid;grid-template-columns:repeat(12,minmax(60px,1fr));grid-auto-rows:115px;gap:10px;min-width:1000px;padding:16px;background:linear-gradient(rgba(8,57,111,.035) 1px,transparent 1px),linear-gradient(90deg,rgba(8,57,111,.035) 1px,transparent 1px),#f8fbfd;background-size:40px 40px}
        .room{overflow:auto;padding:12px;border:2px solid var(--room,#145b9f);border-radius:18px;background:rgba(255,255,255,.94);box-shadow:0 12px 26px rgba(8,57,111,.08)}
        .room h4{margin:0 0 8px;font-size:9px;font-weight:950;text-transform:uppercase}
        .printer-pin{display:flex;align-items:center;gap:7px;margin-bottom:6px;padding:7px;border:1px solid var(--border);border-radius:11px;background:var(--soft);font-size:7px;color:var(--text)}
        .printer-pin i{color:var(--blue);font-size:14px}.printer-pin strong{display:block;font-size:7.5px}.printer-pin span{display:block;margin-top:2px;color:var(--muted);font-size:6.5px}
    </style>
</head>
<body>
<div class="top-strip"></div>
<div class="bg-grid"></div>
<div class="app">
<header class="main-header">
    <div class="header-content">
        <div class="brand-area">
            <div class="logo-box"><img src="assets/logo_pref.jpg" alt=""></div>
            <div>
                <span class="eyebrow"><i class="bi bi-diagram-3-fill"></i>Mapa interno</span>
                <h1 class="header-title">Mapa de Impressoras</h1>
                <p class="header-subtitle">Planta lógica por setor, sala e posição. Não utiliza Google Maps.</p>
            </div>
        </div>
        <nav class="header-actions"><a href="impressoras.php" class="header-button primary"><i class="bi bi-arrow-left"></i>Impressoras</a></nav>
    </div>
</header>

<main class="main">
<?php if ($erro): ?><div class="flash error"><?= impE($erro) ?></div><?php endif; ?>
<?php if ($flash): ?><div class="flash success"><?= impE($flash['mensagem']) ?></div><?php endif; ?>

<section class="form-card">
    <form method="get" class="filters" style="padding:0;border:0">
        <select class="control" name="setor_id" onchange="this.form.submit()">
            <?php foreach ($setores as $setor): ?>
                <option value="<?= (int) $setor['id'] ?>" <?= $setorId === (int) $setor['id'] ? 'selected' : '' ?>><?= impE($setor['nome'] . ' • ' . ($setor['predio'] ?: 'sem prédio')) ?></option>
            <?php endforeach; ?>
        </select>
    </form>
</section>

<section class="panel">
    <div class="panel-head">
        <div class="panel-title"><span class="panel-title-icon"><i class="bi bi-building-fill"></i></span><div><h3>Planta lógica do setor</h3><p><?= count($impressoras) ?> impressora(s) posicionada(s).</p></div></div>
    </div>
    <div class="table-wrap">
        <div class="map-grid">
            <?php foreach ($ambientes as $ambiente): ?>
                <section class="room" style="--room:<?= impE($ambiente['cor'] ?: '#145b9f') ?>;grid-column:<?= (int) $ambiente['grid_coluna'] ?> / span <?= (int) $ambiente['grid_largura'] ?>;grid-row:<?= (int) $ambiente['grid_linha'] ?> / span <?= (int) $ambiente['grid_altura'] ?>">
                    <h4><?= impE($ambiente['nome']) ?></h4>
                    <?php foreach ($porAmbiente[(int) $ambiente['id']] ?? [] as $impressora): ?>
                        <a class="printer-pin" href="detalhes_impressora.php?id=<?= (int) $impressora['id'] ?>">
                            <i class="bi bi-printer-fill"></i>
                            <span><strong><?= impE($impressora['marca'] . ' ' . $impressora['modelo']) ?></strong><span>Pat. <?= impE($impressora['patrimonio'] ?: 's/ patrimônio') ?> • <?= impE($impressora['localizacao_texto'] ?: 'posição não informada') ?></span></span>
                        </a>
                    <?php endforeach; ?>
                </section>
            <?php endforeach; ?>

            <?php if (!empty($porAmbiente[0])): ?>
                <section class="room" style="--room:#d17a00;grid-column:1 / span 12;grid-row:auto / span 1">
                    <h4>Sem ambiente definido</h4>
                    <?php foreach ($porAmbiente[0] as $impressora): ?>
                        <a class="printer-pin" href="detalhes_impressora.php?id=<?= (int) $impressora['id'] ?>">
                            <i class="bi bi-exclamation-triangle-fill"></i>
                            <span><strong><?= impE($impressora['marca'] . ' ' . $impressora['modelo']) ?></strong><span>Pat. <?= impE($impressora['patrimonio'] ?: 's/ patrimônio') ?> • posição pendente</span></span>
                        </a>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>

            <?php if (!$ambientes): ?>
                <div class="empty" style="grid-column:1/-1"><i class="bi bi-diagram-3-fill"></i><strong>Nenhum ambiente configurado</strong><span>Cadastre abaixo a primeira sala do setor.</span></div>
            <?php endif; ?>
        </div>
    </div>
</section>

<section class="form-card">
    <section class="form-section">
        <h3><i class="bi bi-plus-square-fill"></i>Configurar ambiente</h3>
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= impE($csrf) ?>">
            <input type="hidden" name="acao" value="salvar_ambiente">
            <input type="hidden" name="setor_id" value="<?= $setorId ?>">
            <div class="form-grid">
                <div class="form-group"><label>Nome da sala / ambiente</label><input class="control" name="nome" required></div>
                <div class="form-group"><label>Tipo</label><input class="control" name="tipo" value="SALA"></div>
                <div class="form-group"><label>Cor</label><input class="control" type="color" name="cor" value="#145b9f"></div>
                <div class="form-group"><label>Coluna inicial (1-12)</label><input class="control" type="number" min="1" max="12" name="grid_coluna" value="1"></div>
                <div class="form-group"><label>Linha inicial</label><input class="control" type="number" min="1" name="grid_linha" value="1"></div>
                <div class="form-group"><label>Largura</label><input class="control" type="number" min="1" max="12" name="grid_largura" value="3"></div>
                <div class="form-group"><label>Altura</label><input class="control" type="number" min="1" max="8" name="grid_altura" value="1"></div>
            </div>
            <div class="form-actions"><button class="button primary">Salvar ambiente</button></div>
        </form>
    </section>

    <section class="form-section">
        <h3><i class="bi bi-arrows-move"></i>Mover impressora</h3>
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= impE($csrf) ?>">
            <input type="hidden" name="acao" value="mover">
            <input type="hidden" name="novo_setor_id" value="<?= $setorId ?>">
            <div class="form-grid">
                <div class="form-group"><label>Impressora</label><select class="control" name="impressora_id" required><option value="">Selecione</option><?php foreach ($impressoras as $impressora): ?><option value="<?= (int) $impressora['id'] ?>"><?= impE($impressora['marca'] . ' ' . $impressora['modelo'] . ' • Pat. ' . ($impressora['patrimonio'] ?: 's/ patrimônio')) ?></option><?php endforeach; ?></select></div>
                <div class="form-group"><label>Ambiente</label><select class="control" name="ambiente_id"><option value="">Sem ambiente</option><?php foreach ($ambientes as $ambiente): ?><option value="<?= (int) $ambiente['id'] ?>"><?= impE($ambiente['nome']) ?></option><?php endforeach; ?></select></div>
                <div class="form-group"><label>Posição exata</label><input class="control" name="localizacao_texto" maxlength="180"></div>
            </div>
            <div class="form-actions"><button class="button green">Mover no mapa</button></div>
        </form>
    </section>
</section>
</main>
</div>
</body>
</html>
