<?php
/* Copyright 2023 Flávio Ribeiro

This file is part of OCOMON.

OCOMON is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

OCOMON is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */ session_start();

if (!isset($_SESSION['s_logado']) || $_SESSION['s_logado'] == 0) {
	$_SESSION['session_expired'] = 1;
    echo "<script>top.window.location = '../../index.php'</script>";
	exit;
}

require_once __DIR__ . "/" . "../../includes/include_geral_new.inc.php";
require_once __DIR__ . "/" . "../../includes/classes/ConnectPDO.php";

use includes\classes\ConnectPDO;

$conn = ConnectPDO::getInstance();

$auth = new AuthNew($_SESSION['s_logado'], $_SESSION['s_nivel'], 1);


?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" type="text/css" href="../../includes/css/estilos.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/jquery/datetimepicker/jquery.datetimepicker.css" />

	<link rel="stylesheet" type="text/css" href="../../includes/components/bootstrap/custom.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/components/fontawesome/css/all.min.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/components/datatables/datatables.min.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/my_datatables.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/bootstrap-select/dist/css/bootstrap-select.min.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/my_bootstrap_select.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/switch_radio.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/estilos_custom.css" />

	<title><?= APP_NAME; ?>&nbsp;<?= VERSAO; ?></title>
</head>

<body>
	
	<div class="container">
		<div id="idLoad" class="loading" style="display:none"></div>
	</div>

	<div id="divResult"></div>
	<div id="divResultSent"></div>
    <input type="hidden" name="label_close" id="label_close" value="<?= TRANS('BT_CLOSE'); ?>">
	<input type="hidden" name="label_return" id="label_return" value="<?= TRANS('TXT_RETURN'); ?>">


	<div class="container-fluid">
		<h4 class="my-4"><i class="fas fa-file-invoice text-secondary"></i>&nbsp;<?= TRANS('INVOICE_GENERATION'); ?>:&nbsp;<span class="small" id="company_name_label"></span></h4>
		<div class="modal" id="modal" tabindex="-1" style="z-index:9001!important">
			<div class="modal-dialog modal-xl">
				<div class="modal-content">
					<div id="divDetails">
					</div>
				</div>
			</div>
		</div>
        <!-- Modal -->
        <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-light">
                        <h5 class="modal-title" id="exampleModalLabel"><i class="fas fa-exclamation-triangle text-secondary"></i>&nbsp;<?= TRANS('REMOVE'); ?></h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <?= TRANS('CONFIRM_REMOVE'); ?>?
                    </div>
                    <div class="modal-footer bg-light">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?= TRANS('BT_CANCEL'); ?></button>
                        <button type="button" id="deleteButton" class="btn"><?= TRANS('BT_OK'); ?></button>
                    </div>
                </div>
            </div>
        </div>

		<?php
		if (isset($_SESSION['flash']) && !empty($_SESSION['flash'])) {
			echo $_SESSION['flash'];
			$_SESSION['flash'] = '';
        }


        $contractor_id = (isset($_GET['contractor']) && !empty($_GET['contractor']) ? noHtml($_GET['contractor']) : '');
        if (empty($contractor_id)) {
            echo message('danger', 'Ooops!', TRANS('MSG_ERR_NOT_EXECUTE'), '', '', 1);
            return;
        }

        $contractor_info = getContractors($conn, $contractor_id);

        /**
         * Listar as últimas faturas já emitidas para o prestador
        */
        $invoiceForms = [];
        $invoiceForms = getInvoicesFromContractor($conn, $contractor_id);
        if (!empty($invoiceForms)) {
            echo message('info', '', TRANS('MSG_CONTRACTOR_HAS_INVOICES'), '', '', 1);
            ?>
                <table class="table stripe hover order-column row-border" id="table_invoices">
                    <thead>
                        <tr>
                            <th><?= TRANS('TICKET_NUMBER'); ?></th>
                            <th><?= TRANS('DOCUMENT'); ?></th>
                            <th><?= TRANS('CONTRACTOR_ORGANIZATION'); ?></th>
                            <th><?= TRANS('ISSUANCE_DATE'); ?></th>
                            <th><?= TRANS('DUE_DATE'); ?></th>
                            <th><?= TRANS('TOTAL_PRICE'); ?></th>
                            <th><?= TRANS('AUTHOR'); ?></th>
                            <th><?= TRANS('GENERATING_DATE'); ?></th>
                            <th><?= TRANS('INVOICE_SENT_TO_CONTRACTOR'); ?></th>
                            <th><?= TRANS('INVOICE_SENT_TO_PAYMENT'); ?></th>
                            <th>-</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            foreach ($invoiceForms as $row) {
                                $authorInfo = getUserInfo($conn, $row['author']);

                                $sentToContractor = ($row['sent_to_contractor'] ? '<span class="text-success"><i class="fas fa-check"></i></span>' : '<button class="btn btn-sm btn-primary" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="' . TRANS('HELPER_BT_SEND_INVOICE_TO_CONTRACTOR') . '" onClick="sendInvoiceToContractor(' . $row['invoice_id'] . ');"><i class="fas fa-paper-plane"></i>&nbsp;'. TRANS('BT_SEND') . '</button>');
                                $sentToPaying = ($row['sent_to_paying'] ? '<span class="text-success"><i class="fas fa-check"></i></span>' : '');

                                $contractor_organization = (!empty($row['contractor_organization']) ? getContractorsOrganizations($conn, $row['contractor_organization'])['name'] : '');

                                ?>
                                    <tr>
                                        <td><?= $row['invoice_number']; ?></td>
                                        <td><a onClick="redirect('../../includes/functions/download_invoice_files.php?file_id= + <?= $row["file_id"]; ?>');" href="javascript:void(0);"><?= $row['filename']; ?></a></td>
                                        <td><?= $contractor_organization; ?></td>
                                        <td data-sort="<?= $row['issuance_date']; ?>"><?= dateScreen($row['issuance_date'], 1); ?></td>
                                        <td data-sort="<?= $row['due_date']; ?>"><?= dateScreen($row['due_date'], 1); ?></td>
                                        <td data-sort="<?= $row['total_price']; ?>"><?= priceScreen($row['total_price']); ?></td>
                                        <td><?= $authorInfo['nome']; ?></td>
                                        <td data-sort="<?= $row['created_at']; ?>"><?= dateScreen($row['created_at']); ?></td>
                                        <td><?= $sentToContractor; ?></td>
                                        <td><?= $sentToPaying; ?></td>
                                        <td><span onClick="confirmDeleteModal(<?= $row['invoice_id']; ?>);" class="pointer"><i class="fas fa-trash text-danger"></i></span></td>
                                    </tr>
                                <?php
                            }
                        ?>
                    </tbody>
                </table>
                <hr />
            <?php
        }

		?>

        <form method="post" action="<?= $_SERVER['PHP_SELF']; ?>" id="form">
            
            <?= csrf_input(); ?>
        
            <div class="row mb-0 mt-4">
                <div class="col-md-12 mb-0">
                    <h5><?= TRANS('MSG_BELLOW_YOU_CAN_GENERATE_NEW_INVOICE'); ?></h5>
                </div>
            </div>
            
            <?php
                // var_dump($contractor_info);
            ?>

            <div class="form-group row mt-0 mb-4">
                
                <label for="company_name" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('COMPANY_NAME'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="company_name" name="company_name"  value="<?= $contractor_info['company_name']; ?>" disabled/>
                </div>

                <label for="contact_name" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('CONTACT'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="contact_name" name="contact_name"  value="<?= $contractor_info['contact_name']; ?>" disabled/>
                </div>

                <label for="document_type" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('DOCUMENT_TYPE'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="document_type" name="document_type"  value="<?= $contractor_info['document_type']; ?>" disabled/>
                </div>

                <label for="document_value" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('DOCUMENT_VALUE'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="document_value" name="document_value"  value="<?= $contractor_info['document_value']; ?>" disabled/>
                </div>

                <?php
                    $contractorsOrganizations = getContractorsOrganizations($conn);
                ?>
                <label for="contractor_organization" class="col-md-2 col-form-label text-md-right"><?= TRANS('CONTRACTOR_ORGANIZATION'); ?></label>
                <div class="form-group col-md-4">
                    <select class="form-control bs-select" id="contractor_organization" name="contractor_organization" >
                        <option value=""><?= TRANS('SEL_SELECT'); ?></option>
                        <?php
                            foreach ($contractorsOrganizations as $organization) {
                                ?>
                                    <option data-subtext="<?= $organization['description']; ?>" value="<?= $organization['id']; ?>"><?= $organization['name']; ?></option>
                                <?php
                            }
                        ?>
                    </select>
                </div>


                <label for="contract_number" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('CONTRACT_NUMBER'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="contract_number" name="contract_number"  value="<?= $contractor_info['contract_number']; ?>" disabled/>
                </div>
                <div class="w-100"></div>



                <label for="issuance_date" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('ISSUANCE_DATE'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="issuance_date" name="issuance_date" value="<?= date('d/m/Y'); ?>" required />
                    <div class="invalid-feedback">
                        <?= TRANS('MANDATORY_FIELD'); ?>
                    </div>
                </div>

                <label for="due_date" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('DUE_DATE'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="due_date" name="due_date" value="<?= date('d/m/Y'); ?>" required  />
                    <div class="invalid-feedback">
                        <?= TRANS('MANDATORY_FIELD'); ?>
                    </div>
                </div>

                <label class="col-sm-2 col-md-2 col-form-label text-md-right"></label>
                <div class="form-group col-md-10">
                    <hr>
                    <small class="form-text text-muted"><?= TRANS('HELPER_SERVICE_DESCRIPTION'); ?></small>
                </div>


                <label for="service_description" id="add_service" class="col-sm-2 col-md-2 col-form-label text-md-right text-secondary add-service"><i class="fas fa-plus"></i></label>
                <div class="form-group col-md-6">
                    <textarea class="form-control" id="service_description" name="service_description[]" required placeholder="<?= TRANS('SERVICE_DESCRIPTION'); ?>"></textarea>
                </div>

                <div class="form-group col-md-2">
                    <input type="number" class="form-control" id="amount" name="amount[]" value="1" min="1" max="100" placeholder="<?= TRANS('COL_AMOUNT'); ?>" />
                </div>
                <div class="form-group col-md-2">
                    <input type="text" class="form-control" id="unitary_price" name="unitary_price[]" value="" placeholder="<?= TRANS('UNITARY_PRICE'); ?>" />
                    <input type="hidden" id="unitary_price_hidden" name="unitary_price_hidden" value=""/>
                </div>

            </div>

            
            <!-- Renderiza novas linhas para descrição de serviços -->
            <div class="form-group row mt-0 mb-4 new_service_fields" id="new_service_fields"></div>

            
            <div class="form-group row mt-0 mb-4">
                

                <div class="form-group col-md-6"></div>
                <label for="subtotal_price" class="col-md-2 col-form-label col-form-label-sm text-md-right "><?= TRANS('SUBTOTAL_PRICE'); ?></label>
                <div class="form-group col-md-4">
                    
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <div class="input-group-text " title="<?= TRANS('SUBTOTAL_PRICE'); ?>" data-placeholder="<?= TRANS('SUBTOTAL_PRICE'); ?>" data-toggle="popover" data-placement="top" data-trigger="hover">
                                <?= TRANS('CURRENCY'); ?>&nbsp;
                            </div>
                        </div>
                        <input type="text" class="form-control " id="subtotal_price" name="subtotal_price" value="" disabled />
                        <input type="hidden" id="total_price_hidden" name="total_price_hidden" value=""/>

                    </div>
                
                </div>
            
            
            
                <label class="col-sm-2 col-md-2 col-form-label text-md-right"></label>
                <div class="form-group col-md-10">
                    <hr>
                </div>


                <?php
                    $lastInvoiceNumber = getLastInvoiceNumber($conn);
                ?>
                <label for="invoice_number" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('INVOICE_REGISTER_NUMBER'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="invoice_number" name="invoice_number" value="" required placeholder="<?= TRANS('INVOICE_REGISTER_NUMBER'); ?>" />
                    <small class="form-text text-muted"><?= TRANS('LAST_GENERATED_NUMBER'); ?>: <span class="font-weight-bold"><?= $lastInvoiceNumber; ?></span></small>
                    <div class="invalid-feedback">
                        <?= TRANS('MANDATORY_FIELD'); ?>
                    </div>
                </div>
                
                <label for="tax_rate" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('TAX_RATE'); ?>&nbsp;%</label>
                <div class="form-group col-md-4">
                    <input type="number" class="form-control" id="tax_rate" name="tax_rate" value="" min="0" max="100" placeholder="<?= TRANS('TAX_RATE'); ?>" />
                </div>
                <label for="issqn" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('ISSQN'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="issqn" name="issqn" value="" placeholder="<?= TRANS('ISSQN'); ?>" />
                </div>
                <label for="discounts" class="col-sm-2 col-md-2 col-form-label text-md-right"><?= TRANS('DISCOUNTS'); ?></label>
                <div class="form-group col-md-4">
                    <input type="text" class="form-control" id="discounts" name="discounts" value="" placeholder="<?= TRANS('DISCOUNTS'); ?>" />
                </div>

                

                <?php
                    $invoice_models = getInvoiceModels($conn);
                ?>
                <label for="invoice_model" class="col-md-2 col-form-label text-md-right"><?= TRANS('INVOICE_MODEL'); ?></label>
                <div class="form-group col-md-10">
                    <select class="form-control bs-select" id="invoice_model" name="invoice_model" >
                        <?php
                            foreach ($invoice_models as $model) {
                                ?>
                                    <option data-subtext="<?= $model['description']; ?>" value="<?= $model['id']; ?>"><?= $model['name']; ?></option>
                                <?php
                            }
                        ?>
                    </select>
                    <small class="form-text text-muted"><?= TRANS('HELPER_INVOICE_MODEL'); ?></small>
                </div>



                <!-- <div class="form-group col-md-6"></div> -->
                <label class="col-md-2 col-form-label text-md-right" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="<?= TRANS('HELPER_SEND_INVOICE_TO_CONTRACTOR'); ?>"><?= TRANS('SEND_INVOICE_TO_CONTRACTOR'); ?></label>
                <div class="form-group col-md-4 ">
                    <div class="switch-field">
                        <?php
                        $yesChecked = "";
                        $noChecked = "checked";
                        ?>
                        <input type="radio" id="send_invoice" name="send_invoice" value="yes" <?= $yesChecked; ?> />
                        <label for="send_invoice"><?= TRANS('YES'); ?></label>
                        <input type="radio" id="send_invoice_no" name="send_invoice" value="no" <?= $noChecked; ?> />
                        <label for="send_invoice_no"><?= TRANS('NOT'); ?></label>
                    </div>
                </div>
                <label for="total_price" class="col-md-2 col-form-label col-form-label-sm text-md-right "><?= TRANS('TOTAL_PRICE'); ?></label>
                <div class="form-group col-md-4">
                    
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <div class="input-group-text " title="<?= TRANS('TOTAL_PRICE'); ?>" data-placeholder="<?= TRANS('TOTAL_PRICE'); ?>" data-toggle="popover" data-placement="top" data-trigger="hover">
                                <?= TRANS('CURRENCY'); ?>&nbsp;
                            </div>
                        </div>
                        <input type="text" class="form-control " id="total_price" name="total_price" value="" disabled />

                    </div>
                
                </div>




            </div>

            <div class="form-group row my-4 ">
                <div class="row w-100"></div>
                <div class="form-group col-md-7 d-none d-md-block">
                </div>
                <div class="form-group col-12 col-md-3 ">

                    <input type="hidden" name="action" id="action" value="new">
                    <input type="hidden" name="contractor_id" id="contractor_id" value="<?= $contractor_id; ?>">
                    <button type="submit" id="idSubmit" name="submit" class="btn btn-primary btn-block"><?= TRANS('GENERATE_INVOICE'); ?></button>
                </div>
                <div class="form-group col-12 col-md-2">
                    <!-- <button type="reset" class="btn btn-secondary btn-block close-or-return"><?= TRANS('BT_CANCEL'); ?></button> -->
						<button type="reset" id="close_details" class="btn btn-secondary btn-block" "><?= TRANS('BT_CANCEL'); ?></button>

                </div>
            </div>



        </form>


    </div>

	<script src="../../includes/javascript/funcoes-3.0.js"></script>
    <script src="../../includes/components/jquery/jquery.js"></script>
    <script src="../../includes/components/jquery/jquery.initialize.min.js"></script>
    <script src="../../includes/components/jquery/datetimepicker/build/jquery.datetimepicker.full.min.js"></script>
    <script src="../../includes/components/jquery/jquery-mask-plugin/dist/jquery.mask.min.js"></script>

	<script src="../../includes/components/bootstrap/js/bootstrap.bundle.js"></script>
	<script src="../../includes/components/bootstrap-select/dist/js/bootstrap-select.min.js"></script>

	<script type="text/javascript" charset="utf8" src="../../includes/components/datatables/datatables.js"></script>
	<script type="text/javascript">
		$(function() {

            $('#company_name_label').text($('#company_name').val());


            /* Identificar se a janela está sendo carregada em uma popup (iframe dentro de uma modal) */
			var isInIframe = (window.location !== window.parent.location) ? true : false;

            if (isInIframe) {
				var iframeParent = window.parent.document.getElementById('iframeMain');
				if (!iframeParent) {
					$('#close_details').text($('#label_close').val()).on("click", function() {
						window.parent.closeIframe();
					});
				} else {
					$('#close_details').text($('#label_return').val()).on("click", function() {
						window.history.back();
					});
				}
			} else {
				$('#close_details').text($('#label_return').val()).on("click", function() {
					window.history.back();
				});
			}

            if ($('#table_invoices').length > 0) {
                $('#table_invoices').DataTable({
                    paging: true,
                    deferRender: true,
                    order: [0, 'desc'],
                    columnDefs: [{
                        searchable: false,
                        orderable: false,
                        targets: ['editar', 'remover']
                    }],
                    "language": {
                        "url": "../../includes/components/datatables/datatables.pt-br.json"
                    }
                });
            }
            
            $('input[name="unitary_price[]"]').mask('000.000.000,00', {reverse: true});
            $('input[name="discounts"]').mask('000.000.000,00', {reverse: true});

            /* Idioma global para os calendários */
            $.datetimepicker.setLocale('pt-BR');
            
            /* Calendários de início e fim do período */
            $('#issuance_date').datetimepicker({
                format: 'd/m/Y',
                onShow: function(ct) {
                    this.setOptions({
                        maxDate: $('#due_date').datetimepicker('getValue')
                    })
                },
                timepicker: false
            });
            $('#due_date').datetimepicker({
                format: 'd/m/Y',
                onShow: function(ct) {
                    this.setOptions({
                        minDate: $('#issuance_date').datetimepicker('getValue')
                    })
                },
                timepicker: false
            });


            $('.bs-select').selectpicker({
                /* placeholder */
                noneSelectedText: "<?= TRANS('SEL_SELECT', '', 1); ?>",
                liveSearch: true,
                liveSearchNormalize: true,
                showSubtext: true,
                liveSearchPlaceholder: "<?= TRANS('BT_SEARCH', '', 1); ?>",
                noneResultsText: "<?= TRANS('NO_RECORDS_FOUND', '', 1); ?> {0}",
                style: "",
                styleBase: "form-control ",
            });
            
            $(function() {
				$('[data-toggle="popover"]').popover({
					html: true
				});
			});

			$('.popover-dismiss').popover({
				trigger: 'focus'
			});

            closeOrReturn ();

            $('#add_service').css('cursor', 'pointer').on('click', function() {
				loadServiceFields();
			});

            $('.new_service_fields').on('click', '.remove-service', function(e) {
                e.preventDefault();
				dataRandom = $(this).attr('data-random');
				$("."+dataRandom).remove();
            });


            $(document).on('input', 'input[name="amount[]"], input[name="unitary_price[]"], input[name="discounts"]', function() {
                updateTotalPrice();
            });

            $(document).ready(function() {
                updateTotalPrice();
            });


            if ($('#new_service_fields').length > 0) {
                /* Adicionei o mutation observer em função dos elementos que são adicionados após o carregamento do DOM */
                var obs = $.initialize(".after-dom-ready", function() {
					$('.bs-select').selectpicker({
                        /* placeholder */
                        noneSelectedText: "<?= TRANS('SEL_SELECT', '', 1); ?>",
                        liveSearch: true,
                        liveSearchNormalize: true,
                        showSubtext: true,
                        liveSearchPlaceholder: "<?= TRANS('BT_SEARCH', '', 1); ?>",
                        noneResultsText: "<?= TRANS('NO_RECORDS_FOUND', '', 1); ?> {0}",
                        style: "",
                        styleBase: "form-control ",
                    });

                    $('.remove-service').css('cursor', 'pointer');

                    $('input[name="unitary_price[]"]').mask('000.000.000,00', {reverse: true});


                    $('.asset_tag_class').on('change', function() {

						var myId = $(this).attr('id');
                        console.log('meu ID: ' + myId);
						loadUnitsByAssetTag(myId);
                        loadAssetBasicInfo(myId);
					});

                    $('.asset_unit_class').on('change', function() {
                        let randomId = $(this).attr('data-base-random');
                        loadAssetBasicInfo(randomId, $('#' + randomId).val(), $(this).val());
                    });

                }, {
                    target: document.getElementById('new_service_fields')
                }); /* o target limita o scopo do observer */
            }

            $('#idSubmit').on('click', function(e) {
                e.preventDefault();
                invoiceDocumentProcess();
            });


			$('#bt-cancel').on('click', function() {
				var url = '<?= $_SERVER['PHP_SELF'] ?>';
				$(location).prop('href', url);
			});
		});


        function sendInvoiceToContractor(invoice_id) {
            var loading = $(".loading");
            $(document).ajaxStart(function() {
                loading.show();
            });
            $(document).ajaxStop(function() {
                loading.hide();
            });



            $.ajax({
                url: './batch_send_to_contractors_process.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'send_to_sigle_contractor_from_invoices',
                    invoice_id: invoice_id
                }
            }).done(function(response) {
                
                if (!response.success) {
                    if (response.field_id != "") {
                        $('#' + response.field_id).focus().addClass('is-invalid');
                    }
                    $('#divResultSent').html(response.message);
                } else {
                    // getFlashMessage();
                    location.reload();
                }
            });
            return false;
        }



        function loadServiceFields() {
            var loading = $(".loading");
            $(document).ajaxStart(function() {
                loading.show();
            });
            $(document).ajaxStop(function() {
                loading.hide();
            });

            $.ajax({
                url: './render_new_service_row.php',
                method: 'POST',
                data: {
                    random: Math.random().toString(16).substr(2, 8)
                },
                // dataType: 'json',
            }).done(function(data) {
                $('#new_service_fields').append(data);
            });
            return false;
		}


        // function updateTotalPrice() {
        //     // console.log('updateTotalPrice');
        //     let total = 0;

        //     $('input[name="amount[]"]').each(function(index) {
        //         const amount = parseFloat($(this).val()) || 0;
        //         const unitaryPrice = parseFloat($('input[name="unitary_price[]"]').eq(index).val()) || 0;
        //         total += amount * unitaryPrice;
        //     });

        //     $('#total_price').val(total.toFixed(2));
        // }

        function updateTotalPrice() {
            let total = 0;

            // Função para converter valor de moeda brasileira para número
            function parseCurrency(value) {
                return parseFloat(value.replace('R$', '').replace(/\./g, '').replace(',', '.').trim()) || 0;
            }

            // Função para formatar número para moeda brasileira
            function formatCurrency(value) {
                // return 'R$ ' + value.toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
                return value.toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
            }

            $('input[name="amount[]"]').each(function(index) {
                const amount = parseFloat($(this).val()) || 0;
                const unitaryPrice = parseCurrency($('input[name="unitary_price[]"]').eq(index).val());
                total += amount * unitaryPrice;
            });

            // Atualiza o campo #subtotal_price com o valor formatado
            $('#subtotal_price').val(formatCurrency(total));


            // Descontos
            const discounts = parseCurrency($('input[name="discounts"]').val());
            total -= discounts;

            // Atualiza o campo #total_price com o valor formatado
            $('#total_price').val(formatCurrency(total));
        }




        function invoiceDocumentProcess(numero) {
            var loading = $(".loading");
            $(document).ajaxStart(function() {
                loading.show();
            });
            $(document).ajaxStop(function() {
                loading.hide();
            });

            $.ajax({
                url: './generate_invoice_process.php',
                method: 'POST',
                dataType: 'json',
                data: $('#form').serialize(),
            }).done(function(response) {
                if (!response.success) {

                    if (response.field_id != "") {
                        $('#' + response.field_id).focus().addClass('is-invalid');
                    }
                    $('#divResult').html(response.message);
                } else {
                    // location.reload();
                    if (response.send_invoice) {
                        var loading = $(".loading");
                        $(document).ajaxStart(function() {
                            loading.show();
                        });
                        $(document).ajaxStop(function() {
                            loading.hide();
                        });

                        $.ajax({
                            url: './batch_send_to_contractors_process.php',
                            method: 'POST',
                            dataType: 'json',
                            data: {
                                action: 'send_to_sigle_contractor',
                                invoice_id: response.invoice_id
                            }
                        }).done(function(response) {
                            
                            if (!response.success) {
                                if (response.field_id != "") {
                                    $('#' + response.field_id).focus().addClass('is-invalid');
                                }
                                $('#divResultSent').html(response.message);
                            } else {
                                // getFlashMessage();
                                location.reload();
                            }
                        });
                        return false;
                    } else {
                        location.reload();
                    }
                }
            });
            return false;
        }

        function confirmDeleteModal(id) {
            $('#deleteModal').modal();
            $('#deleteButton').html('<a class="btn btn-danger" onclick="deleteData(' + id + ')"><?= TRANS('REMOVE'); ?></a>');
        }

        function deleteData(id) {

            var loading = $(".loading");
            $(document).ajaxStart(function() {
                loading.show();
            });
            $(document).ajaxStop(function() {
                loading.hide();
            });

            $.ajax({
                url: './delete_invoice_process.php',
                method: 'POST',
                data: {
                    cod: id,
                    action: 'delete'
                },
                dataType: 'json',
            }).done(function(response) {
                // var url = '<?= $_SERVER['PHP_SELF'] ?>?contractor=' + response.contractor;
                // $(location).prop('href', url);
                // return false;

                if (!response.success) {

                    if (response.field_id != "") {
                        $('#' + response.field_id).focus().addClass('is-invalid');
                    }
                    $('#divResult').html(response.message);
                    } else {
                        // $('#modalAssets').modal('hide');
                        location.reload();
                    }
            });
            return false;
            // $('#deleteModal').modal('hide'); // now close modal
        }

        
        function closeOrReturn (jumps = 1) {
			buttonValue ();
			$('.close-or-return').on('click', function(){
				if (isPopup()) {
					window.close();
				} else {
					window.history.back(jumps);
				}
			});
		}

		function buttonValue () {
			if (isPopup()) {
				$('.close-or-return').text('<?= TRANS('BT_CLOSE'); ?>');
			}
		}
		
	</script>
</body>

</html>