<?php include('./header.php'); ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <title>Buesimples POS</title>
</head>
<style>
    .space-18 {
        margin: 4.5rem;
    }

    .bg-purple {
        background-color: #081A51;
    }

    .bg-light-white {
        background-color: #3f0061;
    }

    .bg-light-white-hover:hover {
        background-color: #3f0061;
    }

    /* Estilo da barra de rolagem */
    ::-webkit-scrollbar {
        width: 10px;
        /* largura da barra de rolagem */
    }

    .bg-purple {
        background-color: #560085 !important;
    }

    /* Estilo do polegar da barra de rolagem */
    ::-webkit-scrollbar-thumb {
        background-color: #06143fba;
        /* cor de fundo do polegar */
        border-radius: 5px;
        /* borda arredondada do polegar */
    }

    /* Estilize a barra de rolagem quando o mouse estiver sobre ela */
    ::-webkit-scrollbar:hover {
        background-color: rgba(0, 0, 0, 0.1);
        /* cor de fundo da barra de rolagem ao passar o mouse */
    }

    /* Estilize o polegar da barra de rolagem quando o mouse estiver sobre ele */
    ::-webkit-scrollbar-thumb:hover {
        background-color: #06143fd9;
        /* cor de fundo do polegar ao passar o mouse */
    }

    .btn {
        height: 2.5rem;
        /* Defina a altura desejada */
    }

    .link-class:hover {
        background-color: #f1f1f1;
    }

    .markedTest {
        background-color: yellow;
    }

    .swipeable {
        position: relative;
        overflow: hidden;
        vertical-align: bottom;
        backface-visibility: hidden;
        background: #999;
    }

    .swipeable:last-child {
        margin: 0;
    }

    .swipeable .inner {
        position: relative;
        z-index: 2;
        backface-visibility: hidden;
        background: #fff;
        font-size: 12px;
        color: #555;
    }

    .classePreco {
        cursor: grab;
    }

    .swipeable .inner:active {
        cursor: grabbing;
    }
    }

    .swipeable .action-button {
    .swipeable .action-button {
        position: absolute;
        z-index: 1;
        right: 0;
        top: 0;
        padding-right: 1rem;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 100%;
        height: 100%;
        cursor: pointer;
        text-align: right;
        color: white;
        letter-spacing: 2px;
        font-size: 12px;
        transition: .3s ease;
    }
    }

    .swipeable .action-button.delete {
        background: #dc2626;
        /* RGBA for darken effect */
    }

    .swipeable .action-button.delete:hover {
        background: #bf1f1f;
        /* Darker color on hover */
    }

    .swipeable .action-button.save {
        background: rgba(116, 203, 116, 0.8);
        /* RGBA for darken effect */
    }

    .swipeable .action-button.save:hover {
        background: rgba(116, 203, 116, 0.9);
        /* Darker color on hover */
    }

    .swipeable .tab-icon,
    .swipeable .tab-icon:before,
    .swipeable .tab-icon:after {
        background: #666;
    }

    #cardFamilia {
        flex-grow: 1;
        /* Faz com que o elemento cresça para ocupar o espaço disponível */
        max-height: calc(100vh - 280px);
        /* Ajusta o valor conforme necessário para deixar espaço para outros elementos */
        overflow-y: auto;
        /* Adiciona barra de rolagem se o conteúdo exceder o tamanho */
    }

    /* Ajustes adicionais para responsividade */
    @media (max-width: 768px) {
        #cardFamilia {
            max-height: calc(100vh - 150px);
            /* Ajuste conforme necessário para dispositivos menores */
        }
    }

    main {
        flex-grow: 1;
        max-height: calc(100vh - 4.5rem);
        overflow-y: auto;
    }

    #resultadoPesquisa {
        flex-grow: 1;
        max-height: calc(30vh);
        overflow-y: auto;
    }
</style>

<body>
    <div class="preloader flex-column justify-content-center align-items-center">
        <img src="images/logo/logo.svg" alt="AdminLTELogo" height="auto" width="350">
    </div>
    <span class="absolute text-white text-4xl bottom-5 right-4 cursor-pointer" id="cart">
        <i class="fa-solid fa-cart-shopping bg-purple rounded-md p-2" style="font-size: 1.4rem"></i>
    </span>
    <div class="flex flex-col md:flex-row font-sans text-gray-900 bg-gray-100">
        <aside class="w-full md:w-64 duration-300 h-auto md:h-screen p-3 pt-8 bg-purple relative flex flex-col justify-between">
            <div class="flex gap-x-4 items-center">
                <img src="./images/logo/favicon.png" alt="" class="w-10">
                <h1 class="text-white origin-left font-medium text-xl duration-300">Buesimples</h1>
                <img alt="" class="block md:hidden h-10 w-10 object-cover rounded-full ml-auto" id="imagemUsuarioT">
            </div>
            <div class="flex items-center rounded-full bg-light-white md:mt-10 mt-3 px-3 py-2">
                <i class="fa fa-search text-white text-lg block float-left cursor-pointer mr-2"></i>
                <input type="text" name="" id="searchFamilia" placeholder="Pesquisar" class="text-base bg-transparent w-full text-white">
            </div>
            <nav class="flex flex-1 flex-col gap-y-4 md:pt-10 overflow-y-auto h-screen">
                <ul class="overflow-y-auto flex-1 max-h-14 md:max-h-full" id="cardFamilia">
                </ul>
                <ul class="hidden md:block pt-6">
                    <li class="text-gray-300 text-sm flex items-center gap-x-4 p-2 hover:bg-light-white rounded-md mt-2 bg-light-white cursor-pointer" id="btnUser">
                        <img alt="./images/artigo/artigo_12.jpg" class="h-10 w-10 object-cover rounded-full" id="imagemUsuario">
                        <span class="origin-left duration-200">
                            <h1 class="text-white origin-left font-medium duration-300" id="nomeUsuario"></h1>
                        </span>
                    </li>
                </ul>
            </nav>
        </aside>
        <div class="flex-1 flex flex-col">
            <header class="h-18 items-center border-b border-gray-200 bg-white gap-x-6 px-4 md:px-8 py-3 justify-center">
                <form class='w-550px relative'>
                    <div class="relative">
                        <input type="search" placeholder='Pesquise aqui' class='w-full p-3 rounded-full bg-slate-800 bg-gray-100 border border-gray-300' style="height: 2rem;" id="searchArtigo" />
                        <button class='absolute right-0 top-1/2 transform -translate-y-1/2 p-2 bg-purple rounded-full flex items-center justify-center' style="height: 1.5rem; width: 1.5rem; right: .3rem;" id="btnListagemArtigo">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>
                    <ul class="top-10 absolute list-group w-full rounded-xl -translate-x-1/2 flex flex-col z-50" id="resultadoPesquisa"></ul>
                </form>
            </header>
            <main class="relative overflow-y-auto flex-1 md:px-8 h-full" id="containerCardProduct">
            </main>
        </div>
        <aside class="flex flex-col border-l border-gray-200 bg-white w-80 md:flex h-screen -left-80 md:left-0 md:relative absolute" id="asideCart">
            <div class="border-b border-gray-200 px-2 py-2">
                <div class="flex items-center justify-end">
                    <h1 class="flex items-end justify-end gap-x-2 text-sm font-semibold leading-6 text-lg pt-2" id="dataHora"></h1>
                </div>
                <h1 class="flex items-start justify-start text-sm font-semibold leading-6 text-lg" id="codigoDocumento"></h1>
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="flex items-start justify-start gap-x-2 text-sm font-semibold leading-6 text-lg">Cliente</h1>
                        <h1 class="flex items-start justify-start gap-x-2 text-sm font-semibold leading-6 text-lg pt-2" id="textoCliente">Consumidor Final</h1>
                    </div>
                    <button class="flex items-end justify-end rounded-xl bg-purple px-2 py-2 text-sm leading-6 text-white" id="btn">Adicionar</button>
                </div>
                <div class="mt-2">
                    <form class='w-550px relative'>
                        <div class="relative">
                            <input type="search" placeholder='Pesquise aqui' class='w-full p-3 rounded-full bg-slate-800 bg-gray-100 border border-gray-300' style="height: 2rem;" id="searchCliente" />
                            <button class='absolute right-0 top-1/2 transform -translate-y-1/2 p-2 bg-purple rounded-full flex items-center justify-center' style="height: 1.5rem; width: 1.5rem; right: .3rem;" id="btnSearchCliente">
                                <i class="fa fa-search"></i>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            <div class="flex flex-col flex-1  h-screen overflow-y-auto">
                <div class="px-4 border-b border-gray-200">
                    <div class="flex justify-between py-2">
                        <span class="text-sm font-semibold">Descrição</span>
                        <span class="text-sm font-semibold">Qtd.</span>
                        <span class="text-sm font-semibold">Preço</span>
                    </div>
                </div>
                <div class="flex flex-col flex-1 overflow-y-auto" id="linhaArtigo">
                </div>
            </div>

            <div class="flex items-center justify-between py-2 px-4 border-b border-gray-200">
                <h1 class="flex items-start justify-start gap-x-2 font-bold leading-6 text-3xl">TOTAL</h1>
                <h1 class="flex items-start justify-start gap-x-2 font-bold leading-6 text-3xl" id="totalAbsoluto"></h1>
            </div>
            <div class="flex items-center justify-between py-2 px-4 border-b border-gray-200">
                <button class="flex items-center justify-center rounded-xl bg-red-600 px-4 py-2 text-sm leading-6 text-white btn" title="Limpar lista" id="btnLimpar"><i class="fas fa-trash"></i></button>
                <button class="flex items-center justify-center rounded-xl bg-purple px-4 w-1/2 py-2 text-sm leading-6 text-white" id="btnSubmit">Fechar Conta</button>
            </div>
        </aside>
    </div>
    <div class="modal fade" id="modal-formCliente">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <div class="container">
                        <div class="progress-barra">
                            <div class="step">
                                <p style="margin: 0;">Formulário de Entidade</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-body">
                    <div class="container">
                        <div class="card-body form-outer" style="padding: 0;">
                            <div class="formulario">
                                <div class="page slidePage">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <h5 style="margin-bottom: 1rem; justify-content: center;"><span id="doOpcao"></span> - <span id="codigo"></span></h5>
                                            <div class="row">
                                                <div class="col-md-2" style="text-align: -webkit-center;">
                                                    <div class="form-group margem">
                                                        <div class="wrapper-image">
                                                            <div class="image-container">
                                                                <i class="fas fa-image"></i>
                                                            </div>
                                                            <label for="file" class="camera-icon">
                                                                <i class="fas fa-camera"></i>
                                                            </label>
                                                            <input type="file" id="file" name="file" accept="image/*" hidden>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-2"></div>
                                                <div class="col-md-4">
                                                    <div class="form-group" style="margin-top: .4rem;">
                                                        <small>Mensagem de erro</small>
                                                        <div class="custom-control custom-switch">
                                                            <input type="checkbox" class="custom-control-input" name="estado" id="estado" value="1" checked>
                                                            <label class="custom-control-label" for="estado">Estado - Activo</label>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group" style="margin-top: .4rem;">
                                                        <small>Mensagem de erro</small>
                                                        <div class="custom-control custom-switch">
                                                            <input type="checkbox" class="custom-control-input" name="retencaoFonte" id="retencaoFonte" value="0">
                                                            <label class="custom-control-label" for="retencaoFonte">Retenção na Fonte - Inactiva</label>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="required">Nome</small>
                                                        <input type="text" class="form-control" id="nome" name="nome" placeholder="Nome Entidade" title="Nome Entidade" data-campo="Nome" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="required">Nome Comercial</small>
                                                        <input type="text" class="form-control" id="nomeComercial" name="nomeComercial" placeholder="Nome Comercial" title="Nome Comercial" data-campo="Nome Comercial" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="required">Tipo de Entidade</small>
                                                        <select class="form-control select2" style="width: 100%;" id="idTipoEntidade" name="idTipoEntidade" data-campo="Tipo de Entidade">
                                                            <option value="0">Selecione Tipo de Entidade</option>
                                                        </select>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="required">NIF (Número de Identificação Fiscal)</small>
                                                        <input type="text" class="form-control" id="nif" name="nif" placeholder="NIF (Número de Identificação Fiscal)" title="NIF (Número de Identificação Fiscal)" data-campo="NIF" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="not-required">Bilhete de Identidade</small>
                                                        <input type="text" class="form-control" id="bi" name="bi" placeholder="Bilhete de Identidade" title="Nº Bilhete de Identidade" data-campo="BIlhete de Identidade" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="required">Linha de Preço Pré-definida</small>
                                                        <select class="form-control select2 not-required" style="width: 100%;" id="linhaPrecoPredefinida" name="linhaPrecoPredefinida" data-campo="Linha de Preço Pré-definida">
                                                            <option value="0">Selecione Linha de Preço</option>
                                                        </select>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="not-required">Localidade</small>
                                                        <input type="text" class="form-control" id="localidade" name="localidade" placeholder="Localidade" title="Localidade" data-campo="Localidade" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="not-required">Data de Nascimento</small>
                                                        <input type="date" class="form-control" id="dataNasc" name="dataNasc" placeholder="Data de Nascimento" title="Data de Nascimento" data-campo="Data de Nascimento" required>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                    <div class="form-group" style="margin-bottom: 0;">
                                                        <small class="not-required">Morada</small>
                                                        <textarea rows="1" type="text" class="form-control" id="morada" name="morada" placeholder="Morada" title="Morada" data-campo="Morada" required></textarea>
                                                        <small>Mensagem de erro</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-12" style=" bottom: 0; padding-top: 14px;">
                                            <div class="form-group margem">
                                                <small>Mensagem de erro</small>
                                                <div class="form-group field btns">
                                                    <button class="btn btn-block btn-primary submit next" style="margin-top: 0;" id="btnCreateEntidade">
                                                        Gravar Entidade
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-xx">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header" style="background-color: #55127C; color: #fff">
                    <h4 class="modal-title">Abertura de Caixa</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true" style="color: #fff !important">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="col-12">
                        <div class="row">
                            <div class="col-md-12">
                                <small class="required">Nome do Usuário</small>   
                                <input type="text" class="form-control" placeholder="Nome" id="username" value="" readonly>
                            </div>
                            <div class="col-md-12 mt-3">
                                <small class="required">Selecionar caixa</small>   
                                <select name="" id="caixa_id" class="form-control" placeholder="">
                                    <option value="" disabled>Selecione o Caixa</option>
                                </select>
                            </div>
                            <div class="col-md-12 my-3">
                                <small class="required">Valor de Abertura</small>   
                                <input type="text" id="valor_abertura" class="form-control" placeholder="0,00 kz">
                            </div>
                            <div class="col-md-12">
                                <button class="btn btn-block btn-primary" id="btn_abertura_caixa">Finalizar</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal-xx-logout">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header" style="background-color: #55127C; color: #fff">
                    <h4 class="modal-title">Fechar Caixa</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true" style="color: #fff !important">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="col-12">
                        <div class="row">
                            <div class="col-md-12">
                                <small class="required">Nome do Usuário</small>   
                                <input type="text" class="form-control" placeholder="Nome" id="nomeUse" value="admin" readonly>
                            </div>
                            <div class="col-md-12 mt-3">
                                <small class="required">Selecionar caixa</small>   
                                <select name="" id="caixa_select" class="form-control" placeholder="" disabled>
                                </select>
                            </div>
                            <div class="col-md-12 my-3">
                                <small class="required">Valor de Fecho</small>   
                                <input type="text" id="valor_fecho" class="form-control" placeholder="Nome">
                            </div>
                            <div class="col-md-12 mb-1">
                                <button class="btn btn-block btn-primary" id="btn_feicho_caixa">Finalizar</button>
                            </div>
                            
                            <hr>

                            <div class="col-md-12 mt-1">
                                <button class="btn btn-block btn-danger" id="btn_logout">Fazer logout</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="modal-cliente">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Clientes</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <table id="tabelaCliente" class="table table-hover table-bordered table-striped">
                        <thead>
                            <tr style="text-align: center;">
                                <th title="Identificador da Entidade">Ref. Entidade</th>
                                <th title="Nome">Nome</th>
                                <th title="Nome Comercial">Nome Comercial</th>
                                <th title="Bilhete de Identidade do Cliente">B.I</th>
                                <th title="NIF do Cliente">NIF</th>
                                <th title="Localidade do Cliente">Localidade</th>
                                <th title="Morada do Cliente">Morada</th>
                            </tr>
                        </thead>
                        <tbody style="text-align: center;">
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-primary" id="btnSelectCliente" disabled>Confirmar</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modal-artigo">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Artigos</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <table id="tabelaArtigoListagem" class="table table-hover table-bordered table-striped">
                        <thead>
                            <tr style="text-align: center;">
                                <th title="Referência">Referência</th>
                                <th title="Descrição do Artigo">Descrição</th>
                                <th title="Preço do Artigo (C/Imp)">Preço (C/Imp)</th>
                                <th title="Qtd. Stock">Qtd. Stock</th>
                            </tr>
                        </thead>
                        <tbody style="text-align: center;">
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-primary" id="btnSelectArtigo" disabled>Confirmar</button>
                </div>
            </div>
        </div>
    </div>
    </div>
    <div class="modal fade" id="modal-updateTipoEntidade">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header" style="padding: 0.5rem;">
                    <h3 class="card-title p-3">Cliente: <span id="nomeModal"></span></h3>
                </div>
                <div class="modal-body" style="padding-bottom: 0px;">
                    <div class="row">
                        <div class="col-md-12">
                            <form name="tabelaInfo">
                                <table name="tabelaInfo" class="table table-sm table-bordered" style="min-width: 100%;
                      max-width: 100%;">
                                    <tr name="linhaItem">
                                        <td style="padding: 20px 0px 0px 10px;">
                                            <p>Ref. da Cliente: <span id="codigoInfo"></span></p>
                                            <p>Descrição: <span id="nomeInfo"></span></p>
                                            <p>Observações: <span id="notaInfo"></span></p>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modal-modoPagamento">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header" style="padding: 0.5rem;">
                    <h3 class="card-title p-3">Modos de Pagamento</h3>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card-body table-responsive p-0" style="height: 15rem; border: 0;">
                                <table class="table table-hover text-wrap" id="tabelaModoPagamento">
                                    <tbody id="modoPagamentoBody">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="col-md-12" id="footerPagamento" style="margin-top: 2rem;">
                            <h4 style="display: flex; align-items: center; justify-content: space-between;"><span id="entregueTexto" class="text-lg">ENTREGUE</span><span class="text-lg" id="entregueValor"></span></h4>
                            <h4 style="display: flex; align-items: center; justify-content: space-between;"><span class="text-danger text-lg" id="totalTexto">TOTAL</span><span id="totalValor" class="text-lg"></span></h4>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default rounded-xl text-sm leading-6" data-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-primary rounded-xl text-sm leading-6 text-white btn-layout" id="./formLayoutTicket.php">Confirmar</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="modal-layout">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Documento</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <iframe id="layoutDocumento" frameborder="0" width="100%" style="height: 60vh;"></iframe>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                    <button type="button" class="btn btn-primary" id="btn-print">Imprimir</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
    <?php include('footer.php'); ?>
</body>

</html>
<script src="./javascript/snap.min.js"></script>
<script>
    let linha;
    let clienteSelecionado;
    let valores = [];
    let valoresDuplicados = [];
    let totalDoc;
    let moeda;
    let tipoDocumento;
    let idDocumento;

    $(document).ready(function() {

        funcaoSelect("includes/select.inc.php", "post", "json", "caixabanco", function success(data) {
                console.log(data)
                let select = "";
                select = `<option value="" disabled selected>Selecione o Caixa</option>`
                for (var i = 0; i < data.length; i++) {
                    if (data[i]['idTipoCaixaBanco'] == 1) {
                        select += `
                        <option value="${data[i]['idCaixabanco']}">${data[i]['descricao']}</option>

                        `
                    }
                }
                $('#caixa_id').html(select);
            },
            function error(data) {
                erro(data);
            },
            function done(data) {
                loadClickedFamilia();
            });

        $.ajax({
                  url: "includes/movimentocaixa.inc.php",
                  type: "post",
                  dataType: "json",
                  data: {
                    idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
                  },
                  success: function(data) {
                    console.log('Vamos ver o que traz')
                    if (data == 0) {
                        $('#modal-xx').modal('show');
                    }
                  },
                  error: function(data) {
                    console.log(data)
                  }
                });



        $('#btn_feicho_caixa').click(function(e){
            var idcaixa = $('#caixa_id').val();
            var valor_fecho = $('#valor_fecho').val();
            var datatime = '';
            var now = new Date();
            var date = now.toLocaleDateString('pt-BR');
            var time = now.toLocaleTimeString('pt-BR');
            var aux = date.split('/')
            datatime = aux[2] + '-' +aux[1] + '-' +aux[0] + ' ' + time;
            
            if (valor_fecho != null && valor_fecho != '' && valor_fecho != undefined) {
            
            Swal.fire({
              icon: 'info',
              title: 'Emitir Documento?',
              text: 'Tem certeza dos dados submetidos?',
              allowOutsideClick: false,
              showCancelButton: true,
              confirmButtonText: 'Confirmar',
              confirmButtonColor: '#560085',
              cancelButtonText: 'Cancelar',
              cancelButtonColor: '#560085',
            }).then((result) => {
              if (result.isConfirmed) {

                funcaoUpdate("includes/update.inc.php", "post", "json", "movimento_caixa", 
                {
                    data_time_fecho: datatime,
                    valor_fecho: parseInt(valor_fecho.replace(/\ /g, '').replace(/\,/g, '.'))}
                    , {
                    id_movimento_caixa: window.localStorage.getItem('movimento_caixa_id')
                }, function success(data) {

                        console.log("Sucesso: ", data);
                        logout();
                    }
                    , function error(data){
                        console.log("Pegar o erro: ", data);
                    swal.fire({
                      title: "Erro ao Emitir Documento!",
                      text: "Erro ao Facturar!",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "error",
                    });
                    }, function done(data){

                });
                
                };

            });
            }else{
                    $('#caixa_id').css('border-color', 'red');
            }
        });


        $('#btn_abertura_caixa').click(function(e){
            var idcaixa = $('#caixa_id').val();
            var valor_abertura = $('#valor_abertura').val();
            var datatime = '';
            var now = new Date();
            var date = now.toLocaleDateString('pt-BR');
            var time = now.toLocaleTimeString('pt-BR');
            datatime = date + ' ' + time;
            
            if (idcaixa != null) {
            alert('idcaixa '+ idcaixa + ' valor_abertura '+valor_abertura)
            Swal.fire({
              icon: 'info',
              title: 'Emitir Documento?',
              text: 'Tem certeza dos dados submetidos?',
              allowOutsideClick: false,
              showCancelButton: true,
              confirmButtonText: 'Confirmar',
              confirmButtonColor: '#560085',
              cancelButtonText: 'Cancelar',
              cancelButtonColor: '#560085',
            }).then((result) => {
              if (result.isConfirmed) {

                funcaoInsert("includes/insert.inc.php", "post", "json", "movimento_caixa", {
                    usuario_id: <?php echo $_SESSION["usuarioId"]; ?>,
                    caixa_id: idcaixa,
                    valor_abertura: parseInt(valor_abertura.replace(/\ /g, '').replace(/\,/g, '.'))}
                    , function success(data) {
                        console.log("Sucesso: ", data);
                        window.localStorage.setItem('movimento_caixa_id', data);
                        window.location.reload()
                    }
                    , function error(data){
                        console.log("Pegar o erro: ", data);
                    swal.fire({
                      title: "Erro ao Emitir Documento!",
                      text: "Erro ao Facturar!",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "error",
                    });
                    }, function done(data){

                });
                
                };

            });
            }else{
                    $('#caixa_id').css('border-color', 'red');
            }
        });
    });

    $(document).on('click', '#cart', function(e) {
        e.preventDefault();
        const aside = document.querySelector('#asideCart');
        aside.classList.toggle('-left-80');
    });

    $(document).on("click", "#btnUser", function(e) {
        e.preventDefault();
        let fazerLogout = false;
        var boolean = verCaixaAberto();
        
        if (boolean != 0) {

            $('#modal-xx-logout').modal('show');

            return;
        }else{
            logout()
        }
    });

    $(document).on("click", "#btn_logout", function(e) {
        e.preventDefault();
        logout();
    });

    

    $(document).on("click", "#imagemUsuarioT", function(e) {
        e.preventDefault();
        let fazerLogout = false;
        var boolean = verCaixaAberto();
        
        if (boolean != 0) {

            $('#modal-xx-logout').modal('show');

            return;
        }else{
            logout()
        }
    });

    function logout() {
        swal.fire({
                title: "Terminar sessão?",
                text: "Tem a certeza que pretende sair do sistema?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
                cancelButtonText: 'Cancelar',
                cancelButtonColor: '#560085',
            })
            .then((result) => {
                if (result.isConfirmed) {
                    window.location.href = "includes/logout.inc.php";
                }
            });
    }

    $(document).on("click", ".linhaResultadoPesquisa", function(e) {
        e.preventDefault();
        alert('_________')
        //loadClickedArtigo($(this).attr('data-artigo'));
        //$('#resultadoPesquisa').html('');
        //$('#searchArtigo').val('');
    });

    $(document).on("keypress", "#searchArtigo", function(e) {
        if (e.which === 13) {
            e.preventDefault();
        }
    });

    $(document).on("focusout", "#searchArtigo", function(e) {
        e.preventDefault();
        setTimeout(function() {
            if (!$(".linhaResultadoPesquisa:focus").length) {
                $('#resultadoPesquisa').html('');
                $('#searchArtigo').val('');
            }
        }, 200);
    });

    $(document).ready(() => {
        loadNovoId();
    });

    $(document).on("keyup", "#searchArtigo", function(e) {
        e.preventDefault();
        $('#resultadoPesquisa').html('');
        var searchField = $('#searchArtigo').val();
        var expression = new RegExp(searchField, "i");
        getDefinicao()
            .then(dataDefinicao => {
                getArtigo().then(dataArtigo => {
                    if (searchField == "") {
                        $('#searchArtigo').html('');
                    } else if (dataArtigo != null) {
                        for (let i = 0; i < dataArtigo.length; i++) {
                            if (expression.test(dataArtigo[i]["nome"])) {
                                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                                    idArtigo: dataArtigo[i]["idArtigo"],
                                    indice: dataDefinicao[1]["valor"]
                                }, "precoArtigo", function success(data) {
                                    var nomeDestacado = dataArtigo[i]["nome"].replace(expression, function(match) {
                                        return '<span class="markedTest">' + match + '</span>';
                                    });
                                    $('#resultadoPesquisa').append('<li class="list-group-item flex justify-between cursor-pointer linhaResultadoPesquisa" data-artigo=' + dataArtigo[i]["idArtigo"] + '><span>' + nomeDestacado + '</span><span>' + parseFloat(data[0]["comImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda + '</span></li>');
                                }, function error(data) {}, function done(data) {

                                });

                            }
                        }
                    }
                });

            });
    });

    $(document).on('click', '#btnSubmit', function(e) {
        e.preventDefault();
        let linha = document.querySelector('#linhaArtigo').querySelectorAll('.linha');
        if (linha.length > 0) {
            let modoPagamento = document.querySelectorAll('.mp');
            sumCampoTotal(modoPagamento, entregueValor, entregueTexto, totalValor, totalTexto, totalDoc, moeda);
            $('#modal-modoPagamento').modal('show');
        }
    });

    $(document).on('click', '.btn-layout', function(e) {
        e.preventDefault();
        if (parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.')) >= parseFloat(totalDoc)) {
            EfectuarVenda();
            funcaoSelect("includes/select.inc.php", "post", "json", "configuracao", function success(data) {
                console.log("FAMÍLIA: ", data);
            }, function error(data) {

            }, function done(data) {

            });
            $('#modal-modoPagamento').modal('hide');
            var iframe = document.getElementById('layoutDocumento');

            function loadDocumento() {
                let tela = iframe.contentWindow.document.body;

                const dataAtual = new Date();
                const dia = String(dataAtual.getDate()).padStart(2, '0');
                const mes = String(dataAtual.getMonth() + 1).padStart(2, '0');
                const ano = dataAtual.getFullYear();
                const hora = String(dataAtual.getHours()).padStart(2, '0');
                const minuto = String(dataAtual.getMinutes()).padStart(2, '0');
                const segundo = String(dataAtual.getSeconds()).padStart(2, '0');
                console.log(`Hora atual: ${hora}:${minuto}:${segundo}`);


                if (searchCliente.value == "") {
                    searchCliente.value = "999999999";
                }

                let select = "";
                let linha = linhaArtigo.querySelectorAll('.linha');
                for (let i = 0; i < linha.length; i++) {
                    select += `
                <tr>
                    <td style="text-align: left;">${linha[i].querySelector('.quantity').value.replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                    <td style="text-align: left;">${linha[i].querySelector('.descricao').innerText}</td>
                    <td style="text-align: right;">${parseFloat(linha[i].querySelector('.total').innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</td>
                    <td style="text-align: right;">${parseFloat(parseFloat(linha[i].querySelector('.total').innerText.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(linha[i].querySelector('.quantity').value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</td>
                </tr>
                `;
                }
                console.log("VAMOS PEGAR: ", tela.querySelector('#tabelaDocumento'));
                tela.querySelector('#tabelaDocumento').innerHTML = select;
                tela.querySelector('#codigoDoc').innerText = $('#codigoDocumento').text().split("/")[0] + "/" + parseFloat($('#codigoDocumento').text().split("/")[1] - 1);
                tela.querySelector('#dataEmissaoDocumento').innerText = `${dia}-${mes}-${ano} ${hora}:${minuto}:${segundo}`;
                tela.querySelector('#viaDocumento').innerText = "ORIGINAL";
                tela.querySelector('#clienteDocumento').innerText = $('#textoCliente').text();
                tela.querySelector('#nifDocumento').innerText = searchCliente.value;
                tela.querySelector('#usuarioDocumento').innerText = "<?php echo strtoupper($_SESSION["usuarioNome"]); ?>";
                tela.querySelector('#recebidoDocumento').innerText = entregueValor.innerText;
                tela.querySelector('#aPagarDocumento').innerText = parseFloat(totalDoc).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;

                if (parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.')) < parseFloat(totalDoc)) {
                    tela.querySelector('#trocoDocumento').innerText = parseFloat(totalDoc - parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                } else if (parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.')) == parseFloat(totalDoc)) {
                    tela.querySelector('#trocoDocumento').innerText = parseFloat(totalDoc - parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                } else if (parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.')) > parseFloat(totalDoc)) {
                    tela.querySelector('#trocoDocumento').innerText = parseFloat(parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.')) - totalDoc).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                }

                let modos = "";
                let tabela = document.querySelector('#tabelaModoPagamento');
                for (let i = 0; i < tabela.rows.length; i++) {
                    if (tabela.rows[i].cells[2].querySelector("input").value != "") {
                        modos += "<tr>";
                        modos += `<td style="padding: 0; border:none; padding-right: 1rem;">${tabela.rows[i].cells[1].innerText}</td>`;
                        modos += `<td style="padding: 0; border:none; text-align: right;">${parseFloat(tabela.rows[i].cells[2].querySelector("input").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</td>`;
                        modos += "</tr>";
                    }
                }

                tela.querySelector('#tabelaModoPagamentoDocumento').innerHTML = modos;
                tela.querySelector('#totalDocumento').innerText = parseFloat(totalDoc).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;

                tela.querySelector('#logotipoDocumento').src = logotipo;
                tela.querySelector('#telefoneDocumento').innerText = telefoneDoc;
                tela.querySelector('#emailDocumento').innerText = emailDoc;

                let row = linhaArtigo.querySelectorAll('.linha');
                let totalLinha = 0;
                for (let i = 0; i < row.length; i++) {
                    totalLinha += parseInt(row[i].querySelector('.quantity').value.replace(/\ /g, '').replace(/\,/g, '.'));
                }
                tela.querySelector('#nItensDocumento').innerText = totalLinha;
            }
            /*function loadDocumento() {
                iframe.contentWindow.codigoDocumento(idDocumento, tipoDocumento);
            }*/
            iframe.onload = loadDocumento;
            iframe.src = this.id;
            $('#modal-layout').modal('show');
        }
    });

    $(document).on("click", "#btn-print", function(e) {
        var iframe = document.getElementById('layoutDocumento');
        iframe.contentWindow.print();
    });

    $(document).on("click", "#btnListagemArtigo", function(e) {
        e.preventDefault();
        $('#modal-artigo').modal('show');
    });

    $(document).on("click", "#btnLimpar", function(e) {
        e.preventDefault();
        if (linhaArtigo.querySelectorAll('.linha').length > 0) {
            swal.fire({
                    title: "Limpar Lista",
                    text: "Tem a certeza que pretende limpar a lista?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: 'Confirmar',
                    confirmButtonColor: '#560085',
                    cancelButtonText: 'Cancelar',
                    cancelButtonColor: '#560085',
                })
                .then((result) => {
                    if (result.isConfirmed) {
                        linhaArtigo.innerHTML = "";
                        totalAbsoluto.innerText = "0,00";
                        funcaoSearchCliente(1);
                        valores.length = 0;
                        valoresDuplicados.length = 0;
                    }
                });
        }
    });

    $(document).on("click", "#btnCreateEntidade", function(e) {
        e.preventDefault();
        let required = document.querySelector("#modal-formCliente").querySelectorAll('.required');
        let todosPreenchidos = true;

        for (let i = 0; i < required.length; i++) {
            if (required[i].parentElement.querySelector('input') != null) {
                if (required[i].parentElement.querySelector('input').value === "") {
                    todosPreenchidos = false;
                    break;
                }
            }
        }

        if (todosPreenchidos) {
            let img = $("#file")[0].files;
            entidade(img);
        }
    });

    function entidade(img) {
        let dados = {
            idUsuario: 1,
            nome: nome.value,
            nomeComercial: nomeComercial.value,
            nif: nif.value,
            bi: bi.value,
            localidade: localidade.value,
            dataNasc: dataNasc.value,
            morada: morada.value,
            idTipoEntidade: 2,
            linhaPreco: linhaPrecoPredefinida.value,
            retencaoFonte: retencaoFonte.value,
            estado: estado.value,
        };
        let tabela = "entidade";

        funcaoInsert("includes/insert.inc.php", "post", "json", tabela, dados, function success(data) {
            swal.fire({
                title: "Cadastro efectuado com sucesso!",
                text: "Cliente " + nome.value + " cadastrado!",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
                icon: "success",
            });
            $('#modal-formCliente').modal('hide');
            funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                idEntidade: data
            }, "viewEntidade", function success(data) {
                funcaoSearchCliente(data[0]["codigoEntidade"]);
            }, function error(data) {

            }, function done(data) {

            });
        }, function error(data) {
            swal.fire({
                title: "Erro ao cadastrar Cliente!",
                text: "Erro ao cadastrar Cliente: " + nome.value + " !",
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
                icon: "error",
            });
        }, function done(data) {

        });
    }

    $(document).on("change", "#estado", function(e) {
        e.preventDefault();
        var labelEstado = document.querySelector("label[for='estado']");
        if (estado.checked == true) {
            estado.value = 1;
            labelEstado.innerText = "Estado - Activo";
        } else {
            estado.value = 0;
            labelEstado.innerText = "Estado - Inactivo";
        }
    });

    $(document).on("change", "#retencaoFonte", function(e) {
        e.preventDefault();
        var labelRetencaoFonte = document.querySelector("label[for='retencaoFonte']");
        if (retencaoFonte.checked == true) {
            retencaoFonte.value = 1;
            labelRetencaoFonte.innerText = "Retenção na Fonte - Activa";
        } else {
            retencaoFonte.value = 0;
            labelRetencaoFonte.innerText = "Retenção na Fonte - Inactiva";
        }
    });

    $(document).on("keypress", "#searchCliente", function(e) {
        if (e.which === 13) {
            e.preventDefault();
            funcaoSearchCliente(this.value);
        }
    });

    $(document).on("keyup", "#searchFamilia", function(e) {
        e.preventDefault();
        var searchField = $('#searchFamilia').val();
        var expression = new RegExp(searchField, "i");
        funcaoSelect("includes/select.inc.php", "post", "json", "familia", function success(data) {
                if (searchField == "") {
                    let select = "";
                    for (let i = 0; i < data.length; i++) {
                        select += `
                            <li class="text-gray-300 text-sm flex items-center gap-x-4 cursor-pointer p-2 hover:bg-light-white rounded-md mt-2 linhaFamilia" data-familia="${data[i]["idFamilia"]}">
                                <span class="origin-left duration-200">${data[i]["nome"]}</span>
                            </li>
                            `;
                    }
                    $('#cardFamilia').html(select);
                } else if (data != null) {
                    let select = "";
                    for (let i = 0; i < data.length; i++) {
                        if (expression.test(data[i]["nome"])) {
                            select += `
                                <li class="text-gray-300 text-sm flex items-center gap-x-4 cursor-pointer p-2 hover:bg-light-white rounded-md mt-2 linhaFamilia" data-familia="${data[i]["idFamilia"]}">
                                    <span class="origin-left duration-200">${data[i]["nome"]}</span>
                                </li>
                                `;
                            $('#cardFamilia').html(select);
                        }
                    }
                }
            },
            function error(data) {
                erro(data);
            },
            function done(data) {
                loadClickedFamilia();
            });
    });

    function verCaixaAberto() {
            $.ajax({
                  url: "includes/movimentocaixa.inc.php",
                  type: "post",
                  dataType: "json",
                  data: {
                    idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
                  },
                  success: function(data) {
                    if (data != 0) {
                        console.log(data)
                        $('#caixa_select').html(`<option value="${data[0]['idCaixabanco']}">${data[0]['descricao']}</option>`)
                        return data.length
                    }else{
                        return 0;
                    }
                  },
                  error: function(data) {
                  }
                });
        }

    function funcaoSearchArtigo(parametro) {
        let resultado = mesmoArtigoVerify(parametro.find('td')[0].textContent);
        if (resultado.length > 0) {
            var elementos = valoresDuplicados.filter(function(valor) {
                return valor === parametro.find('td')[0].textContent;
            });
            if (elementos.length > 0) {
                let linha = linhaArtigo.querySelectorAll('.linha');
                for (let i = 0; i < linha.length; i++) {
                    if (parametro.find('td')[0].textContent === linha[i].getAttribute('data-linha')) {
                        let valor = linha[i].querySelector('.quantity');
                        if (valor.value == "") {
                            valor.value = 1;
                        } else {
                            valor.value = parseInt(valor.value) + 1;
                            totalDocumento();
                        }
                        linha[i].querySelector('.total').innerText = parseFloat(parseFloat(linha[i].querySelector('.quantity').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                    }
                }
                totalDocumento();
            } else {
                let select = `
                <article class="swipeable">
            <div class="inner">
      <div class="linha" data-linha="${parametro.find('td')[0].textContent}" style="border-bottom: 1px solid #e5e7eb; padding: 0;">
        <div class="col-md-12">
          <div style="display: flex; justify-content: space-between;">
            <div class="col-md-5" style="padding-left: 0;">
              <div class="form-group p-2" style="font-size: 1rem; margin: 0; display: flex; align-items: center; justify-content: left;">
                <h6 class="text-sm descricao" id="textoCliente">${parametro.find('td')[1].textContent}</h6>
              </div>
            </div>
            <div class="col-md-3" style="font-size: 1rem; text-align: center; display: flex;">
              <div class="form-group p-2" style="margin: 0; display: flex; align-items: center; justify-content: center;">
                <div class="flex items-center text-sm">
                  <button class="text-gray-700 font-semibold rounded-full decrement bg-purple flex items-center justify-center w-5 h-5">-</button>
                  <input type="text" class="border-gray-200 rounded-none w-8 text-center quantity" value="1">
                  <button class="text-gray-700 font-semibold rounded-full increment bg-purple flex items-center justify-center w-5 h-5">+</button>
                </div>
              </div>
            </div>
            <div class="col-md-4 p-2 classePreco" style="margin: 0; font-size: 1rem; text-align: right; display: flex; align-items: center; justify-content: right;">
              <div class=" text-sm">
              <p class="border-gray-200 rounded-none text-center  float-right total">${parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</P>
            </div>
          </div>
        </div>
      </div>
      </div>
      </div>
      <div class="action-button delete">
                <span class="text">Apagar</span>
            </div>
        </article>
      `;
                console.log("Primeiro");

                $('#linhaArtigo').append(select);
                initSwipeable();
                let decremento = document.querySelectorAll('.decrement');
                let incremento = document.querySelectorAll('.increment');
                let qtd = document.querySelectorAll('.quantity');
                let total = document.querySelectorAll('.total');

                decremento[decremento.length - 1].addEventListener("click", function(e) {
                    if (qtd[decremento.length - 1].value > 1) {
                        qtd[decremento.length - 1].value = parseInt(qtd[decremento.length - 1].value) - 1;
                        total[decremento.length - 1].innerText = parseFloat(qtd[decremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.'));
                        total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                        totalDocumento();
                    }
                });
                incremento[incremento.length - 1].addEventListener("click", function(e) {
                    qtd[incremento.length - 1].value = parseInt(qtd[incremento.length - 1].value) + 1;
                    total[incremento.length - 1].innerText = parseFloat(qtd[incremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.'));
                    total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                    totalDocumento();
                });
            }
            totalDocumento();
        } else {
            let select = `
            <article class="swipeable">
            <div class="inner">
      <div class="linha" data-linha="${parametro.find('td')[0].textContent}" style="border-bottom: 1px solid #e5e7eb; padding: 0;">
        <div class="col-md-12">
          <div style="display: flex; justify-content: space-between;">
            <div class="col-md-5" style="padding-left: 0;">
              <div class="form-group p-2" style="font-size: 1rem; margin: 0; display: flex; align-items: center; justify-content: left;">
                <h6 class="text-sm descricao" id="textoCliente">${parametro.find('td')[1].textContent}</h6>
              </div>
            </div>
            <div class="col-md-3" style="font-size: 1rem; text-align: center; display: flex;">
              <div class="form-group p-2" style="margin: 0; display: flex; align-items: center; justify-content: center;">
                <div class="flex items-center text-sm">
                  <button class="text-gray-700 font-semibold rounded-full decrement bg-purple flex items-center justify-center w-5 h-5">-</button>
                  <input type="text" class="border-gray-200 rounded-none w-8 text-center quantity" value="1">
                  <button class="text-gray-700 font-semibold rounded-full increment bg-purple flex items-center justify-center w-5 h-5">+</button>
                </div>
              </div>
            </div>
            <div class="col-md-4 p-2 classePreco" style="margin: 0; font-size: 1rem; text-align: right; display: flex; align-items: center; justify-content: right;">
              <div class=" text-sm">
              <p class="border-gray-200 rounded-none text-center  float-right total">${parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</P>
            </div>
          </div>
        </div>
      </div>
      </div>
      </div>
           <div class="action-button delete">
                <span class="text">Apagar</span>
            </div> 
        </article>
      `;
            console.log("Segundo");

            $('#linhaArtigo').append(select);
            initSwipeable();

            let decremento = document.querySelectorAll('.decrement');
            let incremento = document.querySelectorAll('.increment');
            let qtd = document.querySelectorAll('.quantity');
            let total = document.querySelectorAll('.total');

            decremento[decremento.length - 1].addEventListener("click", function(e) {
                if (qtd[decremento.length - 1].value > 1) {
                    qtd[decremento.length - 1].value = parseInt(qtd[decremento.length - 1].value) - 1;
                    total[decremento.length - 1].innerText = parseFloat(qtd[decremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.'));
                    total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                    totalDocumento();
                }
            });
            incremento[incremento.length - 1].addEventListener("click", function(e) {
                qtd[incremento.length - 1].value = parseInt(qtd[incremento.length - 1].value) + 1;
                total[incremento.length - 1].innerText = parseFloat(qtd[incremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.find('td')[2].textContent.replace(/\ /g, '').replace(/\,/g, '.'));
                total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                totalDocumento();
            });
        }
    }

    function funcaoSearchCliente(parametro) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            codigoEntidade: parametro,
            idTipoEntidade: 2
        }, "viewEntidade", function success(data) {
            console.log("Dados: ", data);
            let small = $('#searchCliente').closest('.col-md-12').find('small');
            if (data != null) {
                document.querySelector('#textoCliente').innerText = data[0]["nome"];
                small.css('visibility', 'hidden');
                searchCliente.value = data[0]["codigoEntidade"];
            } else {
                document.querySelector('#textoCliente').innerText = "Consumidor Final";
                small.css('visibility', 'visible');
                small.text('Cliente Inexistente');
                small.css('color', '#dc3545');
            }
        }, function error(data) {

        }, function done(data) {

        });
    }

    funcaoSelect("includes/select.inc.php", "post", "json", "familia", function success(data) {
        console.log(data);
        let select = "";
        for (let i = 0; i < data.length; i++) {
            select += `
      <li class="text-gray-300 text-sm flex items-center gap-x-4 cursor-pointer p-2 hover:bg-light-white rounded-md mt-2 linhaFamilia" data-familia="${data[i]["idFamilia"]}">
                        <span class="origin-left duration-200">${data[i]["nome"]}</span>
                    </li>
      `;
        }
        $('#cardFamilia').html(select);
    }, function error(data) {

    }, function done(data) {
        loadClickedFamilia();
    });

    async function loadCardArtigo(data) {
        let select = "";
        $('#containerCardProduct').html(`<div class="flex flex-col flex-1">
                    <section class="px-4">
                        <div class="grid grid-cols-2 md:grid-cols-5 gap-x-6" id="cardContainer">
                        </div>
                    </section>
                </div>`);
        for (let i = 0; i < data.length; i++) {
            select += `
            <article class="rounded-2xl border border-gray-200 cardArtigo mt-4 cursor-pointer" style="overflow: hidden;" data-artigo="${data[i]["idArtigo"]}">
                                <div class="flex justify-center items-center aspect-square bg-white p-2">
                                    <div style=" background-image: url(./images/artigo/${data[i]["imagem"] != null ? data[i]["imagem"] : "product.svg"}); background-size: contain; background-position: center; background-repeat: no-repeat;" class="h-28 w-28"></div>
                                </div>
                                <div class="flex flex-col p-2">
                                    
                                        <h2 class="font-semibold tracking-wide text-base">${data[i]["nome"]}</h2>
                                        
                                    <span class="text-sm text-gray-500">
                                        Preço: <span class="text-sm font-semibold tracking-wide text-gray-800 text-base">${data[i]["precoComImposto"] + moeda}</span>
                                    </span>
                                    <div class="flex items-center justify-between">
                                    <span class="text-sm text-gray-500">
                                        Stock: <span class="text-sm font-semibold tracking-wide text-gray-800 text-base">${data[i]["stock"]}</span>
                                        </span>
                                        <span class="text-sm font-semibold tracking-wide ${data[i]["stock"] <= 0 ? "text-red-700" : "text-green-700"}">
                                        ${data[i]["stock"] <= 0 ? "Indisponível" : "Disponível"}
                                        </span>
                                    </div>
                                </div>
                            </article>
        `;
        }
        $('#cardContainer').html(select);
    }

    async function getDefinicao() {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoSelect("includes/select.inc.php", "post", "json", "definicao", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }
    async function getQueryArtigoFamilia(familia) {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                    idFamilia: familia
                }, "viewartigousuariofamilia", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }

    async function getQueryArtigo(artigo) {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                    idArtigo: artigo
                }, "viewartigousuariofamilia", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }

    async function getArtigo() {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoSelect("includes/select.inc.php", "post", "json", "viewartigousuariofamilia", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }

    async function getPreco(artigo, linhaPreco) {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                    idArtigo: artigo,
                    indice: linhaPreco
                }, "precoArtigo", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }

    async function getStock(artigo) {
        try {
            let resultado = await new Promise(function(sucesso, erro) {
                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                    idArtigo: artigo
                }, "artigoStock", function success(data) {
                    sucesso(data);
                }, function error(data) {
                    erro(data);
                }, function done(data) {

                });
            });
            return resultado;
        } catch (erro) {
            throw erro;
        }
    }

    function totalDocumento() {
        let all = 0;
        let total = document.querySelectorAll(".total");
        for (let i = 0; i < total.length; i++) {
            if (total[i].innerText != "") {
                all += parseFloat(total[i].innerText.replace(/\ /g, '').replace(/\,/g, '.'));
            }
        }
        totalAbsoluto.innerText = parseFloat(all).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
        totalValor.innerText = parseFloat(all).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
        totalDoc = all;
    }

    function loadClickedFamilia() {
        $('.linhaFamilia').on('click', function(e) {
            e.preventDefault();
            let linha = document.querySelectorAll('.linhaFamilia');
            for (let i = 0; i < linha.length; i++) {
                linha[i].classList.remove('bg-light-white');
            }
            $(this).addClass('bg-light-white');
            getDefinicao()
                .then(dataDefinicao => {
                    getQueryArtigoFamilia($(this).attr('data-familia')).then(dataArtigo => {
                        if (dataArtigo != null) {
                            let promises = [];
                            for (let i = 0; i < dataArtigo.length; i++) {
                                let precoPromise = getPreco(dataArtigo[i]["idArtigo"], dataDefinicao[1]["valor"]);
                                let stockPromise = getStock(dataArtigo[i]["idArtigo"]);

                                promises.push(precoPromise);
                                promises.push(stockPromise);
                            }

                            Promise.all(promises).then(results => {

                                for (let i = 0; i < dataArtigo.length; i++) {
                                    let precoIndex = i * 2;
                                    let stockIndex = i * 2 + 1;

                                    dataArtigo[i].precoSemImposto = parseFloat(results[precoIndex][0]['semImposto']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                                    dataArtigo[i].precoComImposto = parseFloat(results[precoIndex][0]['semImposto']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                                    dataArtigo[i].stock = parseFloat(results[stockIndex][0]["qtdDisponivel"]).toFixed(0).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                                }
                                loadCardArtigo(dataArtigo).then(function(data) {
                                    $('.cardArtigo').on('click', function(e) {
                                        e.preventDefault();
                                        loadClickedArtigo($(this).attr('data-artigo'));
                                    });
                                });
                            }).catch(erro => {
                                console.error('Erro: ', erro);
                            });
                        } else {
                            let select = `
                            <div class="flex flex-col flex-1  h-full mx-80" style="background-image: url('./images/logo/logo.png'); background-size: contain; background-position: center; background-repeat: no-repeat;"></div>
                            `;
                            $('#containerCardProduct').html(select);
                        }
                    }).catch(erro => {
                        console.error('Erro:', erro);
                    });
                })
                .catch(erro => {
                    console.error('Erro:', erro);
                });
        });
    }

    function loadClickedArtigo(parametro) {
        getDefinicao()
            .then(dataDefinicao => {
                getQueryArtigo(parametro).then(dataArtigo => {
                    getPreco(dataArtigo[0]["idArtigo"], dataDefinicao[1]["valor"]).then(dataPreco => {
                        let resultado = mesmoArtigoVerify(parametro);
                        if (resultado.length > 0) {
                            var elementos = valoresDuplicados.filter(function(valor) {
                                return valor == dataArtigo[0]["idArtigo"];

                            });
                            if (elementos.length > 0) {
                                let linha = document.querySelector('#linhaArtigo').querySelectorAll('.linha');
                                for (let i = 0; i < linha.length; i++) {
                                    if (parseInt(dataArtigo[0]["idArtigo"]) === parseInt(linha[i].getAttribute('data-linha'))) {
                                        let valor = linha[i].querySelector('.quantity');
                                        if (valor.value == "") {
                                            valor.value = 1;
                                        } else {
                                            valor.value = parseInt(valor.value) + 1;
                                            totalDocumento();
                                        }
                                        linha[i].querySelector('.total').innerText = parseFloat(linha[i].querySelector('.quantity').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(dataPreco[0]["comImposto"].replace(/\ /g, '').replace(/\,/g, '.'));
                                        linha[i].querySelector('.total').innerText = parseFloat(linha[i].querySelector('.total').innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                                    }
                                }
                                totalDocumento();
                            } else {
                                calcLinhas(dataArtigo, dataPreco);
                            }
                            totalDocumento();

                        } else {
                            calcLinhas(dataArtigo, dataPreco);
                        }
                    });
                }).catch(erro => {
                    console.error('Erro: ', erro);
                });

            }).catch(erro => {
                console.error('Erro: ', erro);
            });
    }

    function initSwipeable() {
        $('.swipeable').each(function() {
            if (!$(this).hasClass('initialized')) {
                $(this).addClass('initialized');
                $(this).on('click', function() {
                    $(this).find('.classePreco').on('click', () => {
                        var snapper = new Snap({
                            element: this.querySelector('.inner'),
                            maxPosition: 100,
                            minPosition: -100
                        });
                        if (snapper.state().state === 'closed') {
                            snapper.open('right');
                        } else {
                            snapper.close();
                        }
                    });

                });

                $(this).find('.delete').on('click', function() {
                    let numero = $(this).closest('article').find('.linha').attr('data-linha');
                    valores = valores.filter(valor => valor !== numero);
                    valoresDuplicados = valoresDuplicados.filter(valor => valor !== numero);
                    $(this).closest('article').slideToggle(100);
                    setTimeout(() => {
                        $(this).closest('article').remove();
                        totalDocumento();
                    }, 200);
                });
            }
        });
    }

    function calcLinhas(dataArtigo, dataPreco) {
        let select = `

        <article class="swipeable">
            <div class="inner">
                <div class="linha" data-linha="${dataArtigo[0]["idArtigo"]}" style="border-bottom: 1px solid #e5e7eb; padding: 0;">
                  <div class="col-md-12">
                    <div style="display: flex; justify-content: space-between;">
                      <div class="col-md-5" style="padding-left: 0;">
                        <div class="form-group p-2" style="font-size: 1rem; margin: 0; display: flex; align-items: center; justify-content: left;">
                          <h6 class="text-sm descricao" id="textoCliente">${dataArtigo[0]["nome"]}</h6>
                        </div>
                      </div>
                      <div class="col-md-3" style="font-size: 1rem; text-align: center; display: flex;">
                        <div class="form-group p-2" style="margin: 0; display: flex; align-items: center; justify-content: center;">
                          <div class="flex items-center text-sm">
                            <button class="text-gray-700 font-semibold rounded-full decrement bg-purple flex items-center justify-center w-5 h-5">-</button>
                            <input type="text" class="border-gray-200 rounded-none w-8 text-center quantity" value="1">
                            <button class="text-gray-700 font-semibold rounded-full increment bg-purple flex items-center justify-center w-5 h-5">+</button>
                          </div>
                        </div>
                      </div>
                      <div class="col-md-4 p-2 classePreco" style="margin: 0; font-size: 1rem; text-align: right; display: flex; align-items: center; justify-content: right;">
                        <div class=" text-sm">
                        <p class="border-gray-200 rounded-none text-center  float-right total">${parseFloat(dataPreco[0]["comImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda}</P>
                      </div>
                    </div>
                  </div>
                </div>
                </div>
                </div>
            <div class="action-button delete">
                <span class="text">Apagar</span>
            </div>
            <div class="action-button delete">
                <span class="text">Apagar</span>
            </div>
        </article>
                `;
        $('#linhaArtigo').append(select);
        initSwipeable();
        let decremento = document.querySelectorAll('.decrement');
        let incremento = document.querySelectorAll('.increment');
        let qtd = document.querySelectorAll('.quantity');
        let total = document.querySelectorAll('.total');

        decremento[decremento.length - 1].addEventListener("click", function(e) {
            if (qtd[decremento.length - 1].value > 1) {
                qtd[decremento.length - 1].value = parseInt(qtd[decremento.length - 1].value) - 1;
                total[decremento.length - 1].innerText = parseFloat(qtd[decremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(dataPreco[0]["comImposto"].replace(/\ /g, '').replace(/\,/g, '.'));
                total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                totalDocumento();
            }
        });
        incremento[incremento.length - 1].addEventListener("click", function(e) {
            qtd[incremento.length - 1].value = parseInt(qtd[incremento.length - 1].value) + 1;
            total[incremento.length - 1].innerText = parseFloat(qtd[incremento.length - 1].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(dataPreco[0]["comImposto"].replace(/\ /g, '').replace(/\,/g, '.'));
            total[decremento.length - 1].innerText = parseFloat(total[decremento.length - 1].innerText).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
            totalDocumento();
        });
        totalDocumento();
    }

    $(document).ready(() => {
        getDefinicao()
            .then(dataDefinicao => {
                getArtigo().then(dataArtigo => {
                    let promises = [];
                    for (let i = 0; i < dataArtigo.length; i++) {
                        let precoPromise = getPreco(dataArtigo[i]["idArtigo"], dataDefinicao[1]["valor"]);
                        let stockPromise = getStock(dataArtigo[i]["idArtigo"]);

                        promises.push(precoPromise);
                        promises.push(stockPromise);
                    }

                    Promise.all(promises).then(results => {

                        for (let i = 0; i < dataArtigo.length; i++) {
                            let precoIndex = i * 2;
                            let stockIndex = i * 2 + 1;

                            dataArtigo[i].precoSemImposto = parseFloat(results[precoIndex][0]['semImposto']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                            dataArtigo[i].precoComImposto = parseFloat(results[precoIndex][0]['comImposto']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                            dataArtigo[i].stock = parseFloat(results[stockIndex][0]["qtdDisponivel"]).toFixed(0).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                        }

                        loadCardArtigo(dataArtigo).then(function(data) {
                            $('.cardArtigo').on('click', function(e) {
                                e.preventDefault();
                                loadClickedArtigo($(this).attr('data-artigo'));
                            });
                        });
                        loadListagemArtigo(dataArtigo);
                    });
                }).catch(erro => {
                    console.error('Erro:', erro);
                });
            })
            .catch(erro => {
                console.error('Erro:', erro);
            });
    });


    function loadListagemArtigo(data) {
        $("#tabelaArtigoListagem").DataTable({
            select: 'single',
            "aaData": data,
            "columns": [{
                data: "idArtigo"
            }, {
                data: "nome"
            }, {
                data: "precoComImposto"
            }, {
                data: "stock"
            }],
            columnDefs: [{
                targets: -1,
                orderable: false
            }],
            "responsive": true,
            "lengthChange": false,
            "autoWidth": false,
            "language": idiomaPortugues,
            lengthMenu: [
                [7, 25, 50, -1],
                [10, 25, 50, 'All']
            ],
        }).buttons().container().appendTo('#tabelaArtigoListagem_wrapper .col-md-6:eq(0)');
    }
    /*
    for (let i = 0; i < data.length; i++) {
          funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idArtigo: data[i]["idArtigo"],
            indice: linhaPreco
          }, "precoArtigo", function success(data) {
            
          }, function error(data) {

          }, function done(data) {

          });
        }*/

    funcaoSelect("includes/select.inc.php", "post", "json", "definicao", function success(data) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idMoeda: data[4]["valor"]
        }, "moeda", function success(data) {
            moeda = data[0]["simbolo"];
            totalAbsoluto.innerText = "0,00" + moeda;
            entregueValor.innerText = "0,00" + moeda;
            totalValor.innerText = "0,00" + moeda;

        }, function error(data) {

        }, function done(data) {

        });
    }, function error(data) {

    }, function done(data) {});

    function loadTabelaArtigo(linhaPreco, callback) {
        let tabela;
        let iteracao = 0;
        funcaoSelect("includes/select.inc.php", "post", "json", "viewartigousuariofamilia", function success(data) {
            tabela = data;
            for (let i = 0; i < data.length; i++) {
                tabela[i].precoComImposto = 0;
                tabela[i].precoSemImposto = 0;
                tabela[i].stock = 0;
                funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                    idArtigo: data[i]["idArtigo"],
                    indice: linhaPreco
                }, "precoArtigo", function success(data) {
                    if (data != null) {
                        tabela[i].precoComImposto = data[0]['semImposto'] + moeda;
                        tabela[i].precoSemImposto = data[0]['comImposto'] + moeda;
                    } else {
                        tabela[i].precoComImposto = 0;
                        tabela[i].precoSemImposto = 0;
                    }
                    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
                        idArtigo: tabela[i]["idArtigo"]
                    }, "artigoStock", function success(data) {
                        if (data != null) {
                            tabela[i].stock = data[0]['qtdDisponivel'];
                        } else {
                            tabela[i].stock = 0;
                        }
                    }, function error(data) {

                    }, function done(data) {

                    });
                }, function error(data) {

                }, function done(data) {

                });
                iteracao = iteracao + 1;
            }
            if (iteracao == data.length) {
                setTimeout(function() {
                    callback(tabela);
                }, 3000);
            }
        }, function error(data) {

        }, function done(data) {});
    }

    function detalhes(id) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idEntidade: id
        }, "viewEntidade", function success(data) {
            for (var key in data) {
                nomeModal.innerText = data[key]["nome"];
                codigoInfo.innerText = data[key]["idTipoUsuario"];
                nomeInfo.innerText = data[key]["nome"];
                notaInfo.innerText = data[key]["nota"];
            }
        }, function error(data) {

        }, function done(data) {

        });
    }
    botaoOutrasOpcoes(document.querySelectorAll(".btn-opcao"));
    linhaSelecionada("tabelaCliente", document.querySelector("#btnSelectCliente"));
    linhaSelecionada("tabelaArtigoListagem", document.querySelector("#btnSelectArtigo"));
    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
        idTipoEntidade: 2
    }, "viewEntidade", function success(data) {
        $("#tabelaCliente").DataTable({
            select: 'single',
            "aaData": data,
            "columns": [{
                data: "codigoEntidade"
            }, {
                data: "nome"
            }, {
                data: "nomeComercial"
            }, {
                data: "bi"
            }, {
                data: "nif"
            }, {
                data: "localidade"
            }, {
                data: "morada"
            }],
            columnDefs: [{
                targets: -1,
                orderable: false
            }],
            "responsive": true,
            "lengthChange": false,
            "autoWidth": false,
            "language": idiomaPortugues,
            lengthMenu: [
                [7, 25, 50, -1],
                [10, 25, 50, 'All']
            ],
        }).buttons().container().appendTo('#tabelaCliente_wrapper .col-md-6:eq(0)');
    }, function error(data) {

    }, function done(data) {

    });


    $(document).on("click", "#btn-preview", function(e) {
        e.preventDefault();
        $('#modal-updateTipoEntidade').modal('show');
    });

    $('#tabelaCliente').on('click', '.btn-more', function(e) {
        e.preventDefault();
        $('#modal-updateTipoEntidade').modal('show');
        detalhes($(this).closest('tr').find('td')[0].textContent);
    });

    let id = {
        idCodigoTaxa: 1
    }
    let tabela = "tipoUsuario";

    function updateLinha(id, tabela) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", id, tabela, function success(data) {
            for (var key in data) {
                linha[1].innerText = data[key]["nome"];
                linha[2].innerText = data[key]["nota"];
            }
        }, function error(data) {

        }, function done(data) {

        });
    }

    function insertLinha(id, tabela) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", id, tabela, function success(data) {
            for (var key in data) {
                var novaLinha = {
                    idTipoUsuario: data[key]["idTipoUsuario"],
                    nome: data[key]["nome"],
                    nota: data[key]["nota"],
                };
                $('#tabelaCliente').DataTable().row.add(novaLinha).draw(false);
            }
        }, function error(data) {

        }, function done(data) {

        });
    }

    $('#btnSearchCliente').on("click", function(e) {
        e.preventDefault();
        $('#modal-cliente').modal('show');
    });

    $(document).ready(function() {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idUsuario: <?php echo $_SESSION["usuarioId"]; ?>
        }, "usuario", function success(data) {
            imagemUsuarioT.src = "../gestao/images/usuario/" + data[0]["imagem"];
            imagemUsuario.src = "../gestao/images/usuario/" + data[0]["imagem"];
            nomeUsuario.innerText = data[0]["nome"].toUpperCase();
            $('#username').val(data[0]["nome"].toUpperCase()); 
            $('#nomeUse').val(data[0]["nome"].toUpperCase()); 
        }, function error(data) {

        }, function done(data) {

        });
        funcaoSelect("includes/select.inc.php", "post", "json", "modoPagamento", function success(data) {
            let select = "";
            for (let i = 0; i < data.length; i++) {
                select += `
          <tr id="${data[i]['idModoPagamento']}">
            <td style="border: none !important; width: 10%; vertical-align: middle;">${data[i]['idModoPagamento']}</td>
            <td style="border: none !important; width: 70%; vertical-align: middle;">${data[i]['nome']}</td>
            <td style="border: none !important; width: 20%;" vertical-align: middle;>
              <input type="text" class="form-control mp" placeholder="0,00">
            </td>
          </tr>`;
            }
            $("#modoPagamentoBody").html(select);

            let modoPagamento = document.querySelectorAll('.mp');
            separadorMilhares(modoPagamento);
            for (let i = 0; i < modoPagamento.length; i++) {
                modoPagamento[i].addEventListener("keyup", function() {
                    sumCampoTotal(modoPagamento, entregueValor, entregueTexto, totalValor, totalTexto, totalDoc, moeda);
                });
            }

        }, function error(data) {

        }, function done(data) {

        });
    });

    $(document).on("click", ".submit", function(e) {
        e.preventDefault();
        if (nome.value != '') {
            //tipoUsuario();
        }
    });

    $(document).on("click", "#btn", function(e) {
        e.preventDefault();
        doOpcao.innerText = "Novo Cliente";
        funcaoReload(document.querySelector(".submit"));

        $('#modal-formCliente').modal('show');
    });

    function tipoUsuario() {
        let dados = {
            nome: nome.value,
            nota: nota.value,
        };
        let tabela = "tipoUsuario";
        if (doOpcao.innerText == "Novo Cliente") {
            funcaoInsert("includes/insert.inc.php", "post", "json", tabela, dados, function success(data) {
                swal.fire({
                    title: "Cadastro efectuado com sucesso!",
                    text: "Cliente " + nome.value + " cadastrado!",
                    confirmButtonText: 'Confirmar',
                    confirmButtonColor: '#560085',
                    icon: "success",
                });
                insertLinha({
                    idTipoUsuario: data
                }, tabela);
                funcaoReload(document.querySelector(".submit"));
            }, function error(data) {
                swal.fire({
                    title: "Erro ao cadastrar Cliente!",
                    text: "Erro ao cadastrar Cliente: " + nome.value + " !",
                    confirmButtonText: 'Confirmar',
                    confirmButtonColor: '#560085',
                    icon: "error",
                });
            }, function done(data) {

            });
        } else {
            funcaoUpdate("includes/update.inc.php", "post", "json", tabela, dados, {
                idTipoUsuario: codigo.innerText
            }, function success(data) {
                swal.fire({
                    title: "Informações Actualizadas com sucesso!",
                    text: "Cliente " + nome.value + ".",
                    confirmButtonText: 'Confirmar',
                    confirmButtonColor: '#560085',
                    icon: "success",
                });
                updateLinha({
                    idTipoUsuario: codigo.innerText
                }, tabela);
                funcaoReload(document.querySelector(".submit"));
            }, function error(data) {
                console.log("Erro: ", data);
                swal.fire({
                    title: "Erro ao actualizar Cliente!",
                    text: "Erro ao actualizar Cliente: " + nome.value + " !",
                    confirmButtonText: 'Confirmar',
                    confirmButtonColor: '#560085',
                    icon: "error",
                });
            }, function done(data) {

            });
        }
    }

    $('#tabelaArtigoListagem').on('click', 'tbody td', function(e) {
        e.preventDefault();
        artigoSelecionado = $(this).closest('tr');
    });

    $('#tabelaArtigoListagem').on('dblclick', 'tbody td', function(e) {
        e.preventDefault();
        funcaoSearchArtigo($(this).closest('tr'));
        $('#modal-artigo').modal('hide');
    });

    $('#btnSelectArtigo').on('click', function(e) {
        e.preventDefault();
        funcaoSearchArtigo(artigoSelecionado);
        $('#modal-artigo').modal('hide');
    });

    $('#tabelaCliente').on('click', 'tbody td', function(e) {
        e.preventDefault();
        clienteSelecionado = $(this).closest('tr').find('td')[0].textContent;
    });

    $('#tabelaCliente').on('dblclick', 'tbody td', function(e) {
        e.preventDefault();
        funcaoSearchCliente($(this).closest('tr').find('td')[0].textContent);
        $('#modal-cliente').modal('hide');
    });

    $('#btnSelectCliente').on('click', function(e) {
        e.preventDefault();
        funcaoSearchCliente(clienteSelecionado);
        $('#modal-cliente').modal('hide');
    });


    function mesmoArtigoVerify(referencia) {

        for (let i = 0; i < referencia.length; i++) {
            if (referencia[i] !== "") {
                valores.push(referencia[i]);
            }
        }

        for (let i = 0; i < valores.length; i++) {
            for (let j = i + 1; j < valores.length; j++) {
                if (valores[i] === valores[j] && !valoresDuplicados.includes(valores[i])) {
                    valoresDuplicados.push(valores[i]);
                }
            }
        }

        return valoresDuplicados;
    }

    $(document).ready(function() {
        funcaoSelect("includes/select.inc.php", "post", "json", "tipoEntidade", function success(data) {
            let select = "";
            select += "<option value='0'>Selecione Tipo de Entidade</option>";
            for (var key in data) {
                select += "<option value=" + data[key]['idTipoEntidade'] + ">" + data[key]['nome'] + "</option>";
            }
            $("#idTipoEntidade").html(select);
        }, function error(data) {

        }, function done(data) {
            $('#idTipoEntidade').attr('disabled', 'disabled');
            $('#idTipoEntidade').val(2);
            $('#idTipoEntidade').select2().trigger('change');
        });
        funcaoSelect("includes/select.inc.php", "post", "json", "definicao", function success(data) {
            let select = "";
            select += `<option value="0">Definição do Sistema</option>`;
            for (var key in data) {
                if (data[key]["idDefinicao"] == 1) {
                    for (let i = 0; i < data[key]["valor"]; i++) {
                        select += `<option value="${i + 1}">P.Venda (${i + 1})</option>`;
                    }
                }
            }
            $("#linhaPrecoPredefinida").html(select);
        }, function error(data) {

        }, function done(data) {

        });
    });

    $('#tabelaCliente').on('click', '.btn-update', function(e) {
        e.preventDefault();
        linha = $(this).closest('tr').find('td');
        doOpcao.innerText = "Editar Cliente";
        resetForm(document.querySelector(".slidePage"));
        $('#modal-formCliente').modal('show');
        let id = $(this).closest('tr').find('td')[0].textContent;
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idTipoUsuario: id
        }, "tipoUsuario", function success(data) {
            for (var key in data) {
                codigo.innerText = data[key]["idTipoUsuario"];

                if (data[key]["nome"] != "") {
                    nome.value = data[key]["nome"];
                } else {
                    nome.value = "";
                }

                if (data[key]["nota"] != "") {
                    nota.value = data[key]["nota"];
                } else {
                    nota.value = "";
                }
            }
        }, function error(data) {

        }, function done(data) {

        });
    });

    $('#tabelaCliente').on('click', '.btn-delete', function(e) {
        e.preventDefault();
        linha = $(this).closest('tr').find('td');
        let id = $(this).closest('tr').find('td')[0].textContent;
        let nome = $(this).closest('tr').find('td')[1].textContent;
        swal.fire({
                title: "Tem a certeza que pretende eliminar Cliente?",
                text: "Cliente: " + nome,
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: 'Confirmar',
                confirmButtonColor: '#560085',
                cancelButtonText: 'Cancelar',
                cancelButtonColor: '#560085',
            })
            .then((result) => {
                if (result.isConfirmed) {
                    funcaoDelete("includes/delete.inc.php", "post", "json", tabela, {
                        idTipoUsuario: id
                    }, function success(data) {
                        console.log(data);
                        swal.fire({
                            title: "Cliente " + nome + " eliminado com sucesso!",
                            icon: "success",
                            confirmButtonText: 'Confirmar',
                            confirmButtonColor: '#560085',
                        });
                        $('#tabelaCliente').DataTable().row(linha).remove().draw(false);
                        funcaoReload(document.querySelector(".submit"));
                    }, function error(data) {
                        console.log(data);
                        swal.fire({
                            title: "Erro ao eliminar Cliente!",
                            text: "Cliente associado a uma ou mais Documentos.",
                            icon: "error",
                            confirmButtonText: 'Confirmar',
                            confirmButtonColor: '#560085',
                        });
                    }, function done(data) {

                    });
                }
            });
    });

    $(document).on('keydown', '.quantity', function(e) {
        let totalLinha = 0;
        getDefinicao()
            .then(dataDefinicao => {
                getQueryArtigo($(this).closest('.linha').data('linha')).then(dataArtigo => {
                    getPreco(dataArtigo[0]["idArtigo"], dataDefinicao[1]["valor"]).then(dataPreco => {
                        console.log("Pegar o preço: ", dataPreco);
                        if ($(this).val() !== '') {
                            totalLinha = parseFloat(parseInt($(this).val()) * parseFloat(dataPreco[0]["comImposto"].replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + moeda;
                            $(this).closest('article').find('.total')[0].innerText = totalLinha;
                        }
                    });
                });
            });
        setTimeout(() => {
            totalDocumento();
        }, 500);
    });

    function loadNovoId() {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            tipoDocumento: "venda",
            natureza: "facturaRecibo"
        }, "tipoDoc", function success(data) {
            tipoDocumento = data[0]['tipoDoc'];
            funcaoCount("includes/count.inc.php", "post", "json", "documento", {
                idTipoDoc: data[0]['tipoDoc']
            }, function success(data) {
                console.log("Pegar: ", data);
                codigoDocumento.innerText = "FR " + serie + "/" + parseFloat(parseInt(data[0]["COUNT(*)"]) + parseInt(1));
            }, function error(data) {

            }, function done(data) {

            });
        }, function error(data) {

        }, function done(data) {

        });
    }

    function EfectuarVenda() {
        let idUsuario = "<?php echo $_SESSION["usuarioId"]; ?>";
        let tipoDoc = tipoDocumento;
        let entidade = searchCliente.value !== '999999999' && searchCliente.value !== '' ? searchCliente.value : 1;
        let prazoPagamento = 1;
        let serie = idSerie;

        let entregueSpan = parseFloat(entregueValor.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let totalDocumento = parseFloat(totalAbsoluto.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let totalSpan = parseFloat(totalAbsoluto.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let opcaoTotalLiquido = 0;
        let opcaoTotalImposto = 0;
        let descontoGlobalValor = 0;

        $.ajax({
            url: "../gestao/includes/create/doc.inc.php",
            type: "post",
            dataType: "json",
            data: {
                idUsuario: idUsuario,
                idTipoDoc: tipoDoc,
                idEntidade: entidade,
                idPrazoPagamento: prazoPagamento,
                entregue: entregueSpan,
                total: totalDocumento,
                troco: totalSpan,
                totalLiquido: opcaoTotalLiquido,
                totalImposto: opcaoTotalImposto,
                descontoGlobal: descontoGlobalValor
            },
            success: function(data) {
                idDocumento = data;
                let id = data;
                let elementos = document.querySelectorAll('.linha');
                for (let i = 0; i < elementos.length; i++) {
                    let inputSearchArtigo = elementos[i].dataset.linha;
                    let qtd = elementos[i].querySelector('.quantity').value;
                    let preco = 0;
                    getDefinicao()
                        .then(dataDefinicao => {
                            getQueryArtigo(inputSearchArtigo).then(dataArtigo => {
                                getPreco(dataArtigo[0]["idArtigo"], dataDefinicao[1]["valor"]).then(dataPreco => {
                                    preco = dataPreco[0]['comImposto'];
                                });
                            });
                        });
                    let desconto = 0;
                    let imposto = 0;
                    let total = parseFloat(elementos[i].querySelector('.total').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
                    let taxa = 0;

                    $.ajax({
                        url: "../gestao/includes/create/artigoDocumento.inc.php",
                        type: "post",
                        dataType: "json",
                        data: {
                            idDocumento: id,
                            idArtigo: parseInt(inputSearchArtigo),
                            descricao: elementos[i].querySelector('.descricao').innerText,
                            qtd: elementos[i].querySelector('.quantity').value,
                            preco: preco,
                            desconto: desconto,
                            idImposto: 1,
                            imposto: 0,
                            total: total,
                        },
                        success: function(data) {
                            loadNovoId();
                        },
                        error: function(data) {

                        }
                    }).done(function(data) {

                    });
                }

                let table = document.getElementById("tabelaModoPagamento");
                for (i = 0; i < table.rows.length; i++) {
                    if (table.rows[i].querySelector('.mp').value != "") {
                        $.ajax({
                            url: "../gestao/includes/create/modoPagamentoDocumento.inc.php",
                            type: "post",
                            dataType: "json",
                            data: {
                                idModoPagamento: parseInt(table.rows[i].cells[0].innerText),
                                idDocumento: id,
                                valor: parseFloat(table.rows[i].querySelector('.mp').value.replace(/\ /g, '').replace(/\,/g, '.')),
                            },
                            success: function(data) {},
                            error: function(data) {},
                        });
                    }
                }
            },
            error: function(data) {

            }
        }).done(function(data) {});
    }
</script>