<!DOCTYPE html>
<html lang="pt">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <style>
        :root {
            --body-bg: rgb(204, 204, 204);
            --white: #ffffff;
            --darkWhite: #ccc;
            --black: #000000;
            --dark: #615c60;
            --themeColor: #560085;
            --pageShadow: 0 0 0.5cm rgba(0, 0, 0, 0.5);
        }

        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100&display=swap');

        body {
            background-color: var(--body-bg);
            -webkit-print-color-adjust: exact !important;
        }


        .page {
            background: var(--white);
            display: block;
            margin: 0 auto;
            position: relative;
            box-shadow: var(--pageShadow);
        }

        .page[size="A4"] {
            width: 21cm;
            min-height: 29.7cm;
            overflow: hidden;
        }

        .bb {
            border-bottom: 3px solid var(--darkWhite);
        }
        .invisible{
            display: none;
        }

        .top-content {
            padding-bottom: 15px;
        }

        .logo img {
            height: 30px;
        }

        .top-left p {
            margin: 0;
        }

        .top-left .graphic-path {
            height: 40px;
            position: relative;
        }

        .top-left .graphic-path::before {
            content: "";
            height: 20px;
            background-color: var(--dark);
            position: absolute;
            left: 15px;
            right: 0;
            top: -15px;
            z-index: 2;
        }

        .top-left .graphic-path::after {
            content: "";
            height: 22px;
            width: 17px;
            background: var(--black);
            position: absolute;
            top: -13px;
            left: 6px;
            transform: rotate(45deg);
        }

        .top-left .graphic-path p {
            color: var(--white);
            height: 40px;
            left: 0;
            right: -100px;
            text-transform: uppercase;
            background-color: var(--themeColor);
            font: 26px;
            z-index: 3;
            position: absolute;
            padding-left: 10px;
        }

        .store-user {
            padding-bottom: 25px;
        }

        .store-user p {
            margin: 0;
            font-weight: 600;
        }

        .store-user .address {
            font-weight: 400;
        }

        .store-user h2 {
            color: var(--themeColor);
            font-family: 'Rajdhani', sans-serif;
        }

        .extra-info p span {
            font-weight: 400;
        }

        .table td,
        .table th {
            text-align: center;
            vertical-align: middle;
        }

        tr th:first-child,
        tr td:first-child {
            text-align: left;
        }

        .media img {
            height: 60px;
            width: 60px;
        }

        .media p {
            font-weight: 400;
            margin: 0;
        }

        .media p.title {
            font-weight: 600;
        }

        .media-body>p {
            font-weight: 600;
        }

        .balance-info .table td,
        .balance-info .table th {
            padding: 0;
            border: 0;
        }

        .balance-info tr td:first-child {
            font-weight: 600;
        }

        tfoot {
            border-top: 2px solid var(--darkWhite);
        }

        tfoot td {
            font-weight: 600;
        }

        footer {
            text-align: center;
            position: absolute;
            bottom: 30px;
            left: 0;
            right: 0;
            background: var(--white);
            padding: 3rem;
        }

        footer hr {
            margin-bottom: -22px;
            border-top: 3px solid var(--darkWhite);
        }

        footer a {
            color: var(--themeColor);
        }

        @media print {

            .page,
            .page * {
                visibility: visible;
            }

            .page {
                position: absolute;
                left: 0;
                top: 0;
                box-shadow: none;
            }

            .my-5 {
                margin: 0 !important;
            }

            @page {
                margin: 0;
            }
        }

        .tabela thead td {
            background-color: #0000000d;
        }

        .tabela td {
            text-align: left;
        }

        .tabela-principal thead {
            font-weight: 600;
        }

        .tabela-principal thead td {
            background: none;
            border-bottom: 1px solid #000;
        }

        .tabela-principal td {
            border: none;
        }

        .marca-dagua {
            position: relative;
            width: 100%;
            height: 100%;
        }

        .marca-dagua::before {
            content: var(--content, '');
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 10rem;
            color: #bcbcbc;
        }
    </style>
</head>

<body>
    <div id="layout-doc-content">

    </div>

    <script src="template/plugins/jquery/jquery.min.js"></script>

    <script>
        // document.addEventListener("DOMContentLoaded", () => {
        //     const mainDoc = document.querySelector('#layout-doc-content');

        //     // Header section
        //     

        //     // Store-user section


        //     // Product-area section
        //     const productAreaSectionHTML = `
        //         <section class="product-area mt-4">
        //             <table class="tabela-principal table table-hover table-sm" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
        //                 <thead>
        //                     <tr>
        //                         <td>REF.</td>
        //                         <td>DESCRIÇÃO</td>
        //                         <td>QTD.</td>
        //                         <td>PREÇO</td>
        //                         <td>DESC.</td>
        //                         <td>IMPOSTO</td>
        //                         <td>TOTAL</td>
        //                     </tr>
        //                 </thead>
        //                 <tbody id="tabelaDocumento-1"></tbody>
        //             </table>
        //         </section>
        //     `;

        //     // Footer section
        //     const footerSectionHTML = `
        //         <footer>
        //             <section class="balance-info">
        //                 <div class="row">
        //                     <div class="col-12">
        //                         <p id="hashPrograma" style="float: left; font-weight: 500; font-size: 9pt; font-family: 'Noto Sans', sans-serif;"></p>
        //                     </div>
        //                     <div class="col-4 ml-auto">
        //                         <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 700;">
        //                             <span>Subtotal:</span>
        //                             <span id="subtotalDocumento" style="float: right; font-weight: 400;"></span>
        //                         </p>
        //                         <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 700;">
        //                             <span>Desconto:</span>
        //                             <span id="descontoDocumento" style="float: right; font-weight: 400;"></span>
        //                         </p>
        //                         <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 700;">
        //                             <span>Impostos:</span>
        //                             <span id="impostosDocumento" style="float: right; font-weight: 400;"></span>
        //                         </p>
        //                         <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 700;">
        //                             <span>Total:</span>
        //                             <span id="totalDocumento" style="float: right; font-weight: 400;"></span>
        //                         </p>
        //                     </div>
        //                 </div>
        //             </section>
        //             <div class="row mt-4">
        //                 <div class="col-4">
        //                     <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: center; font-weight: 700;">
        //                         ________________________<br>
        //                         <span style="font-size: 7pt;">Assinatura da Loja</span>
        //                     </p>
        //                 </div>
        //                 <div class="col-4 ml-auto">
        //                     <p style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: center; font-weight: 700;">
        //                         ________________________<br>
        //                         <span style="font-size: 7pt;">Assinatura do Cliente</span>
        //                     </p>
        //                 </div>
        //             </div>
        //         </footer>
        //     `;


        //     const A4 = `<div class="my-5 page marca-dagua" size="A4">`;

        //     const p5 = `<div class="p-5>` + headerSectionHTML + storeUserSectionHTML + productAreaSectionHTML + footerSectionHTML + `</div>`;

        //     // Append all sections to the main document
        //     mainDoc.innerHTML = A4 + p5 + `</div>`
        // });
    </script>


    <script>
        const docData = [];
        const lineDOCS = [];
        const mainDoc = document.querySelector('#layout-doc-content');

        function openDoc() {
            return `
                <div class="my-5 page marca-dagua" size="A4">
                    <div class="p-5">
            `;
        }

        function closeDoc(current, totalPaginas) {
            const paginateSectionHTML = `
                        <small class="d-flex justify-content-end mt-auto" style="top: 95%; right: 3rem; position: absolute;font-size: 6pt;">
                            ${current} de ${totalPaginas}
                        </small>
                    </div>
                </div>
            `;
            return paginateSectionHTML;
        }

        function funcaoSelect(url, type, dataType, tabela, success, error, done) {
            $.ajax({
                url: url,
                type: type,
                dataType: dataType,
                data: {
                    tabela: tabela
                },
                success: function(data) {
                    success(data);
                },
                error: function(data) {
                    error(data);
                }
            }).done(function(data) {
                done(data);
            });
        }

        function buildHeaderSection() {
            // console.log(docData);
            const headerSectionHTML = `
                <section class="top-content d-flex justify-content-between" style="padding-bottom: 0; padding-top: 1.5rem;">
                    <div class="col-7">
                        <div class="logo">
                            <img src="${'./images/logo/'+docData['configuracao']['logotipoDocumento']}" alt="" class="img-fluid" id="logotipoDocumento">
                        </div>
                    </div>
                    <div class="col-5">
                        <p style="font-size: 14pt; font-family: 'Noto Sans', sans-serif; text-align: justify; background-color: #560085; color: #fff; padding-left: .5rem;">
                            <span id="nomeTipoDocumento">Fatura</span>
                            <span id="codDocumento" style="float: right; padding-right: .5rem;">FT 1/2024</span>
                        </p>
                    </div>
                </section>
            `;
            return headerSectionHTML;
        }

        function buildStoreUserSection() {
                var niff = '';
            if (docData["outrosDocumento"]["nifDocumento"] == null || docData["outrosDocumento"]["nifDocumento"] == '999999999') {
                niff = 'Consumidor Final'
            }else{
                niff = docData["outrosDocumento"]["nifDocumento"];
            }
            const storeUserSectionHTML = `
                <section class="store-user" style="padding-bottom: 0;">
                    <div class="col-12">
                        <div class="row pb-3">
                            <div class="col-7">
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 400;" id="enderecoDocumento">${docData["configuracao"]["enderecoDocumento"]}</p>

                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 400;">Nº Contribuinte: <span id="nifDocumento">${docData["configuracao"]["nifDocumento"]}</span></p>

                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 400;">
                                    Telefone: <span id="telefoneDocumento">${docData["configuracao"]["telefoneDocumento"]}</span></p>

                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 400;">Email:
                                    <span id="emailDocumento">${docData["configuracao"]["emailDocumento"]}</span>
                                </p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; font-weight: 400;" id="websiteDocumento">${docData["configuracao"]["websiteDocumento"]}</p>
                            </div>

                            <div class="col-5">
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; margin-bottom: 0.3rem;">
                                    CLIENTE: <span style="font-weight: 400;" id="clienteDocumento">${docData["outrosDocumento"]["clienteDocumento"]}</span></p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify; margin-bottom: 0.3rem;">
                                    MORADA: <span style="font-weight: 400;" id="moradaDocumento">${docData["outrosDocumento"]["moradaDocumento"]}</span></p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">DATA
                                    EMISSÃO: <span style="font-weight: 400;" id="dataEmissaoDocumento">${docData["outrosDocumento"]["dataEmissaoDocumento"]}</span style="font-weight: 400;"> &nbsp; DATA VENCIMENTO: <span style="font-weight: 400;" id="dataVencimentoDocumento">${docData["outrosDocumento"]["dataVencimentoDocumento"]}</span></p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    DESCONTO: <span style="font-weight: 400;">0,00%</span></p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    PAGAMENTO: <span style="font-weight: 400;" id="modoPagamentoDocumento">${docData["outrosDocumento"]["modoPagamentoDocumento"]}</span></p>
                                <p style="font-size: 6pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">NIF:
                                    <span style="font-weight: 400;" id="nifDocumento">${niff}</span>
                                </p>
                            </div>
                        </div>
                    </div>
                </section>
            `;



            return storeUserSectionHTML;
        }

        var incideNOR = 0;
        var ipostoNOR = 0;
        var incideRED = 0;
        var ipostoRED = 0;
        var incideICB = 0;
        var ipostoICB = 0;
        var incideISE = 0;
        var ipostoISE = 0;
        var descrNOR = '';
        var descrRED = '';
        var descrICB = '';
        var descrISE = '';
        let imposto_i = 0;
        let motivo_isec = '';
        // var controlPageIterator = 1;
        var transporte = 0.00;

        function buildProductSection(totalPage, controlPageIterator, dataLine) {
            let row = "";
            let productSectionHTML = `
                <section class="product-area mt-4">
                    <table class="tabela-principal table table-hover table-sm" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                        <thead>
                            <tr>
                                <td>REF.</td>
                                <td>DESCRIÇÃO</td>
                                <td>QTD.</td>
                                <td>PREÇO/UNIT.</td>
                                <td>DESC.</td>
                                <td>TAXA(%)</td>
                                <td style="text-align: right !important">TOTAL</td>
                            </tr>
                        </thead>
                        <tbody id="tabelaDocumento-1">
            `;

            if (totalPage >= 2) {
                if (controlPageIterator > 1) {
                    for (const key in dataLine) {
                        transporte += parseFloat(dataLine[key]['totalAd']);
                    }
                    var transline = `
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td style="border: 1px solid #000; border-width: 1px 0 1px 0">transporte: ${transporte},00</td>
                        </tr>
                    `;
                    productSectionHTML += transline;
                    transporte = 0.00;
                }
            }

            for (const key in dataLine) {
                transporte += parseFloat(dataLine[key]['totalAd']);

                row = `
                    <tr>
                        <td>${dataLine[key]['idArtigoAd']}</td>
                        <td>${dataLine[key]['descricaoAd']}</td>
                        <td>${parseInt(dataLine[key]['qtdAd']).toFixed(0).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                        <td style="text-align: right !important">${parseFloat(dataLine[key]['precoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                        <td>${parseFloat(dataLine[key]['descontoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                        <td>${parseFloat(dataLine[key]['impostoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + ""}</td>
                        <td style="text-align: right !important">${parseFloat(dataLine[key]['totalAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                    </tr>
                `;

                if (dataLine[key]['idImposto'] == 1) {
                    incideNOR = Number(dataLine[key]['totalAd']) + incideNOR;
                    ipostoNOR = ((Number(dataLine[key]['totalAd']) * 14) / 100) + ipostoNOR;
                    console.log(dataLine[key]['imposto'])
                    descrNOR = dataLine[key]['nome'];
                } else if (dataLine[key]['idImposto'] == 2) {
                    incideRED = Number(dataLine[key]['totalAd']) + incideRED;
                    ipostoRED = ((Number(dataLine[key]['totalAd']) * 14) / 100) + ipostoRED;
                    descrRED = dataLine[key]['nome'];
                } else if (dataLine[key]['idImposto'] == 3) {
                    incideICB = Number(dataLine[key]['totalAd']) + incideICB;
                    ipostoICB = ((Number(dataLine[key]['totalAd']) * 14) / 100) + ipostoICB;
                    descrICB = dataLine[key]['nome'];
                } else if (dataLine[key]['idImposto'] == 4) {
                    imposto_i = dataLine[key]['idImposto'];
                    incideISE = Number(dataLine[key]['totalAd']) + incideISE;
                    ipostoISE = ((Number(dataLine[key]['totalAd']) * 14) / 100) + ipostoISE;
                    descrISE = dataLine[key]['nome'];
                }


                productSectionHTML += row;
            }
            if (totalPage >= 2) {
                if (controlPageIterator == 1) {
                    var transline = `
                        <tr>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td style="border: 1px solid #000; border-width: 1px 0 1px 0">A transportar: ${transporte},00</td>
                        </tr>
                    `;
                    productSectionHTML += transline;
                }
            }

            productSectionHTML += `
                        </tbody>
                    </table>
                </section>
            `;

            return productSectionHTML;
        }

        function buildFooter() {
            let incidNew = '';
            if (descrNOR != '') {
                incidNew = `<tr>
                                <td>${descrNOR}</td>
                                <td>14</td>
                                <td>${parseFloat(incideNOR).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                <td>${parseFloat(ipostoNOR).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                            </tr>`;
            }
            if (descrRED != '') {
                incidNew += `<tr>
                                <td>${descrRED}</td>
                                <td>7</td>
                                <td>${parseFloat(incideRED).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                <td>${parseFloat(ipostoRED).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                            </tr>`;
            }
            if (descrICB != '') {
                incidNew += `<tr>
                                <td>${descrICB}</td>
                                <td>5</td>
                                <td>${parseFloat(incideICB).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                <td>${parseFloat(ipostoICB).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                            </tr>`;
            }
            if (descrISE != '') {
                if (imposto_i != 0) {
                $.ajax({
                        url: "includes/read/queryDocumentoModoPagamento.inc.php",
                        type: "post",
                        dataType: "json",
                        data: {
                            motivo_isencao: 'motivo',
                            idImposto: imposto_i
                        },
                        success: function(data) {
                            console.log(data)
                            motivo_isec = data[0]['motivo'];
                            $('#motivo_isencao').text(motivo_isec)
                            $('#motivo_isencao').removeClass('invisible')
                            
                            
                        }, error: function(data){

                        } 
                    });
                }
                incidNew += `<tr>
                                <td>${descrISE}</td>
                                <td>0</td>
                                <td>${parseFloat(incideISE).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                <td>${parseFloat(ipostoICB).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                            </tr>`;
            }

            let footerSectionHTML = `
                <footer>
                    <section class="balance-info">
                        <div class="row">
                            <div class="col-12">
                                
                            <p id="hashPrograma" style="float: left; font-weight: 500; font-size: 9pt; font-family: 'Noto Sans', sans-serif;">${docData["outrosDocumento"]["hashPrograma"]}</p>
                            </div>
                            <div class="col-12">
                                <p class="m-0 font-weight-bold" style="font-weight: 600; font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    RESUMO DE IMPOSTOS: </p>
                            </div>
                            <div class="col-8">
                                <table class="tabela table border-0 table-hover" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    <thead style="font-weight: 600; color: #0000000d;">
                                        <tr>
                                            <td style="width: 10rem;">DESIGNAÇÃO</td>
                                            <td style="width: 8rem;">TAXA(%)</td>
                                            <td>INCIDÊNCIA</td>
                                            <td>IMPOSTO</td>
                                        </tr>
                                    </thead>
                                    <tbody id="incidencia">${incidNew}</tbody>
                                </table>
                                <p id="motivo_isencao" class="mb-1 font-weight-bold invisible" style="font-weight: 600; margin-top: -0.7rem !important; font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;" >${motivo_isec}</p>
                                <div class="col-12">
                                    <p class="m-0 font-weight-bold" style="font-weight: 600; font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                        MODOS DE PAGAMENTO: </p>
                                </div>
                                <table class="tabela table border-0 table-hover" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    <thead style="font-weight: 600; color: #0000000d;">
                                        <tr>
                                            <td style="width: 10rem;">DESCRIÇÃO</td>
                                            <td style="width: 8rem;">TOTAL</td>
                                            <td>INFORMAÇÃO ADICIONAL</td>
                                        </tr>
                                    </thead>
                                    <tbody id="tabelaModoPagamentoDocumento">
                                    
            `;

            

            const dataModoPagamento = docData["modoPagamento"];
            let row = "";
            for (var key in dataModoPagamento) {
                row += `
                    <tr>
                        <td>${dataModoPagamento[key]['nomeMp']}</td>
                        <td>${dataModoPagamento[key]['valor'].replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                        <td></td>
                    </tr>`;
                footerSectionHTML += row;
                row = '';
            }

            footerSectionHTML += `
                </tbody>
                                </table>
                                <div class="col-12">
                                    <p class="m-0 font-weight-bold" style="font-weight: 600; font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                        COORDENADAS BANCÁRIAS: </p>
                                </div>
                                <table class="tabela table border-0 table-hover" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    <thead style="font-weight: 600; color: #0000000d;">
                                        <tr>
                                            <td style="width: 10rem;">BANCO</td>
                                            <td style="width: 8rem;">NÚMERO DA CONTA</td>
                                            <td>IBAN</td>
                                        </tr>
                                    </thead>
                                    <tbody id="banco_banco">
                                        
                                        
                                    
                                    </tbody>
                                    <tr>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-4">
                                <table class="table border-0 table-hover table-striped" style="font-size: 7pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    <tr>
                                        <td>TOTAL ILÍQUIDO:</td>
                                        <td style="text-align: right;" id="totalLiquidoDocumento">${docData["outrosDocumento"]["totalLiquidoDocumento"]}</td>
                                    </tr>
                                    <tr>
                                        <td>DESCONTO GLOBAL:</td>
                                        <td style="text-align: right;" id="descontoGlobalDocumento">${docData["outrosDocumento"]["descontoGlobalDocumento"]}</td>
                                    </tr>
                                    <tr>
                                        <td>TOTAL IMPOSTO:</td>
                                        <td style="text-align: right;" id="impostoIvaDocumento">${docData["outrosDocumento"]["impostoIvaDocumento"]}</td>
                                    </tr>
                                    <tr>
                                        <td>RETENÇÃO 0,00%:</td>
                                        <td style="text-align: right;" id="retencaoDocumento">${docData["outrosDocumento"]["retencaoDocumento"]}</td>
                                    </tr>
                                    <tr>
                                        <td>TOTAL DO DOCUMENTO:</td>
                                        <td style="text-align: right;" id="totalDocumento">${docData["outrosDocumento"]["totalDocumento"]}</td>
                                    </tr>
                                </table>
                                <div class="col-12">
                                    <p id="paragrafoProforma" class="m-0" style="color: #8F8F8F; font-size: 5pt; font-family: 'Noto Sans', sans-serif; text-align: justify;">
                                    </p>
                                </div>
                            </div>
                        </div>
                    </section>
                </footer>
            `;

            return footerSectionHTML;
        }

        $.ajax({
            url: "includes/read/configuracao.inc.php",
            type: "post",
            dataType: "json",
            success: function(data) {
                docData["configuracao"] = data;
                // logotipoDocumento.src = "./images/logo/" + data[0]['valor'];
                // enderecoDocumento.innerText = data[3]['valor'];
                // telefoneDocumento.innerText = data[4]['valor'];
                // emailDocumento.innerText = data[5]['valor'];
                // nifDocumento.innerText = data[6]['valor'];
                // websiteDocumento.innerText = data[7]['valor'];

                docData["configuracao"]["logotipoDocumento"] = data[0]['valor'];
                docData["configuracao"]["enderecoDocumento"] = data[3]['valor'];
                docData["configuracao"]["telefoneDocumento"] = data[4]['valor'];
                docData["configuracao"]["emailDocumento"] = data[5]['valor'];
                docData["configuracao"]["nifDocumento"] = data[6]['valor'];
                docData["configuracao"]["websiteDocumento"] = data[7]['valor'];
            }
        });

        let countLines = 1,
            totalLines = 0;

        function codigoDocumento(codigo, tipoDocumento) {
            $.ajax({
                url: "includes/read/queryCodigoDocumento.inc.php",
                type: "post",
                dataType: "json",
                data: {
                    codigo: codigo.split("/")[1],
                    tipoDocumento: tipoDocumento
                },
                success: function(data) {
                    docData["documento"] = data;
                    $.ajax({
                        url: "includes/read/queryDocumentoModoPagamento.inc.php",
                        type: "post",
                        dataType: "json",
                        data: {
                            idDocumento: data[0]['idDocumento'],
                        },
                        success: function(data) {
                            docData["modoPagamento"] = data;
                            let row = "";
                            for (var key in data) {
                                row += `
                                <tr>
                                    <td>${data[key]['nomeMp']}</td>
                                    <td>${data[key]['valor'].replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                    <td></td>
                                </tr>`;
                            }
                            $("#tabelaModoPagamentoDocumento").html(row);
                        }
                    });
                    $.ajax({
                        url: "includes/read/queryDocumentoLinha.inc.php",
                        type: "post",
                        dataType: "json",
                        data: {
                            idDocumento: data[0]['idDocumento'],
                        },
                        success: function(data) {
                            docData["linhaDocumento"] = data ?? [];
                        },
                        error: function(err) {
                            console.log('LinhaDocumento ERROR');
                        }
                    });
                }
            }).done(function(data) {
                $.ajax({
                    url: "includes/read/queryDocumento.inc.php",
                    type: "post",
                    dataType: "json",
                    data: {
                        idDocumento: data[0]['idDocumento'],
                    },
                    success: function(data) {
                        
                        docData["outrosDocumento"] = data;

                        docData["outrosDocumento"]['estadoEmissao'] = data[0]['estadoEmissao'];

                        //let marcaDagua = document.querySelector('.marca-dagua');
                        if (data[0]['estadoEmissao'] == 0) {
                            //marcaDagua.style.setProperty('--content', '"Anulado"');
                        } else if (data[0]['estadoEmissao'] == 1) {
                            //marcaDagua.style.setProperty('--content', '""');
                        } else if (data[0]['estadoEmissao'] == 2) {
                            //marcaDagua.style.setProperty('--content', '"Bloqueado"');
                        }
                        docData["outrosDocumento"]["hashPrograma"] = data[0]['hashSaft'].substring(0, 4) + "-Processado por programa válido n308/agt";
                        docData["outrosDocumento"]["codDocumento"] = data[0]['codigoDocumento'];
                        docData["outrosDocumento"]["nomeTipoDocumento"] = data[0]['nomeTd'];
                        docData["outrosDocumento"]["clienteDocumento"] = data[0]['nomeE'].toUpperCase();
                        docData["outrosDocumento"]["moradaDocumento"] = data[0]['moradaE'];
                        docData["outrosDocumento"]["dataEmissaoDocumento"] = data[0]['dataDocumento'];
                        docData["outrosDocumento"]["dataVencimentoDocumento"] = data[0]['dataDocumento'];
                        docData["outrosDocumento"]["modoPagamentoDocumento"] = data[0]['nomePp'];
                        docData["outrosDocumento"]["nifDocumento"] = data[0]['nifE'];
                        docData["outrosDocumento"]["mercadoriaServicoDocumento"] = data[0]['total'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['total']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

                        docData["outrosDocumento"]["descontoGlobalDocumento"] = data[0]['descontoGlobal'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['descontoGlobal']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

                        docData["outrosDocumento"]["totalLiquidoDocumento"] = data[0]['totalLiquido'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['totalLiquido']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                        docData["outrosDocumento"]["impostoIvaDocumento"] = data[0]['imposto'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['imposto']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                        docData["outrosDocumento"]["retencaoDocumento"] = data[0]['retencao'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['retencao']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                        docData["outrosDocumento"]["totalDocumento"] = data[0]['total'] == null ? parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") : parseFloat(data[0]['total']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");


                        docData["outrosDocumento"]["natureza"] = data[0]["natureza"];

                    }
                }).done((data) => {
                    console.log("AAAAA: ", docData["linhaDocumento"])

                    const dataLine = docData["linhaDocumento"];
                    const totalLinhas = dataLine.length;
                    const linhasPorPagina = 24;
                    const totalPaginas = Math.ceil(totalLinhas / linhasPorPagina);

                    let documentParts = [];

                    for (let i = 0; i < totalPaginas; i++) {
                        const start = i * linhasPorPagina;
                        const end = start + linhasPorPagina;
                        const pageData = dataLine.slice(start, end);

                        documentParts.push(openDoc());
                        documentParts.push(buildHeaderSection());

                        if (i === 0) {}

                        documentParts.push(buildStoreUserSection());
                        documentParts.push(buildProductSection(totalPaginas, i + 1, pageData));

                        if (i + 1 === totalPaginas) {
                            documentParts.push(buildFooter());
                        }
                        documentParts.push(closeDoc(i + 1, totalPaginas));
                    }

                    mainDoc.innerHTML = documentParts.join("");

                    if (docData["outrosDocumento"]["natureza"] === "facturaProforma" || docData["outrosDocumento"]["natureza"] === "facturaProformaC") {
                        paragrafoProforma.innerText = ` Este Documento é válido por oito dias. Valor de Referência para Luanda e arredores, restantes provincias a negociar. Garantia: Suporte contínuo enquato durar a vigência do contracto de prestação de serviço. Exclusões: Estão excluídos desta proposta, Serviços adicionais que carecem de concertação prévia antes de serem executados, serviços de manutenção a infraestrutura de rede do cliente e ou de computadores que tenha apresentado avarias no seu funcionamento.`;
                    } else {
                        paragrafoProforma.innerText = `Os bens/serviços foram colocados a disposição do adquirente na data e local do documento.`;

                    }

                    var dados = docData["outrosDocumento"]
                    var elemento = document.getElementById('codDocumento');
                    elemento.innerText = dados[0]['codigoDocumento'];
                    var elemento1 = document.getElementById('nomeTipoDocumento');
                    elemento1.innerText = dados[0]['nomeTd'];

                    // console.log(`Page ${i + 1}:`, pageData);

                    let marcaDagua = document.querySelectorAll('.marca-dagua');
                    console.log('MARCA DA AGUA: ', marcaDagua);
                    marcaDagua.forEach(mH20 => {
                        if (docData['outrosDocumento']['estadoEmissao'] == 0) {
                            mH20.style.setProperty('--content', '"Anulado"');
                        } else if (docData['outrosDocumento']['estadoEmissao'] == 1) {
                            mH20.style.setProperty('--content', '""');
                        } else if (docData['outrosDocumento']['estadoEmissao'] == 2) {
                            mH20.style.setProperty('--content', '"Bloqueado"');
                        }
                    });
                    

                    




                    funcaoSelect("../pos/includes/select.inc.php", "post", "json", "banco", function success(data) {
                        if (Array.isArray(data)) {
                            console.log(data);
                            for (var i = 0; i < data.length; i++) {

                                $('#banco_banco').append(`
                                                <tr>
                                                    <td>${data[i]['nomeBanco']}</td>
                                                    <td>${data[i]['numeroConta']}</td>
                                                    <td>${data[i]['iban']}</td>
                                                </tr>
                            `)
                            }

                        }
                    }, function error(data) {

                    }, function done(data) {

                    });

                });
            });
        }




        function buildDocLayout4() {





        }
    </script>
</body>

</html>