<?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');

$id = (int) ($_GET['id'] ?? 0);
$impressora = impBuscarImpressora($mysqli, $id);

if (!$impressora) {
    http_response_code(404);
    exit('Impressora não encontrada.');
}

$manutencoes = [];
$movimentos = [];
$anexos = [];
$termos = [];

$stmt = impExecutar(
    $mysqli,
    'SELECT *
     FROM ti_impressora_manutencoes
     WHERE impressora_id = ?
     ORDER BY id DESC
     LIMIT 30',
    [$id]
);

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

$stmt = impExecutar(
    $mysqli,
    'SELECT *
     FROM ti_impressora_movimentacoes
     WHERE impressora_id = ?
     ORDER BY id DESC
     LIMIT 100',
    [$id]
);

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

$stmt = impExecutar(
    $mysqli,
    'SELECT *
     FROM ti_impressora_anexos
     WHERE impressora_id = ?
     ORDER BY id DESC',
    [$id]
);

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

$stmt = impExecutar(
    $mysqli,
    'SELECT *
     FROM ti_impressora_termos
     WHERE impressora_id = ?
     ORDER BY id DESC',
    [$id]
);

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

$ativa = impManutencaoAtiva($mysqli, $id);
$status = impStatus((string) $impressora['status']);
$flash = impConsumirFlash();
?>
<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Ficha da Impressora</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">
</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-printer-fill"></i><?= impE($impressora['codigo_interno']) ?></span>
                <h1 class="header-title"><?= impE($impressora['marca'] . ' ' . $impressora['modelo']) ?></h1>
                <p class="header-subtitle">Patrimônio <?= impE($impressora['patrimonio'] ?: 'não informado') ?> • Série <?= impE($impressora['numero_serie'] ?: 'não informada') ?></p>
            </div>
        </div>
        <nav class="header-actions">
            <a href="impressoras.php" class="header-button"><i class="bi bi-arrow-left"></i>Voltar</a>
            <a href="nova_impressora.php?id=<?= $id ?>" class="header-button"><i class="bi bi-pencil-fill"></i>Editar</a>
            <?php if (!$ativa): ?>
                <a href="receber_impressora.php?id=<?= $id ?>" class="header-button primary"><i class="bi bi-box-arrow-in-down"></i>Receber TI</a>
            <?php else: ?>
                <a href="manutencao_impressora.php?id=<?= (int) $ativa['id'] ?>" class="header-button primary"><i class="bi bi-tools"></i>Manutenção</a>
            <?php endif; ?>
        </nav>
    </div>
</header>

<main class="main">
<?php if ($flash): ?>
    <div class="flash <?= $flash['tipo'] === 'sucesso' ? 'success' : 'error' ?>"><i class="bi bi-check-circle-fill"></i><?= impE($flash['mensagem']) ?></div>
<?php endif; ?>

<section class="form-card">
    <div class="detail-grid">
        <div class="detail"><span>Status</span><strong><span class="status <?= impE($status['classe']) ?>"><i class="bi <?= impE($status['icone']) ?>"></i><?= impE($status['rotulo']) ?></span></strong></div>
        <div class="detail"><span>Localização</span><strong><?= impE($impressora['setor_nome'] ?: 'Sem setor') ?> • <?= impE($impressora['ambiente_nome'] ?: 'Sem ambiente') ?></strong></div>
        <div class="detail"><span>Local atual</span><strong><?= impE($impressora['local_atual'] ?: 'Não informado') ?></strong></div>
        <div class="detail"><span>Responsável</span><strong><?= impE($impressora['responsavel_nome'] ?: 'Não informado') ?></strong></div>
        <div class="detail"><span>Rede</span><strong><?= impE($impressora['ip'] ?: 'Sem IP') ?> • <?= impE($impressora['nome_rede'] ?: 'Sem nome') ?></strong></div>
        <div class="detail"><span>Toner</span><strong><?= impE($impressora['toner_modelo'] ?: 'Não vinculado') ?></strong></div>
        <div class="detail"><span>Contador</span><strong><?= number_format((int) $impressora['contador_paginas'],0,',','.') ?> páginas</strong></div>
        <div class="detail"><span>Condição</span><strong><?= impE(impCondicao((string) $impressora['condicao'])) ?></strong></div>
        <div class="detail"><span>Conexão</span><strong><?= impE($impressora['conexao'] ?: 'Não informada') ?></strong></div>
        <div class="detail"><span>Fila</span><strong><?= impE($impressora['fila_impressao'] ?: 'Não informada') ?></strong></div>
        <div class="detail"><span>Propriedade</span><strong><?= impE($impressora['propriedade']) ?></strong></div>
        <div class="detail"><span>Garantia</span><strong><?= impE($impressora['garantia_ate'] ?: 'Não informada') ?></strong></div>
    </div>
</section>

<section class="panel">
    <div class="panel-head">
        <div class="panel-title"><span class="panel-title-icon"><i class="bi bi-tools"></i></span><div><h3>Atendimentos</h3><p>Histórico de entradas e manutenções.</p></div></div>
    </div>
    <div style="padding:14px">
        <?php if (!$manutencoes): ?>
            <div class="empty"><i class="bi bi-tools"></i><strong>Nenhum atendimento registrado</strong></div>
        <?php else: ?>
            <div class="timeline">
                <?php foreach ($manutencoes as $m): ?>
                    <article class="timeline-item">
                        <span class="timeline-icon"><i class="bi bi-tools"></i></span>
                        <span>
                            <strong><?= impE($m['numero_atendimento']) ?> • <?= impE(str_replace('_',' ',$m['status'])) ?></strong>
                            <span>Defeito: <?= impE($m['defeito_relatado']) ?></span>
                            <span>Solução: <?= impE($m['solucao'] ?: 'não finalizada') ?></span>
                            <span><a href="manutencao_impressora.php?id=<?= (int) $m['id'] ?>">Abrir atendimento</a></span>
                        </span>
                        <time><?= impE(impData($m['data_entrada'])) ?></time>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<section class="panel" id="historico">
    <div class="panel-head">
        <div class="panel-title"><span class="panel-title-icon"><i class="bi bi-clock-history"></i></span><div><h3>Linha do tempo</h3><p>Todas as movimentações auditadas.</p></div></div>
    </div>
    <div style="padding:14px">
        <?php if (!$movimentos): ?>
            <div class="empty"><i class="bi bi-clock-history"></i><strong>Sem movimentações</strong></div>
        <?php else: ?>
            <div class="timeline">
                <?php foreach ($movimentos as $m): ?>
                    <article class="timeline-item">
                        <span class="timeline-icon"><i class="bi bi-arrow-left-right"></i></span>
                        <span><strong><?= impE(str_replace('_',' ',$m['acao'])) ?></strong><span><?= impE($m['detalhes'] ?: 'Sem detalhes') ?> • por <?= impE($m['usuario']) ?></span></span>
                        <time><?= impE(impData($m['criado_em'])) ?></time>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<section class="panel">
    <div class="panel-head">
        <div class="panel-title"><span class="panel-title-icon"><i class="bi bi-file-earmark-text-fill"></i></span><div><h3>Termos e anexos</h3><p>Documentos vinculados à impressora.</p></div></div>
    </div>
    <div style="padding:14px">
        <div class="actions" style="justify-content:flex-start">
            <?php foreach ($termos as $t): ?>
                <a class="action purple" target="_blank" href="<?= $t['tipo'] === 'ENTRADA' ? 'termo_entrada_impressora.php' : 'termo_entrega_impressora.php' ?>?termo_id=<?= (int) $t['id'] ?>"><i class="bi bi-file-earmark-pdf-fill"></i><?= impE($t['numero_termo']) ?></a>
            <?php endforeach; ?>
            <?php foreach ($anexos as $a): ?>
                <a class="action" target="_blank" href="visualizar_anexo_impressora.php?id=<?= (int) $a['id'] ?>"><i class="bi bi-paperclip"></i><?= impE($a['nome_original']) ?></a>
            <?php endforeach; ?>
        </div>
        <?php if (!$termos && !$anexos): ?>
            <div class="empty"><i class="bi bi-folder2-open"></i><strong>Nenhum documento</strong></div>
        <?php endif; ?>
    </div>
</section>
</main>
</div>
</body>
</html>
