<?php
declare(strict_types=1);

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

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

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

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

function jsonOut(array $data, int $status = 200): never
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE |
        JSON_UNESCAPED_SLASHES |
        JSON_HEX_TAG |
        JSON_HEX_APOS |
        JSON_HEX_QUOT |
        JSON_HEX_AMP
    );
    exit;
}

function colunaExiste(mysqli $db, string $tabela, string $coluna): bool
{
    $stmt = $db->prepare("
        SELECT COUNT(*) 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();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

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

function post(string $key, string $default = ''): string
{
    return trim((string)($_POST[$key] ?? $_GET[$key] ?? $default));
}

function numeroOs(): string
{
    try {
        $suffix = strtoupper(bin2hex(random_bytes(2)));
    } catch (Throwable) {
        $suffix = strtoupper(substr(md5(uniqid('', true)), 0, 4));
    }

    return 'MANU-' . date('Ymd-His') . '-' . $suffix;
}

function sugerirPrioridade(string $texto): array
{
    $texto = mb_strtolower($texto, 'UTF-8');

    $urgentes = [
        'pegou fogo', 'incêndio', 'incendio', 'explodiu',
        'servidor caiu', 'servidor parado', 'tudo parado',
        'todos sem acesso', 'rede toda caiu', 'risco elétrico',
        'risco eletrico', 'sem energia'
    ];

    $altas = [
        'não liga', 'nao liga', 'rede caiu', 'sem internet',
        'internet caiu', 'não inicia', 'nao inicia',
        'impressora parada', 'setor parado', 'tela azul',
        'erro crítico', 'erro critico', 'travando muito'
    ];

    foreach ($urgentes as $termo) {
        if (str_contains($texto, $termo)) {
            return [
                'prioridade' => 'Urgente',
                'prazo' => 1,
                'motivo' => "Termo crítico identificado: {$termo}"
            ];
        }
    }

    foreach ($altas as $termo) {
        if (str_contains($texto, $termo)) {
            return [
                'prioridade' => 'Alta',
                'prazo' => 2,
                'motivo' => "Impacto elevado identificado: {$termo}"
            ];
        }
    }

    return [
        'prioridade' => 'Média',
        'prazo' => 5,
        'motivo' => 'Nenhum termo de criticidade alta foi identificado.'
    ];
}

if (empty($_SESSION['csrf_nova_os'])) {
    $_SESSION['csrf_nova_os'] = bin2hex(random_bytes(24));
}

$csrf = (string)$_SESSION['csrf_nova_os'];

/* AJAX */
if (isset($_GET['action'])) {
    $action = trim((string)$_GET['action']);

    if ($action === 'search_patrimonio') {
        $q = trim((string)($_GET['q'] ?? ''));

        if ($q === '') {
            jsonOut([]);
        }

        $like = "%{$q}%";

        $stmt = $mysqli->prepare("
            SELECT
                patrimonio,
                COUNT(*) total_os,
                MAX(data_entrada) ultima_data
            FROM ordens_servico
            WHERE patrimonio LIKE ?
              AND TRIM(COALESCE(patrimonio, '')) <> ''
            GROUP BY patrimonio
            ORDER BY
                CASE
                    WHEN patrimonio = ? THEN 0
                    WHEN patrimonio LIKE CONCAT(?, '%') THEN 1
                    ELSE 2
                END,
                patrimonio
            LIMIT 12
        ");

        if (!$stmt) {
            jsonOut([]);
        }

        $stmt->bind_param('sss', $like, $q, $q);
        $stmt->execute();
        $res = $stmt->get_result();

        $items = [];

        while ($row = $res->fetch_assoc()) {
            $items[] = [
                'patrimonio' => (string)$row['patrimonio'],
                'total_os' => (int)$row['total_os'],
                'ultima_data' => (string)($row['ultima_data'] ?? '')
            ];
        }

        $stmt->close();
        jsonOut($items);
    }

    if ($action === 'get_patrimonio') {
        $pat = trim((string)($_GET['pat'] ?? ''));

        if ($pat === '') {
            jsonOut([]);
        }

        $stmt = $mysqli->prepare("
            SELECT
                tipo_equipamento,
                marca,
                modelo,
                numero_serie,
                setor,
                nome_solicitante,
                telefone,
                problema,
                status,
                prioridade,
                data_entrada
            FROM ordens_servico
            WHERE patrimonio = ?
            ORDER BY data_entrada DESC
            LIMIT 1
        ");

        if (!$stmt) {
            jsonOut([]);
        }

        $stmt->bind_param('s', $pat);
        $stmt->execute();
        $data = $stmt->get_result()->fetch_assoc() ?: [];
        $stmt->close();

        $stmt = $mysqli->prepare("
            SELECT
                COUNT(*) total,
                SUM(
                    CASE
                        WHEN LOWER(TRIM(status)) <> 'finalizado'
                        THEN 1 ELSE 0
                    END
                ) abertas
            FROM ordens_servico
            WHERE patrimonio = ?
        ");

        if ($stmt) {
            $stmt->bind_param('s', $pat);
            $stmt->execute();
            $count = $stmt->get_result()->fetch_assoc() ?: [];
            $stmt->close();

            $data['total_os'] = (int)($count['total'] ?? 0);
            $data['os_abertas'] = (int)($count['abertas'] ?? 0);
        }

        jsonOut($data);
    }

    if ($action === 'suggest_priority') {
        jsonOut(sugerirPrioridade((string)($_GET['text'] ?? '')));
    }

    jsonOut([]);
}

/* SUBMISSÃO */
$erro = '';
$arquivoSalvo = '';
$temEmail = colunaExiste($mysqli, 'ordens_servico', 'email');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfRecebido = (string)($_POST['csrf_token'] ?? '');

    if (
        $csrfRecebido === '' ||
        !hash_equals($csrf, $csrfRecebido)
    ) {
        $erro = 'A sessão do formulário expirou. Atualize a página.';
    }

    $nome = post('nome_solicitante');
    $setor = post('setor');
    $email = post('email');
    $telefone = post('telefone');

    $tipo = post('tipo_equipamento');
    $marca = post('marca');
    $modelo = post('modelo');
    $patrimonio = post('patrimonio');
    $serie = post('numero_serie');

    $problema = trim((string)($_POST['problema'] ?? ''));
    $prioridade = post('prioridade', 'Média');
    $prazo = max(1, min(365, (int)($_POST['prazo'] ?? 5)));
    $quantidade = max(1, min(50, (int)($_POST['quantidade'] ?? 1)));

    if (!in_array(
        $prioridade,
        ['Baixa', 'Média', 'Alta', 'Urgente'],
        true
    )) {
        $prioridade = 'Média';
    }

    if ($erro === '' && $nome === '') {
        $erro = 'Informe o nome do solicitante.';
    }

    if ($erro === '' && $setor === '') {
        $erro = 'Informe o setor.';
    }

    if ($erro === '' && $telefone === '') {
        $erro = 'Informe o telefone ou ramal.';
    }

    if ($erro === '' && mb_strlen($problema, 'UTF-8') < 10) {
        $erro = 'Descreva o problema com pelo menos 10 caracteres.';
    }

    if (
        $erro === '' &&
        $email !== '' &&
        filter_var($email, FILTER_VALIDATE_EMAIL) === false
    ) {
        $erro = 'O e-mail informado é inválido.';
    }

    /* UPLOAD */
    if (
        $erro === '' &&
        isset($_FILES['anexo']) &&
        (int)$_FILES['anexo']['error'] !== UPLOAD_ERR_NO_FILE
    ) {
        $file = $_FILES['anexo'];

        if ((int)$file['error'] !== UPLOAD_ERR_OK) {
            $erro = 'Falha ao receber o anexo.';
        } elseif ((int)$file['size'] > 8 * 1024 * 1024) {
            $erro = 'O anexo deve ter no máximo 8 MB.';
        } else {
            $mime = '';

            if (function_exists('finfo_open')) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);

                if ($finfo !== false) {
                    $mime = (string)finfo_file(
                        $finfo,
                        (string)$file['tmp_name']
                    );
                    finfo_close($finfo);
                }
            }

            $allowed = [
                'image/png' => 'png',
                'image/jpeg' => 'jpg',
                'application/pdf' => 'pdf'
            ];

            if (!isset($allowed[$mime])) {
                $erro = 'Envie somente PNG, JPG, JPEG ou PDF.';
            } else {
                $dir = __DIR__ . '/uploads';

                if (
                    !is_dir($dir) &&
                    !mkdir($dir, 0755, true) &&
                    !is_dir($dir)
                ) {
                    $erro = 'Não foi possível criar a pasta de anexos.';
                } else {
                    $fileName =
                        'os_' .
                        date('Ymd_His') .
                        '_' .
                        bin2hex(random_bytes(5)) .
                        '.' .
                        $allowed[$mime];

                    if (
                        !move_uploaded_file(
                            (string)$file['tmp_name'],
                            $dir . '/' . $fileName
                        )
                    ) {
                        $erro = 'Não foi possível salvar o anexo.';
                    } else {
                        $arquivoSalvo = 'uploads/' . $fileName;
                    }
                }
            }
        }
    }

    if ($erro === '') {
        $status = 'Em andamento';

        try {
            $mysqli->begin_transaction();

            if ($temEmail) {
                $sql = "
                    INSERT INTO ordens_servico (
                        numero_os, nome_solicitante, setor, email,
                        telefone, tipo_equipamento, marca, modelo,
                        patrimonio, numero_serie, problema, status,
                        prioridade, prazo, anexo, token_acompanhamento,
                        acompanhamento_ativo, mensagem_publica
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ";
            } else {
                $sql = "
                    INSERT INTO ordens_servico (
                        numero_os, nome_solicitante, setor,
                        telefone, tipo_equipamento, marca, modelo,
                        patrimonio, numero_serie, problema, status,
                        prioridade, prazo, anexo, token_acompanhamento,
                        acompanhamento_ativo, mensagem_publica
                    )
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ";
            }

            $idsCriadas = [];

            for ($i = 1; $i <= $quantidade; $i++) {
                $numero = numeroOs();

                $descricao = $quantidade > 1
                    ? "[Equipamento {$i} de {$quantidade}] {$problema}"
                    : $problema;

                $tokenAcompanhamento = osPublicoGerarToken();
                $acompanhamentoAtivo = 1;
                $mensagemPublica =
                    'Sua solicitação foi recebida e encaminhada para análise da Gerência de Tecnologia.';

                $stmt = $mysqli->prepare($sql);

                if (!$stmt) {
                    throw new RuntimeException(
                        'Falha na preparação: ' . $mysqli->error
                    );
                }

                if ($temEmail) {
                    $stmt->bind_param(
                        'sssssssssssssissis',
                        $numero,
                        $nome,
                        $setor,
                        $email,
                        $telefone,
                        $tipo,
                        $marca,
                        $modelo,
                        $patrimonio,
                        $serie,
                        $descricao,
                        $status,
                        $prioridade,
                        $prazo,
                        $arquivoSalvo,
                        $tokenAcompanhamento,
                        $acompanhamentoAtivo,
                        $mensagemPublica
                    );
                } else {
                    $stmt->bind_param(
                        'ssssssssssssissis',
                        $numero,
                        $nome,
                        $setor,
                        $telefone,
                        $tipo,
                        $marca,
                        $modelo,
                        $patrimonio,
                        $serie,
                        $descricao,
                        $status,
                        $prioridade,
                        $prazo,
                        $arquivoSalvo,
                        $tokenAcompanhamento,
                        $acompanhamentoAtivo,
                        $mensagemPublica
                    );
                }

                if (!$stmt->execute()) {
                    $msg = $stmt->error;
                    $stmt->close();

                    throw new RuntimeException(
                        'Falha ao salvar a OS: ' . $msg
                    );
                }

                $novaOsId = (int) $stmt->insert_id;
                $idsCriadas[] = $novaOsId;
                $stmt->close();

                osPublicoRegistrarAtualizacao(
                    $mysqli,
                    $novaOsId,
                    'Solicitação recebida',
                    'A ordem de serviço foi registrada e encaminhada para análise da equipe técnica.',
                    'RECEBIDA',
                    (string) ($_SESSION['usuario'] ?? 'Sistema'),
                    1
                );

                usleep(1200);
            }

            $mysqli->commit();

            $_SESSION['csrf_nova_os'] = bin2hex(random_bytes(24));

            $loteComprovante = bin2hex(random_bytes(16));

            if (
                !isset($_SESSION['lotes_comprovante_abertura_os']) ||
                !is_array($_SESSION['lotes_comprovante_abertura_os'])
            ) {
                $_SESSION['lotes_comprovante_abertura_os'] = [];
            }

            $_SESSION['lotes_comprovante_abertura_os'][$loteComprovante] = [
                'ids' => $idsCriadas,
                'criado_em' => time()
            ];

            header(
                'Location: comprovante_abertura_os.php?lote=' .
                rawurlencode($loteComprovante) .
                '&print=1'
            );
            exit;
        } catch (Throwable $ex) {
            $mysqli->rollback();

            if (
                $arquivoSalvo !== '' &&
                is_file(__DIR__ . '/' . $arquivoSalvo)
            ) {
                @unlink(__DIR__ . '/' . $arquivoSalvo);
            }

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

/* RESUMO */
$resumo = [
    'patrimonios' => 0,
    'setores' => 0,
    'hoje' => 0
];

$res = $mysqli->query("
    SELECT
        COUNT(DISTINCT NULLIF(TRIM(patrimonio), '')) patrimonios,
        COUNT(DISTINCT NULLIF(TRIM(setor), '')) setores,
        SUM(
            CASE WHEN DATE(data_entrada) = CURDATE()
            THEN 1 ELSE 0 END
        ) hoje
    FROM ordens_servico
");

if ($res) {
    $row = $res->fetch_assoc() ?: [];
    $resumo['patrimonios'] = (int)($row['patrimonios'] ?? 0);
    $resumo['setores'] = (int)($row['setores'] ?? 0);
    $resumo['hoje'] = (int)($row['hoje'] ?? 0);
    $res->free();
}

$setores = [];

$res = $mysqli->query("
    SELECT setor, COUNT(*) total
    FROM ordens_servico
    WHERE TRIM(COALESCE(setor, '')) <> ''
    GROUP BY setor
    ORDER BY total DESC, setor
    LIMIT 20
");

if ($res) {
    while ($row = $res->fetch_assoc()) {
        $setores[] = (string)$row['setor'];
    }

    $res->free();
}

$tipos = [
    'Computador', 'Notebook', 'Monitor', 'Impressora',
    'Scanner', 'Nobreak', 'Switch', 'Roteador',
    'Telefone IP', 'Projetor', 'Tablet', 'Outro'
];
?>
<!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">
<title>Nova OS | 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@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">

<style>
:root{
    --primary:#08396f;
    --primary-dark:#05294f;
    --primary-light:#145b9f;
    --green:#087f5b;
    --green-soft:#e8f8f1;
    --yellow:#d17a00;
    --yellow-soft:#fff7e6;
    --red:#bd263d;
    --red-soft:#fff0f3;
    --cyan:#087f9c;
    --background:#edf3f8;
    --surface:#fff;
    --surface-soft:#f6f9fc;
    --text:#152236;
    --muted:#617086;
    --light:#8795a8;
    --border:#dce5ee;
    --border-soft:#e9eff5;
    --shadow-sm:0 10px 28px rgba(8,57,111,.06);
    --shadow-md:0 22px 58px rgba(8,57,111,.11);
    --shadow-lg:0 38px 98px rgba(5,41,79,.19);
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{
    margin:0;
    min-height:100vh;
    overflow-x:hidden;
    font-family:"Inter",system-ui,sans-serif;
    color:var(--text);
    background:
        radial-gradient(circle at 7% 5%,rgba(20,91,159,.13),transparent 29rem),
        radial-gradient(circle at 95% 90%,rgba(8,127,91,.09),transparent 31rem),
        linear-gradient(145deg,#f8fbfd,var(--background) 54%,#e7eff6);
}
button,input,select,textarea{font:inherit}
a{text-decoration:none}
.top-strip{
    position:fixed;inset:0 0 auto;z-index:1100;height:6px;
    background:linear-gradient(90deg,var(--primary) 0 58%,var(--green) 58% 88%,#e8ad16 88%);
}
.bg-grid{
    position:fixed;inset:0;z-index:0;pointer-events:none;
    background-image:
        linear-gradient(rgba(8,57,111,.026) 1px,transparent 1px),
        linear-gradient(90deg,rgba(8,57,111,.026) 1px,transparent 1px);
    background-size:54px 54px;
}
.app{position:relative;z-index:2;padding-top:6px}
.header{
    position:relative;overflow:hidden;margin:19px 19px 0;padding:21px 23px;
    border:1px solid rgba(255,255,255,.18);border-radius:28px;color:#fff;
    background:
        radial-gradient(circle at 82% 0,rgba(255,255,255,.13),transparent 23rem),
        radial-gradient(circle at 0 100%,rgba(8,127,91,.26),transparent 25rem),
        linear-gradient(135deg,var(--primary-dark),var(--primary) 56%,#07547c);
    box-shadow:var(--shadow-lg),inset 0 1px 0 rgba(255,255,255,.12);
}
.header:before{
    content:"";position:absolute;top:-215px;right:-115px;width:440px;height:440px;
    border:42px solid rgba(255,255,255,.035);border-radius:50%;
    box-shadow:0 0 0 44px rgba(255,255,255,.018),0 0 0 88px rgba(255,255,255,.012);
    animation:spin 31s linear infinite;
}
@keyframes spin{to{transform:rotate(360deg)}}
.header-content{
    position:relative;z-index:2;display:flex;align-items:center;
    justify-content:space-between;gap:24px;
}
.brand{display:flex;align-items:center;gap:15px;min-width:0}
.logo{
    width:72px;height:72px;flex:0 0 72px;display:grid;place-items:center;padding:5px;
    border-radius:22px;background:linear-gradient(145deg,#fff,#dceaf5);
    box-shadow:0 19px 37px rgba(0,0,0,.18);animation:float 6s ease-in-out infinite;
}
.logo img{max-width:58px;max-height:58px;object-fit:contain}
@keyframes float{50%{transform:translateY(-5px) rotateY(3deg)}}
.gov{
    display:inline-flex;align-items:center;gap:7px;margin-bottom:7px;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:800;letter-spacing:.65px;text-transform:uppercase;
}
.gov i{color:#9cebd2}
.header h1{margin:0;font-size:clamp(22px,2.5vw,35px);font-weight:900;letter-spacing:-1px}
.header p{margin:7px 0 0;color:rgba(255,255,255,.68);font-size:11px}
.header-side{min-width:440px;display:flex;flex-direction:column;align-items:flex-end;gap:11px}
.draft-status{
    display:inline-flex;align-items:center;gap:7px;padding:6px 9px;
    border:1px solid rgba(255,255,255,.14);border-radius:999px;
    color:rgba(255,255,255,.72);background:rgba(255,255,255,.07);
    font-size:8px;font-weight:750;
}
.header-actions{display:flex;justify-content:flex-end;gap:7px;flex-wrap:wrap}
.header-btn{
    min-height:38px;display:inline-flex;align-items:center;justify-content:center;gap:7px;
    padding:0 12px;border:1px solid rgba(255,255,255,.15);border-radius:13px;
    color:#fff;background:rgba(255,255,255,.08);font-size:8px;font-weight:800;
    text-transform:uppercase;transition:.2s;
}
.header-btn:hover{color:#fff;background:rgba(255,255,255,.15);transform:translateY(-2px)}
.header-btn.primary{color:var(--primary-dark);border-color:#fff;background:#fff}
.page{max-width:1740px;margin:auto;padding:17px 19px 34px}
.error{
    display:flex;align-items:center;gap:11px;margin-bottom:14px;padding:13px 15px;
    border:1px solid #efcbd2;border-radius:18px;color:#842037;background:var(--red-soft);
}
.error-icon{
    width:39px;height:39px;display:grid;place-items:center;border-radius:13px;
    color:#fff;background:var(--red);font-size:17px;
}
.error strong{font-size:10px}.error span{display:block;margin-top:3px;font-size:8px}
.hero{
    position:relative;display:grid;grid-template-columns:minmax(0,1.35fr) minmax(300px,.65fr);
    gap:15px;overflow:hidden;padding:22px;border:1px solid rgba(255,255,255,.9);
    border-radius:30px;background:rgba(255,255,255,.85);backdrop-filter:blur(20px);
    box-shadow:var(--shadow-md),inset 0 1px 0 #fff;transform-style:preserve-3d;
    transition:transform .25s ease;
}
.hero-label{
    display:inline-flex;align-items:center;gap:7px;margin-bottom:10px;color:var(--primary);
    font-size:8px;font-weight:850;letter-spacing:.65px;text-transform:uppercase;
}
.hero h2{max-width:900px;margin:0;font-size:clamp(27px,3.1vw,43px);font-weight:900;letter-spacing:-1.7px;line-height:1.04}
.hero h2 span{color:var(--primary)}
.hero p{max-width:850px;margin:12px 0 0;color:var(--muted);font-size:10px;line-height:1.65}
.hero-stats{display:flex;flex-wrap:wrap;gap:7px;margin-top:16px}
.hero-stat{
    display:inline-flex;align-items:center;gap:6px;padding:7px 9px;border:1px solid var(--border);
    border-radius:999px;color:#536378;background:#fff;font-size:7px;font-weight:750;
    box-shadow:var(--shadow-sm);
}
.quality{
    min-height:210px;padding:19px;display:flex;flex-direction:column;justify-content:space-between;
    border-radius:24px;color:#fff;background:linear-gradient(145deg,var(--primary-dark),var(--primary));
    box-shadow:0 23px 47px rgba(8,57,111,.21);transform:translateZ(20px);
}
.quality-top{display:flex;align-items:center;justify-content:space-between;gap:10px}
.quality-label{font-size:8px;font-weight:850;text-transform:uppercase}
.quality-badge{
    padding:6px 8px;border:1px solid rgba(255,255,255,.14);border-radius:999px;
    background:rgba(255,255,255,.08);font-size:7px;font-weight:800;
}
.quality-number{display:flex;align-items:flex-end;gap:3px;margin-top:18px}
.quality-number strong{font-size:50px;line-height:.9;letter-spacing:-2px}
.quality-number span{color:rgba(255,255,255,.65);font-size:14px;font-weight:700}
.quality p{margin:8px 0 0;color:rgba(255,255,255,.65);font-size:8px}
.quality-track{height:8px;overflow:hidden;margin-top:16px;border-radius:999px;background:rgba(255,255,255,.13)}
.quality-track span{display:block;height:100%;background:linear-gradient(90deg,#91ebcf,#fff);transition:.35s}
.layout{display:grid;grid-template-columns:310px minmax(0,1fr);gap:14px;margin-top:14px}
.panel{
    border:1px solid rgba(255,255,255,.9);border-radius:30px;background:rgba(255,255,255,.92);
    backdrop-filter:blur(18px);box-shadow:var(--shadow-md),inset 0 1px 0 #fff;
}
.sticky{position:sticky;top:17px;align-self:start;overflow:hidden}
.panel-head{
    padding:18px 19px;border-bottom:1px solid var(--border-soft);
    background:linear-gradient(180deg,#fff,#f9fbfd);
}
.panel-head h2{margin:0;font-size:14px;font-weight:850}
.panel-head p{margin:4px 0 0;color:var(--muted);font-size:8px}
.steps{display:flex;flex-direction:column;gap:8px;padding:14px}
.step{
    display:flex;align-items:center;gap:10px;width:100%;padding:10px;
    border:1px solid var(--border-soft);border-radius:15px;color:var(--muted);
    background:var(--surface-soft);cursor:pointer;text-align:left;transition:.18s;
}
.step:hover{border-color:#c7d6e3;background:#fff;transform:translateX(2px)}
.step.active{color:#fff;border-color:var(--primary);background:linear-gradient(145deg,var(--primary-dark),var(--primary));box-shadow:0 13px 27px rgba(8,57,111,.21)}
.step.completed{border-color:#c3e9dc;background:var(--green-soft)}
.step-icon{
    width:36px;height:36px;flex:0 0 36px;display:grid;place-items:center;
    border-radius:12px;color:var(--primary);background:#eaf4fc;font-size:15px;
}
.step.active .step-icon{color:#fff;background:rgba(255,255,255,.14)}
.step.completed .step-icon{color:var(--green);background:#fff}
.step strong{display:block;font-size:8px;font-weight:850;text-transform:uppercase}
.step small{display:block;margin-top:3px;font-size:7px;opacity:.75}
.step-check{margin-left:auto;color:var(--green)}
.step.active .step-check{color:#fff}
.progress-area{padding:0 14px 14px}
.progress-meta{display:flex;justify-content:space-between;margin-bottom:7px;color:var(--light);font-size:7px}
.progress-track{height:7px;overflow:hidden;border-radius:999px;background:#e5edf4}
.progress-fill{height:100%;width:0;border-radius:inherit;background:linear-gradient(90deg,var(--primary),var(--cyan),var(--green));transition:.35s}
.help{
    margin:0 14px 14px;padding:12px;border:1px solid #cfe0ee;border-radius:14px;
    color:#31546f;background:#edf7fc;font-size:7px;line-height:1.55;
}
.help strong{display:block;margin-bottom:4px;color:var(--primary);font-size:8px}
.draft-actions{display:grid;grid-template-columns:1fr 1fr;gap:7px;padding:0 14px 14px}
.draft-btn{
    min-height:36px;border:1px solid var(--border);border-radius:11px;color:var(--muted);
    background:#fff;font-size:7px;font-weight:800;
}
.form-panel{overflow:hidden}
.form-head{
    display:flex;align-items:center;justify-content:space-between;gap:12px;padding:18px 20px;
    border-bottom:1px solid var(--border-soft);background:linear-gradient(180deg,#fff,#f9fbfd);
}
.form-title{display:flex;align-items:center;gap:10px}
.form-title-icon{
    width:40px;height:40px;display:grid;place-items:center;border-radius:13px;color:#fff;
    background:linear-gradient(145deg,var(--primary),var(--primary-light));font-size:16px;
}
.form-head h2{margin:0;font-size:14px;font-weight:850}
.form-head p{margin:4px 0 0;color:var(--muted);font-size:8px}
.step-counter{
    padding:7px 9px;border:1px solid var(--border);border-radius:999px;color:var(--primary);
    background:#fff;font-size:7px;font-weight:800;
}
.form-body{min-height:520px;padding:20px}
.step-content{animation:stepin .28s ease}
@keyframes stepin{from{opacity:0;transform:translateY(7px)}to{opacity:1;transform:none}}
.intro{
    display:flex;align-items:flex-start;gap:11px;margin-bottom:17px;padding:12px;
    border:1px solid var(--border-soft);border-radius:15px;background:var(--surface-soft);
}
.intro-icon{
    width:38px;height:38px;flex:0 0 38px;display:grid;place-items:center;
    border-radius:12px;color:var(--primary);background:#eaf4fc;font-size:16px;
}
.intro strong{display:block;font-size:9px;font-weight:850}
.intro span{display:block;margin-top:4px;color:var(--light);font-size:7px}
.form-group{margin-bottom:13px}
.form-label{
    display:flex;align-items:center;gap:5px;margin-bottom:6px;color:#516176;
    font-size:8px;font-weight:850;letter-spacing:.45px;text-transform:uppercase;
}
.required{color:var(--red)}
.input-wrap{position:relative}
.input-wrap>i{
    position:absolute;top:50%;left:13px;z-index:2;color:var(--primary);
    font-size:14px;transform:translateY(-50%);pointer-events:none;
}
.form-control,.form-select{
    min-height:48px;border:1px solid var(--border);border-radius:14px;color:var(--text);
    background:var(--surface-soft);font-size:10px;font-weight:650;box-shadow:none;
}
.input-wrap .form-control,.input-wrap .form-select{padding-left:38px}
textarea.form-control{min-height:155px;padding-top:12px;resize:vertical}
.form-control:focus,.form-select:focus{
    border-color:var(--primary-light);background:#fff;
    box-shadow:0 0 0 4px rgba(20,91,159,.1);
}
.form-control.is-invalid,.form-select.is-invalid{
    border-color:var(--red);background-image:none;box-shadow:0 0 0 4px rgba(189,38,61,.08);
}
.note{display:flex;gap:5px;margin-top:6px;color:var(--light);font-size:7px}
.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
.chip{
    min-height:31px;padding:0 9px;border:1px solid var(--border);border-radius:999px;
    color:var(--muted);background:#fff;font-size:7px;font-weight:750;
}
.chip:hover{color:var(--primary);border-color:#c3d4e2}
.autocomplete{
    position:absolute;top:calc(100% + 7px);right:0;left:0;z-index:1000;
    max-height:260px;overflow:auto;border:1px solid var(--border);border-radius:15px;
    background:#fff;box-shadow:0 20px 48px rgba(8,57,111,.17);
}
.auto-item{
    display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:10px 12px;border-bottom:1px solid var(--border-soft);cursor:pointer;
}
.auto-item:hover,.auto-item.active{background:#eef6fc}
.auto-main{color:var(--text);font-size:8px;font-weight:800}
.auto-meta{color:var(--light);font-size:6px}
.asset-info{
    display:none;margin-top:10px;padding:12px;border:1px solid #c3e9dc;
    border-radius:14px;color:#076448;background:var(--green-soft);font-size:8px;
}
.asset-info.visible{display:block}
.asset-info.warning{color:#916000;border-color:#edd9aa;background:var(--yellow-soft)}
.advisor{
    display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:10px;
    margin-top:10px;padding:11px;border:1px solid var(--border);border-radius:14px;
    background:var(--surface-soft);
}
.advisor-icon{
    width:36px;height:36px;display:grid;place-items:center;border-radius:12px;
    color:var(--primary);background:#eaf4fc;font-size:15px;
}
.advisor strong{display:block;font-size:8px}.advisor span{display:block;margin-top:3px;color:var(--light);font-size:7px}
.advisor-badge{padding:6px 8px;border-radius:999px;color:var(--primary);background:#eaf4fc;font-size:7px;font-weight:850}
.advisor-badge.Alta{color:#916000;background:var(--yellow-soft)}
.advisor-badge.Urgente{color:#922138;background:var(--red-soft)}
.file-zone{
    position:relative;min-height:116px;display:flex;align-items:center;justify-content:center;
    padding:17px;border:2px dashed #c9d7e3;border-radius:16px;text-align:center;
    background:var(--surface-soft);cursor:pointer;transition:.2s;
}
.file-zone:hover,.file-zone.drag{border-color:var(--primary-light);background:#edf7fc;transform:translateY(-2px)}
.file-zone input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}
.file-zone i{display:block;margin-bottom:7px;color:var(--primary);font-size:26px}
.file-zone strong{display:block;font-size:9px}.file-zone span{display:block;margin-top:4px;color:var(--light);font-size:7px}
.file-preview{
    display:none;align-items:center;justify-content:space-between;gap:10px;margin-top:9px;
    padding:10px;border:1px solid var(--border);border-radius:13px;background:#fff;
}
.file-preview.visible{display:flex}
.file-info{display:flex;align-items:center;gap:9px;min-width:0}
.file-icon{
    width:34px;height:34px;display:grid;place-items:center;border-radius:11px;
    color:var(--primary);background:#eaf4fc;
}
.file-info strong{display:block;overflow:hidden;font-size:8px;text-overflow:ellipsis;white-space:nowrap}
.file-info small{display:block;color:var(--light);font-size:6px}
.remove-file{
    width:30px;height:30px;border:1px solid var(--border);border-radius:10px;
    color:var(--red);background:#fff;
}
.summary{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}
.summary-card{
    min-height:82px;padding:11px;border:1px solid var(--border);border-radius:14px;
    background:var(--surface-soft);
}
.summary-card.wide{grid-column:1/-1}
.summary-card span{display:block;color:var(--light);font-size:6px;font-weight:850;text-transform:uppercase}
.summary-card strong{display:block;margin-top:7px;font-size:9px;line-height:1.45;word-break:break-word}
.confirm{
    display:flex;gap:10px;margin-top:12px;padding:12px;border:1px solid #c3e9dc;
    border-radius:14px;color:#076448;background:var(--green-soft);
}
.confirm strong{display:block;font-size:8px}.confirm span{display:block;margin-top:3px;font-size:7px}
.form-actions{
    display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:14px 18px;border-top:1px solid var(--border-soft);background:#f9fbfd;
}
.action-group{display:flex;gap:8px}
.action{
    min-height:43px;display:inline-flex;align-items:center;justify-content:center;gap:7px;
    padding:0 14px;border:1px solid var(--border);border-radius:13px;
    color:var(--muted);background:#fff;font-size:8px;font-weight:850;text-transform:uppercase;
}
.action.primary{color:#fff;border-color:var(--primary);background:linear-gradient(145deg,var(--primary-dark),var(--primary))}
.action.success{color:#fff;border-color:var(--green);background:linear-gradient(145deg,#07694b,var(--green))}
.footer{
    display:flex;justify-content:space-between;gap:15px;margin-top:14px;padding:13px 16px;
    border:1px solid rgba(255,255,255,.9);border-radius:17px;color:var(--light);
    background:rgba(255,255,255,.72);font-size:7px;
}
@media(max-width:1100px){
    .header{margin:13px 11px 0}.header-content{align-items:flex-start;flex-direction:column}
    .header-side{width:100%;min-width:0;align-items:flex-start}.header-actions{justify-content:flex-start}
    .page{padding:14px 11px 28px}.hero{grid-template-columns:1fr}.layout{grid-template-columns:1fr}
    .sticky{position:static}.steps{display:grid;grid-template-columns:repeat(4,1fr)}
    .step{flex-direction:column;align-items:flex-start;position:relative}.step-check{position:absolute;top:8px;right:8px}
}
@media(max-width:760px){
    .header-actions{display:grid;grid-template-columns:repeat(2,1fr);width:100%}.header-btn{width:100%}
    .steps{grid-template-columns:repeat(2,1fr)}.summary{grid-template-columns:1fr}.summary-card.wide{grid-column:auto}
    .form-actions{align-items:stretch;flex-direction:column}.action-group{width:100%}.action{flex:1}
}
@media(max-width:540px){
    .header{margin:7px;padding:15px;border-radius:21px}.page{padding:12px 7px 28px}
    .hero{padding:17px;border-radius:23px}.hero h2{font-size:28px}.form-body{min-height:0;padding:15px}
    .step small{display:none}.footer{flex-direction:column}
}
@media(prefers-reduced-motion:reduce){
    *,*:before,*:after{animation-duration:.01ms!important;transition-duration:.01ms!important}
}
</style>
</head>

<body>
<div class="top-strip"></div>
<div class="bg-grid"></div>

<div class="app">

<header class="header">
    <div class="header-content">

        <div class="brand">
            <div class="logo">
                <img
                    src="assets/logo_pref.jpg"
                    alt="Prefeitura de Extrema"
                    onerror="this.style.display='none';this.parentElement.innerHTML='<i class=&quot;bi bi-buildings-fill text-primary fs-3&quot;></i>'"
                >
            </div>

            <div>
                <div class="gov">
                    <i class="bi bi-shield-check"></i>
                    Prefeitura de Extrema • Gerência de Tecnologia
                </div>

                <h1>Nova Ordem de Serviço</h1>

                <p>
                    Cadastro guiado, inteligente e rastreável para manutenção de equipamentos.
                </p>
            </div>
        </div>

        <div class="header-side">
            <div class="draft-status" id="draftStatus">
                <i class="bi bi-cloud-check-fill"></i>
                Rascunho automático ativado
            </div>

            <nav class="header-actions">
                <a href="listar_os.php" class="header-btn primary">
                    <i class="bi bi-arrow-left-circle-fill"></i>
                    Ordens de serviço
                </a>

                <a href="dashboard.php" class="header-btn">
                    <i class="bi bi-grid-1x2-fill"></i>
                    Dashboard
                </a>

                <a href="inteligencia.php" class="header-btn">
                    <i class="bi bi-cpu-fill"></i>
                    Inteligência
                </a>
            </nav>
        </div>

    </div>
</header>

<main class="page">

<?php if ($erro !== ''): ?>
    <div class="error">
        <div class="error-icon">
            <i class="bi bi-exclamation-triangle-fill"></i>
        </div>

        <div>
            <strong>Não foi possível cadastrar a ordem.</strong>
            <span><?= e($erro) ?></span>
        </div>
    </div>
<?php endif; ?>

<section class="hero" id="hero">
    <div>
        <div class="hero-label">
            <i class="bi bi-clipboard2-plus-fill"></i>
            Assistente de cadastro técnico
        </div>

        <h2>
            Registre uma demanda com
            <span>clareza, contexto e prioridade correta.</span>
        </h2>

        <p>
            A pesquisa de patrimônio recupera dados anteriores, a descrição auxilia na
            sugestão de prioridade e a revisão final reduz erros antes da criação da OS.
        </p>

        <div class="hero-stats">
            <span class="hero-stat">
                <i class="bi bi-upc-scan"></i>
                <?= $resumo['patrimonios'] ?> patrimônios conhecidos
            </span>

            <span class="hero-stat">
                <i class="bi bi-buildings-fill"></i>
                <?= $resumo['setores'] ?> setores registrados
            </span>

            <span class="hero-stat">
                <i class="bi bi-calendar-check-fill"></i>
                <?= $resumo['hoje'] ?> OS criada(s) hoje
            </span>

            <span class="hero-stat">
                <i class="bi bi-paperclip"></i>
                Anexos de até 8 MB
            </span>
        </div>
    </div>

    <aside class="quality">
        <div class="quality-top">
            <span class="quality-label">
                <i class="bi bi-check2-circle me-1"></i>
                Qualidade do cadastro
            </span>

            <span class="quality-badge" id="qualityBadge">Iniciando</span>
        </div>

        <div>
            <div class="quality-number">
                <strong id="qualityNumber">0</strong>
                <span>%</span>
            </div>

            <p id="qualityText">
                Preencha os campos para aumentar a precisão da triagem.
            </p>

            <div class="quality-track">
                <span id="qualityProgress" style="width:0"></span>
            </div>
        </div>
    </aside>
</section>

<div class="layout">

    <aside class="panel sticky">
        <div class="panel-head">
            <h2>Etapas do cadastro</h2>
            <p>Avance após preencher os campos obrigatórios.</p>
        </div>

        <div class="steps">
            <?php
            $etapas = [
                1 => ['bi-person-fill', 'Solicitante', 'Contato e setor'],
                2 => ['bi-pc-display-horizontal', 'Equipamento', 'Patrimônio e identificação'],
                3 => ['bi-tools', 'Problema', 'Descrição e prioridade'],
                4 => ['bi-check2-circle', 'Revisão', 'Conferência final']
            ];

            foreach ($etapas as $numero => $dados):
            ?>
                <button
                    type="button"
                    class="step <?= $numero === 1 ? 'active' : '' ?>"
                    data-step-indicator="<?= $numero ?>"
                >
                    <span class="step-icon">
                        <i class="bi <?= e($dados[0]) ?>"></i>
                    </span>

                    <span>
                        <strong><?= e($dados[1]) ?></strong>
                        <small><?= e($dados[2]) ?></small>
                    </span>

                    <i class="bi bi-check-circle-fill step-check d-none"></i>
                </button>
            <?php endforeach; ?>
        </div>

        <div class="progress-area">
            <div class="progress-meta">
                <span>Progresso</span>
                <strong id="progressText">Etapa 1 de 4</strong>
            </div>

            <div class="progress-track">
                <div class="progress-fill" id="stepProgress"></div>
            </div>
        </div>

        <div class="help" id="helpBox">
            <strong>
                <i class="bi bi-lightbulb-fill me-1"></i>
                Dica desta etapa
            </strong>

            Use o nome completo e informe um telefone ou ramal válido.
        </div>

        <div class="draft-actions">
            <button type="button" class="draft-btn" id="saveDraft">
                <i class="bi bi-cloud-arrow-up-fill me-1"></i>
                Salvar
            </button>

            <button type="button" class="draft-btn" id="clearDraft">
                <i class="bi bi-trash3-fill me-1"></i>
                Limpar
            </button>
        </div>
    </aside>

    <section class="panel form-panel">
        <div class="form-head">
            <div class="form-title">
                <div class="form-title-icon" id="titleIcon">
                    <i class="bi bi-person-fill"></i>
                </div>

                <div>
                    <h2 id="formTitle">Dados do solicitante</h2>
                    <p id="formSubtitle">Identifique quem está solicitando o atendimento.</p>
                </div>
            </div>

            <span class="step-counter" id="stepCounter">Etapa 1 de 4</span>
        </div>

        <form method="POST" enctype="multipart/form-data" id="osForm" novalidate>
            <input type="hidden" name="csrf_token" value="<?= e($csrf) ?>">

            <div class="form-body">

                <!-- ETAPA 1 -->
                <section class="step-content" data-step="1">
                    <div class="intro">
                        <div class="intro-icon">
                            <i class="bi bi-person-lines-fill"></i>
                        </div>

                        <div>
                            <strong>Quem precisa do atendimento?</strong>
                            <span>
                                Informe os dados que permitirão contato durante o atendimento
                                e na devolução do equipamento.
                            </span>
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label" for="nome">
                                    Nome do solicitante
                                    <span class="required">*</span>
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-person-fill"></i>

                                    <input
                                        type="text"
                                        name="nome_solicitante"
                                        id="nome"
                                        class="form-control"
                                        value="<?= e(post('nome_solicitante')) ?>"
                                        placeholder="Nome completo"
                                        maxlength="150"
                                        required
                                    >
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label" for="setor">
                                    Setor ou secretaria
                                    <span class="required">*</span>
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-buildings-fill"></i>

                                    <input
                                        type="text"
                                        name="setor"
                                        id="setor"
                                        class="form-control"
                                        list="setoresList"
                                        value="<?= e(post('setor')) ?>"
                                        placeholder="Ex.: Secretaria de Saúde"
                                        maxlength="150"
                                        required
                                    >
                                </div>

                                <datalist id="setoresList">
                                    <?php foreach ($setores as $item): ?>
                                        <option value="<?= e($item) ?>">
                                    <?php endforeach; ?>
                                </datalist>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label" for="email">
                                    E-mail institucional
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-envelope-fill"></i>

                                    <input
                                        type="email"
                                        name="email"
                                        id="email"
                                        class="form-control"
                                        value="<?= e(post('email')) ?>"
                                        placeholder="usuario@extrema.mg.gov.br"
                                        maxlength="180"
                                    >
                                </div>

                                <div class="note">
                                    <i class="bi bi-info-circle-fill"></i>
                                    <?= $temEmail
                                        ? 'O e-mail será armazenado na OS.'
                                        : 'A tabela não possui a coluna email; o dado ficará somente na revisão.' ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label" for="telefone">
                                    Telefone ou ramal
                                    <span class="required">*</span>
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-telephone-fill"></i>

                                    <input
                                        type="text"
                                        name="telefone"
                                        id="telefone"
                                        class="form-control"
                                        value="<?= e(post('telefone')) ?>"
                                        placeholder="Ex.: 3535-0000 / Ramal 123"
                                        maxlength="80"
                                        required
                                    >
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- ETAPA 2 -->
                <section class="step-content d-none" data-step="2">
                    <div class="intro">
                        <div class="intro-icon">
                            <i class="bi bi-upc-scan"></i>
                        </div>

                        <div>
                            <strong>Identifique o equipamento</strong>
                            <span>
                                Digite o patrimônio para pesquisar atendimentos anteriores e
                                preencher os dados automaticamente.
                            </span>
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-5">
                            <div class="form-group position-relative">
                                <label class="form-label" for="patrimonio">
                                    Patrimônio
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-upc-scan"></i>

                                    <input
                                        type="text"
                                        name="patrimonio"
                                        id="patrimonio"
                                        class="form-control"
                                        value="<?= e(post('patrimonio')) ?>"
                                        placeholder="Digite para pesquisar"
                                        maxlength="100"
                                        autocomplete="off"
                                    >
                                </div>

                                <div id="patList" class="autocomplete d-none"></div>
                            </div>
                        </div>

                        <div class="col-md-7">
                            <div class="form-group">
                                <label class="form-label" for="tipo">
                                    Tipo de equipamento
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-pc-display"></i>

                                    <input
                                        type="text"
                                        name="tipo_equipamento"
                                        id="tipo"
                                        class="form-control"
                                        list="tiposList"
                                        value="<?= e(post('tipo_equipamento')) ?>"
                                        placeholder="Computador, notebook, impressora..."
                                        maxlength="120"
                                    >
                                </div>

                                <datalist id="tiposList">
                                    <?php foreach ($tipos as $item): ?>
                                        <option value="<?= e($item) ?>">
                                    <?php endforeach; ?>
                                </datalist>

                                <div class="chips">
                                    <?php foreach (array_slice($tipos, 0, 7) as $item): ?>
                                        <button
                                            type="button"
                                            class="chip"
                                            data-fill="tipo"
                                            data-value="<?= e($item) ?>"
                                        >
                                            <?= e($item) ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="marca">Marca</label>

                                <div class="input-wrap">
                                    <i class="bi bi-tag-fill"></i>

                                    <input
                                        type="text"
                                        name="marca"
                                        id="marca"
                                        class="form-control"
                                        value="<?= e(post('marca')) ?>"
                                        placeholder="Dell, HP, Lenovo..."
                                        maxlength="120"
                                    >
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="modelo">Modelo</label>

                                <div class="input-wrap">
                                    <i class="bi bi-box-fill"></i>

                                    <input
                                        type="text"
                                        name="modelo"
                                        id="modelo"
                                        class="form-control"
                                        value="<?= e(post('modelo')) ?>"
                                        placeholder="Modelo do equipamento"
                                        maxlength="120"
                                    >
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="serie">
                                    Número de série
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-qr-code"></i>

                                    <input
                                        type="text"
                                        name="numero_serie"
                                        id="serie"
                                        class="form-control"
                                        value="<?= e(post('numero_serie')) ?>"
                                        placeholder="Número de série"
                                        maxlength="150"
                                    >
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="assetInfo" class="asset-info"></div>
                </section>

                <!-- ETAPA 3 -->
                <section class="step-content d-none" data-step="3">
                    <div class="intro">
                        <div class="intro-icon">
                            <i class="bi bi-tools"></i>
                        </div>

                        <div>
                            <strong>Descreva sintomas, impacto e urgência</strong>
                            <span>
                                Uma descrição detalhada melhora a triagem e reduz contatos
                                adicionais para esclarecimentos.
                            </span>
                        </div>
                    </div>

                    <div class="row g-3">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="prioridade">
                                    Prioridade
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-flag-fill"></i>

                                    <select
                                        name="prioridade"
                                        id="prioridade"
                                        class="form-select"
                                    >
                                        <?php
                                        $priorAtual = post('prioridade', 'Média');

                                        foreach (['Baixa', 'Média', 'Alta', 'Urgente'] as $p):
                                        ?>
                                            <option
                                                value="<?= e($p) ?>"
                                                <?= $priorAtual === $p ? 'selected' : '' ?>
                                            >
                                                <?= e($p) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="prazo">
                                    Prazo em dias
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-calendar-event-fill"></i>

                                    <input
                                        type="number"
                                        name="prazo"
                                        id="prazo"
                                        class="form-control"
                                        value="<?= e(post('prazo', '5')) ?>"
                                        min="1"
                                        max="365"
                                        required
                                    >
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="form-label" for="quantidade">
                                    Quantidade de equipamentos
                                </label>

                                <div class="input-wrap">
                                    <i class="bi bi-123"></i>

                                    <input
                                        type="number"
                                        name="quantidade"
                                        id="quantidade"
                                        class="form-control"
                                        value="<?= e(post('quantidade', '1')) ?>"
                                        min="1"
                                        max="50"
                                        required
                                    >
                                </div>

                                <div class="note">
                                    <i class="bi bi-info-circle-fill"></i>
                                    Cada equipamento gerará uma OS independente.
                                </div>
                            </div>
                        </div>

                        <div class="col-12">
                            <div class="form-group">
                                <label class="form-label" for="problema">
                                    Descrição detalhada
                                    <span class="required">*</span>
                                </label>

                                <textarea
                                    name="problema"
                                    id="problema"
                                    class="form-control"
                                    placeholder="Explique o defeito, sintomas, mensagens, quando começou e o impacto no setor..."
                                    minlength="10"
                                    maxlength="4000"
                                    required
                                ><?= e(post('problema')) ?></textarea>

                                <div class="chips">
                                    <button type="button" class="chip" data-template="O equipamento não liga e não apresenta sinais de energia.">
                                        Não liga
                                    </button>

                                    <button type="button" class="chip" data-template="O equipamento apresenta lentidão e trava durante o uso.">
                                        Lentidão
                                    </button>

                                    <button type="button" class="chip" data-template="O setor está sem acesso à rede e à internet.">
                                        Rede/Internet
                                    </button>

                                    <button type="button" class="chip" data-template="A impressora está parada e não conclui os trabalhos enviados.">
                                        Impressora
                                    </button>

                                    <button type="button" class="chip" data-template="O sistema apresenta mensagem de erro durante a operação.">
                                        Erro de sistema
                                    </button>
                                </div>

                                <div class="advisor">
                                    <div class="advisor-icon">
                                        <i class="bi bi-cpu-fill"></i>
                                    </div>

                                    <div>
                                        <strong>Análise automática</strong>
                                        <span id="advisorText">
                                            Digite a descrição para receber uma sugestão.
                                        </span>
                                    </div>

                                    <span id="advisorBadge" class="advisor-badge">
                                        Média
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="col-12">
                            <label class="form-label">Anexo ou evidência</label>

                            <label class="file-zone" id="fileZone">
                                <input
                                    type="file"
                                    name="anexo"
                                    id="anexo"
                                    accept=".png,.jpg,.jpeg,.pdf,image/png,image/jpeg,application/pdf"
                                >

                                <span>
                                    <i class="bi bi-cloud-arrow-up-fill"></i>
                                    <strong>Clique ou arraste o arquivo</strong>
                                    <span>PNG, JPG, JPEG ou PDF com até 8 MB</span>
                                </span>
                            </label>

                            <div class="file-preview" id="filePreview">
                                <div class="file-info">
                                    <div class="file-icon">
                                        <i class="bi bi-paperclip"></i>
                                    </div>

                                    <div style="min-width:0">
                                        <strong id="fileName"></strong>
                                        <small id="fileSize"></small>
                                    </div>
                                </div>

                                <button
                                    type="button"
                                    class="remove-file"
                                    id="removeFile"
                                >
                                    <i class="bi bi-x-lg"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- ETAPA 4 -->
                <section class="step-content d-none" data-step="4">
                    <div class="intro">
                        <div class="intro-icon">
                            <i class="bi bi-clipboard2-check-fill"></i>
                        </div>

                        <div>
                            <strong>Confira antes de cadastrar</strong>
                            <span>
                                Volte às etapas anteriores para corrigir qualquer informação.
                            </span>
                        </div>
                    </div>

                    <div class="summary">
                        <?php
                        $summary = [
                            ['bi-person-fill', 'Solicitante', 'sumNome'],
                            ['bi-buildings-fill', 'Setor', 'sumSetor'],
                            ['bi-telephone-fill', 'Contato', 'sumContato'],
                            ['bi-envelope-fill', 'E-mail', 'sumEmail'],
                            ['bi-pc-display', 'Equipamento', 'sumEquip'],
                            ['bi-upc-scan', 'Patrimônio', 'sumPat'],
                            ['bi-flag-fill', 'Prioridade e prazo', 'sumPrior'],
                            ['bi-123', 'Quantidade', 'sumQtd'],
                            ['bi-paperclip', 'Anexo', 'sumAnexo'],
                            ['bi-qr-code', 'Número de série', 'sumSerie']
                        ];

                        foreach ($summary as $item):
                        ?>
                            <div class="summary-card">
                                <span>
                                    <i class="bi <?= e($item[0]) ?> me-1"></i>
                                    <?= e($item[1]) ?>
                                </span>

                                <strong id="<?= e($item[2]) ?>">—</strong>
                            </div>
                        <?php endforeach; ?>

                        <div class="summary-card wide">
                            <span>
                                <i class="bi bi-card-text me-1"></i>
                                Descrição do problema
                            </span>

                            <strong id="sumProblema">—</strong>
                        </div>
                    </div>

                    <div class="confirm">
                        <i class="bi bi-shield-check fs-5"></i>

                        <div>
                            <strong>Cadastro protegido por transação</strong>
                            <span>
                                Caso uma das inserções falhe, nenhuma OS do lote será
                                gravada parcialmente.
                            </span>
                        </div>
                    </div>
                </section>

            </div>

            <div class="form-actions">
                <div class="action-group">
                    <button type="button" class="action d-none" id="backBtn">
                        <i class="bi bi-arrow-left"></i>
                        Voltar
                    </button>
                </div>

                <div class="action-group">
                    <button type="button" class="action" id="cancelBtn">
                        <i class="bi bi-x-circle"></i>
                        Cancelar
                    </button>

                    <button type="button" class="action primary" id="nextBtn">
                        Avançar
                        <i class="bi bi-arrow-right"></i>
                    </button>

                    <button type="submit" class="action success d-none" id="submitBtn">
                        <i class="bi bi-check-circle-fill"></i>
                        Cadastrar OS
                    </button>
                </div>
            </div>
        </form>
    </section>

</div>

<footer class="footer">
    <span>
        Prefeitura de Extrema — Gerência de Tecnologia<br>
        Cadastro institucional de ordens de serviço.
    </span>

    <span>
        <i class="bi bi-shield-lock-fill me-1 text-primary"></i>
        Sessão protegida e validação ativa
    </span>
</footer>

</main>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
(() => {
    'use strict';

    const $ = id => document.getElementById(id);
    const form = $('osForm');

    const contents = [...document.querySelectorAll('.step-content')];
    const indicators = [...document.querySelectorAll('[data-step-indicator]')];

    const titles = {
        1: ['Dados do solicitante', 'Identifique quem está solicitando o atendimento.', 'bi-person-fill',
            'Use o nome completo e informe um telefone ou ramal válido.'],
        2: ['Identificação do equipamento', 'Pesquise o patrimônio e confira os dados técnicos.', 'bi-pc-display-horizontal',
            'Ao escolher um patrimônio conhecido, os dados anteriores serão recuperados.'],
        3: ['Detalhamento técnico', 'Descreva sintomas, impacto, prioridade e prazo.', 'bi-tools',
            'Informe quando começou, mensagens exibidas e impacto no setor.'],
        4: ['Revisão e confirmação', 'Confira todas as informações antes de cadastrar.', 'bi-clipboard2-check-fill',
            'Revise patrimônio, prioridade, prazo, quantidade e descrição.']
    };

    let current = 1;
    let highest = 1;
    let sending = false;

    function value(id, fallback = 'Não informado') {
        const v = String($(id)?.value ?? '').trim();
        return v || fallback;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = String(text ?? '');
        return div.innerHTML;
    }

    function bytes(size) {
        return size < 1024 * 1024
            ? `${(size / 1024).toFixed(1)} KB`
            : `${(size / 1024 / 1024).toFixed(2)} MB`;
    }

    function showStep(step) {
        current = Math.max(1, Math.min(4, step));
        highest = Math.max(highest, current);

        contents.forEach(content => {
            content.classList.toggle(
                'd-none',
                Number(content.dataset.step) !== current
            );
        });

        indicators.forEach(indicator => {
            const n = Number(indicator.dataset.stepIndicator);
            const complete = n < current;

            indicator.classList.toggle('active', n === current);
            indicator.classList.toggle('completed', complete);
            indicator.querySelector('.step-check')
                ?.classList.toggle('d-none', !complete);
        });

        $('stepProgress').style.width =
            `${((current - 1) / 3) * 100}%`;

        $('progressText').textContent = `Etapa ${current} de 4`;
        $('stepCounter').textContent = `Etapa ${current} de 4`;

        $('formTitle').textContent = titles[current][0];
        $('formSubtitle').textContent = titles[current][1];
        $('titleIcon').innerHTML =
            `<i class="bi ${titles[current][2]}"></i>`;

        $('helpBox').innerHTML = `
            <strong>
                <i class="bi bi-lightbulb-fill me-1"></i>
                Dica desta etapa
            </strong>
            ${titles[current][3]}
        `;

        $('backBtn').classList.toggle('d-none', current === 1);
        $('nextBtn').classList.toggle('d-none', current === 4);
        $('submitBtn').classList.toggle('d-none', current !== 4);

        if (current === 4) {
            updateSummary();
        }

        document.querySelector('.layout').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }

    function validateStep(step) {
        const section = contents.find(
            c => Number(c.dataset.step) === step
        );

        const required = [...section.querySelectorAll('[required]')];
        let valid = true;
        let first = null;

        required.forEach(input => {
            const text = String(input.value ?? '').trim();

            let invalid =
                text === '' ||
                !input.checkValidity() ||
                (input.id === 'problema' && text.length < 10);

            input.classList.toggle('is-invalid', invalid);

            if (invalid && !first) {
                first = input;
            }

            if (invalid) {
                valid = false;
            }
        });

        first?.focus();
        return valid;
    }

    $('nextBtn').addEventListener('click', () => {
        if (validateStep(current)) {
            showStep(current + 1);
        }
    });

    $('backBtn').addEventListener('click', () => {
        showStep(current - 1);
    });

    indicators.forEach(indicator => {
        indicator.addEventListener('click', () => {
            const target = Number(indicator.dataset.stepIndicator);

            if (target <= highest) {
                if (target > current && !validateStep(current)) {
                    return;
                }

                showStep(target);
            }
        });
    });

    /* Qualidade */
    const qualityWeights = {
        nome: 12,
        setor: 10,
        telefone: 10,
        email: 5,
        patrimonio: 12,
        tipo: 10,
        marca: 6,
        modelo: 6,
        serie: 5,
        problema: 19
    };

    function quality() {
        let score = 0;

        Object.entries(qualityWeights).forEach(([id, points]) => {
            const text = String($(id)?.value ?? '').trim();

            if (!text) {
                return;
            }

            if (id === 'problema') {
                score += Math.round(
                    points * Math.min(1, text.length / 120)
                );
            } else {
                score += points;
            }
        });

        if ($('anexo').files[0]) {
            score += 5;
        }

        score = Math.min(100, score);

        $('qualityNumber').textContent = score;
        $('qualityProgress').style.width = `${score}%`;

        if (score >= 85) {
            $('qualityBadge').textContent = 'Excelente';
            $('qualityText').textContent =
                'Cadastro completo e adequado para uma triagem precisa.';
        } else if (score >= 65) {
            $('qualityBadge').textContent = 'Bom';
            $('qualityText').textContent =
                'O cadastro está consistente, mas pode receber mais detalhes.';
        } else if (score >= 40) {
            $('qualityBadge').textContent = 'Em progresso';
            $('qualityText').textContent =
                'Continue preenchendo os dados do equipamento e do problema.';
        } else {
            $('qualityBadge').textContent = 'Iniciando';
            $('qualityText').textContent =
                'Preencha os campos para aumentar a precisão da triagem.';
        }
    }

    form.addEventListener('input', quality);
    form.addEventListener('change', quality);

    /* Chips */
    document.querySelectorAll('[data-fill]').forEach(btn => {
        btn.addEventListener('click', () => {
            $(btn.dataset.fill).value = btn.dataset.value || '';
            $(btn.dataset.fill).dispatchEvent(
                new Event('input', { bubbles: true })
            );
        });
    });

    document.querySelectorAll('[data-template]').forEach(btn => {
        btn.addEventListener('click', () => {
            const currentText = $('problema').value.trim();
            const template = btn.dataset.template || '';

            $('problema').value = currentText
                ? `${currentText}\n${template}`
                : template;

            $('problema').dispatchEvent(
                new Event('input', { bubbles: true })
            );
            $('problema').focus();
        });
    });

    /* Prioridade */
    let priorityTimer = null;
    let manualPriority = false;

    function advisor(priority, reason) {
        $('advisorBadge').textContent = priority;
        $('advisorBadge').className =
            `advisor-badge ${priority}`;
        $('advisorText').textContent = reason;
    }

    $('prioridade').addEventListener('change', () => {
        manualPriority = true;

        const prazo = {
            Urgente: 1,
            Alta: 2,
            Média: 5,
            Baixa: 7
        };

        $('prazo').value = prazo[$('prioridade').value] || 5;

        advisor(
            $('prioridade').value,
            'Prioridade definida manualmente.'
        );
    });

    $('problema').addEventListener('input', () => {
        clearTimeout(priorityTimer);

        const text = $('problema').value.trim();

        if (text.length < 10) {
            advisor(
                $('prioridade').value,
                'Digite uma descrição mais detalhada.'
            );
            return;
        }

        priorityTimer = setTimeout(() => {
            fetch(
                `?action=suggest_priority&text=${
                    encodeURIComponent(text.slice(0, 1800))
                }`
            )
                .then(r => r.json())
                .then(data => {
                    if (!data.prioridade) {
                        return;
                    }

                    if (!manualPriority) {
                        $('prioridade').value = data.prioridade;
                        $('prazo').value = data.prazo || 5;
                    }

                    advisor(
                        data.prioridade,
                        data.motivo || 'Sugestão automática.'
                    );

                    quality();
                });
        }, 350);
    });

    /* Patrimônio */
    const patInput = $('patrimonio');
    const patList = $('patList');
    const assetInfo = $('assetInfo');
    let patTimer = null;

    function closePat() {
        patList.classList.add('d-none');
        patList.innerHTML = '';
    }

    function loadPat(pat) {
        patInput.value = pat;
        closePat();

        assetInfo.className = 'asset-info visible';
        assetInfo.innerHTML =
            `<i class="bi bi-arrow-repeat me-1"></i>
             Consultando o patrimônio <strong>${escapeHtml(pat)}</strong>...`;

        fetch(`?action=get_patrimonio&pat=${encodeURIComponent(pat)}`)
            .then(r => r.json())
            .then(data => {
                if (data.tipo_equipamento) $('tipo').value = data.tipo_equipamento;
                if (data.marca) $('marca').value = data.marca;
                if (data.modelo) $('modelo').value = data.modelo;
                if (data.numero_serie) $('serie').value = data.numero_serie;

                const total = Number(data.total_os || 0);
                const abertas = Number(data.os_abertas || 0);

                assetInfo.className =
                    `asset-info visible ${abertas > 0 ? 'warning' : ''}`;

                assetInfo.innerHTML = abertas > 0
                    ? `<i class="bi bi-exclamation-triangle-fill me-1"></i>
                       Este patrimônio possui <strong>${abertas} OS aberta(s)</strong>
                       e ${total} atendimento(s) no histórico. Verifique duplicidade.`
                    : `<i class="bi bi-check-circle-fill me-1"></i>
                       Dados recuperados. Histórico total:
                       <strong>${total} OS</strong>.`;

                quality();
            })
            .catch(() => {
                assetInfo.className = 'asset-info visible warning';
                assetInfo.textContent =
                    'Não foi possível consultar o histórico.';
            });
    }

    patInput.addEventListener('input', () => {
        clearTimeout(patTimer);

        const q = patInput.value.trim();

        assetInfo.className = 'asset-info';
        assetInfo.innerHTML = '';

        if (!q) {
            closePat();
            return;
        }

        patTimer = setTimeout(() => {
            fetch(`?action=search_patrimonio&q=${encodeURIComponent(q)}`)
                .then(r => r.json())
                .then(items => {
                    if (!Array.isArray(items) || !items.length) {
                        closePat();
                        return;
                    }

                    patList.innerHTML = items.map(item => {
                        const date = item.ultima_data
                            ? new Date(item.ultima_data.replace(' ', 'T'))
                                .toLocaleDateString('pt-BR')
                            : 'Sem data';

                        return `
                            <div class="auto-item" data-pat="${escapeHtml(item.patrimonio)}">
                                <span class="auto-main">
                                    <i class="bi bi-upc-scan me-2"></i>
                                    ${escapeHtml(item.patrimonio)}
                                </span>

                                <span class="auto-meta">
                                    ${Number(item.total_os)} OS • ${date}
                                </span>
                            </div>
                        `;
                    }).join('');

                    patList.classList.remove('d-none');
                });
        }, 230);
    });

    patList.addEventListener('click', event => {
        const item = event.target.closest('[data-pat]');

        if (item) {
            loadPat(item.dataset.pat || '');
        }
    });

    document.addEventListener('click', event => {
        if (
            event.target !== patInput &&
            !patList.contains(event.target)
        ) {
            closePat();
        }
    });

    /* Arquivo */
    const fileInput = $('anexo');
    const fileZone = $('fileZone');

    function filePreview() {
        const file = fileInput.files[0];

        if (!file) {
            $('filePreview').classList.remove('visible');
            quality();
            return;
        }

        const allowed = [
            'image/png',
            'image/jpeg',
            'application/pdf'
        ];

        if (!allowed.includes(file.type)) {
            alert('Envie somente PNG, JPG, JPEG ou PDF.');
            fileInput.value = '';
            filePreview();
            return;
        }

        if (file.size > 8 * 1024 * 1024) {
            alert('O arquivo deve ter no máximo 8 MB.');
            fileInput.value = '';
            filePreview();
            return;
        }

        $('fileName').textContent = file.name;
        $('fileSize').textContent = `${bytes(file.size)} • ${file.type}`;
        $('filePreview').classList.add('visible');
        quality();
    }

    fileInput.addEventListener('change', filePreview);

    ['dragenter', 'dragover'].forEach(name => {
        fileZone.addEventListener(name, event => {
            event.preventDefault();
            fileZone.classList.add('drag');
        });
    });

    ['dragleave', 'drop'].forEach(name => {
        fileZone.addEventListener(name, event => {
            event.preventDefault();
            fileZone.classList.remove('drag');
        });
    });

    $('removeFile').addEventListener('click', event => {
        event.preventDefault();
        fileInput.value = '';
        filePreview();
    });

    /* Revisão */
    function updateSummary() {
        $('sumNome').textContent = value('nome');
        $('sumSetor').textContent = value('setor');
        $('sumContato').textContent = value('telefone');
        $('sumEmail').textContent = value('email');

        $('sumEquip').textContent = [
            value('tipo', ''),
            value('marca', ''),
            value('modelo', '')
        ].filter(Boolean).join(' • ') || 'Não informado';

        $('sumPat').textContent = value('patrimonio');
        $('sumPrior').textContent =
            `${value('prioridade')} • ${value('prazo', '5')} dia(s)`;
        $('sumQtd').textContent =
            `${value('quantidade', '1')} equipamento(s)`;
        $('sumAnexo').textContent =
            fileInput.files[0]?.name || 'Sem anexo';
        $('sumSerie').textContent = value('serie');
        $('sumProblema').textContent = value('problema');
    }

    /* Rascunho */
    const draftKey = 'nova_os_manutencao_ti_v3';

    const draftFields = [
        'nome', 'setor', 'email', 'telefone',
        'patrimonio', 'tipo', 'marca', 'modelo',
        'serie', 'prioridade', 'prazo',
        'quantidade', 'problema'
    ];

    function saveDraft(manual = false) {
        const data = {};

        draftFields.forEach(id => {
            data[id] = $(id).value;
        });

        data.savedAt = new Date().toISOString();

        localStorage.setItem(draftKey, JSON.stringify(data));

        $('draftStatus').innerHTML = `
            <i class="bi bi-cloud-check-fill"></i>
            ${manual ? 'Rascunho salvo agora' : 'Rascunho salvo automaticamente'}
        `;
    }

    function restoreDraft() {
        const raw = localStorage.getItem(draftKey);

        if (!raw) {
            return;
        }

        try {
            const data = JSON.parse(raw);

            draftFields.forEach(id => {
                if (
                    $(id) &&
                    !String($(id).value).trim() &&
                    data[id] !== undefined
                ) {
                    $(id).value = data[id];
                }
            });

            $('draftStatus').innerHTML = `
                <i class="bi bi-cloud-arrow-down-fill"></i>
                Rascunho anterior restaurado
            `;
        } catch {
            localStorage.removeItem(draftKey);
        }
    }

    let autosave = null;

    form.addEventListener('input', () => {
        clearTimeout(autosave);
        autosave = setTimeout(() => saveDraft(false), 700);
    });

    $('saveDraft').addEventListener('click', () => saveDraft(true));

    $('clearDraft').addEventListener('click', () => {
        if (!confirm('Limpar o formulário e remover o rascunho?')) {
            return;
        }

        localStorage.removeItem(draftKey);
        form.reset();
        fileInput.value = '';
        filePreview();

        manualPriority = false;
        $('prioridade').value = 'Média';
        $('prazo').value = '5';

        assetInfo.className = 'asset-info';
        assetInfo.innerHTML = '';

        showStep(1);
        quality();

        $('draftStatus').innerHTML = `
            <i class="bi bi-cloud-check-fill"></i>
            Rascunho removido
        `;
    });

    $('cancelBtn').addEventListener('click', () => {
        if (
            confirm(
                'Sair do cadastro? O rascunho continuará salvo neste navegador.'
            )
        ) {
            location.href = 'listar_os.php';
        }
    });

    form.addEventListener('submit', event => {
        if (sending) {
            event.preventDefault();
            return;
        }

        for (let step = 1; step <= 3; step++) {
            if (!validateStep(step)) {
                event.preventDefault();
                showStep(step);
                return;
            }
        }

        sending = true;
        $('submitBtn').disabled = true;
        $('submitBtn').innerHTML = `
            <span class="spinner-border spinner-border-sm"></span>
            Cadastrando...
        `;

        localStorage.removeItem(draftKey);
    });

    /* 3D */
    const hero = $('hero');

    if (
        matchMedia('(pointer:fine)').matches &&
        !matchMedia('(prefers-reduced-motion:reduce)').matches
    ) {
        hero.addEventListener('mousemove', event => {
            const rect = hero.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            const ry = ((x - rect.width / 2) / (rect.width / 2)) * .4;
            const rx = (((rect.height / 2) - y) / (rect.height / 2)) * .26;

            hero.style.transform =
                `perspective(1600px) rotateX(${rx}deg) rotateY(${ry}deg)`;
        });

        hero.addEventListener('mouseleave', () => {
            hero.style.transform =
                'perspective(1600px) rotateX(0) rotateY(0)';
        });
    }

    restoreDraft();
    showStep(1);
    quality();

    if ($('problema').value.trim().length >= 10) {
        $('problema').dispatchEvent(
            new Event('input', { bubbles: true })
        );
    }
})();
</script>

</body>
</html>
