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

$_SESSION['s_page_admin'] = $_SERVER['PHP_SELF'];

$config = getConfig($conn);

$type = "";


$sendingOptions = [
	"0" => TRANS('OCO_SEL_ANY'),
	"1" => TRANS('OPTION_SENT'),
	"2" => TRANS('OPTION_NOT_SENT'),
];


?>
<!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/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/datatables/datatables-checkboxes-master/css/dataTables.checkboxes.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-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/components/suneditor/node_modules/suneditor/dist/css/suneditor.min.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/components/suneditor/node_modules/suneditor/src/assets/css/suneditor-contents.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 class="container-fluid">
		<h4 class="my-4"><i class="fas fa-search text-secondary"></i>&nbsp;<?= TRANS('TTL_SEARCH_AND_BATCH_ACTIONS'); ?></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>

		<div id="div_flash"></div>

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


		if ((!isset($_GET['action'])) && !isset($_POST['submit'])) {

		?>
			<!-- 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'); ?> <span class="j_param_id"></span>?
						</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>

            
			<form name="form" method="post" action="<?= $_SERVER['PHP_SELF']; ?>" id="form" >
				<?= csrf_input(); ?>
				<div class="form-group row my-4">


					<label for="contractor" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('CONTRACTOR'); ?></label>
                    <div class="form-group col-md-10 ">
                        <select class="form-control bs-select" id="contractor" name="contractor" required>
                            <option value=""><?= TRANS('OCO_SEL_ANY'); ?></option>
							<?php
								$contractors = getContractors($conn);
								foreach ($contractors as $contractor){
									?>
										<option value="<?= $contractor['id']; ?>"
										><?= $contractor['company_name']; ?></option>
									<?php
								}
							?>
                        </select>
                    </div>
                    
                    <label for="start_issuance_date" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('START_ISSUANCE_DATE'); ?></label>
                    <div class="form-group col-md-4">
                        <input type="text" class="form-control " id="start_issuance_date" name="start_issuance_date" value="<?= date("01/m/Y"); ?>" autocomplete="off" placeholder="<?= TRANS('OCO_SEL_ANY'); ?>"/>
                    </div>

                    <label for="end_issuance_date" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('END_ISSUANCE_DATE'); ?></label>
                    
                    <div class="form-group col-md-4">
                        <input type="text" class="form-control " id="end_issuance_date" name="end_issuance_date" value="" autocomplete="off" placeholder="<?= TRANS('OCO_SEL_ANY'); ?>" />
                    </div>
                    <label for="start_due_date" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('START_DUE_DATE'); ?></label>
                    <div class="form-group col-md-4">
                        <input type="text" class="form-control " id="start_due_date" name="start_due_date" value="" placeholder="<?= TRANS('OCO_SEL_ANY'); ?>" autocomplete="off" />
                    </div>

                    <label for="end_due_date" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('END_DUE_DATE'); ?></label>
                    
                    <div class="form-group col-md-4">
                        <input type="text" class="form-control " id="end_due_date" name="end_due_date" value="" autocomplete="off" placeholder="<?= TRANS('OCO_SEL_ANY'); ?>" />
                    </div>

                    
					<label for="sent_to_contractor" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('CONTRACTOR_SENDING_STATUS'); ?></label>
                    <div class="form-group col-md-4">
                        <select class="form-control bs-select" id="sent_to_contractor" name="sent_to_contractor" >
							<?php
								foreach ($sendingOptions as $key => $value) {
									?>
										<option value="<?= $key; ?>"><?= $value; ?></option>
									<?php
								}
							?>
						</select>
                    </div>
                    

					<label for="sent_to_paying" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('PAYMENT_SENDING_STATUS'); ?></label>
                    <div class="form-group col-md-4">
                        <select class="form-control bs-select" id="sent_to_paying" name="sent_to_paying" >
							<?php
								foreach ($sendingOptions as $key => $value) {
									?>
										<option value="<?= $key; ?>"><?= $value; ?></option>
									<?php
								}
							?>
						</select>
                    </div>
                    

					<?php
						$organizations = getContractorsOrganizations($conn);
					?>
					<label for="contractor_organization" class="col-md-2 col-form-label col-form-label-sm 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('OCO_SEL_ANY'); ?></option>
							<?php
								foreach ($organizations as $organization) {
									?>
										<option value="<?= $organization['id']; ?>"><?= $organization['name']; ?></option>
									<?php
								}
							?>
						</select>
                    </div>


					<div class="row w-100"></div>
					<div class="form-group col-md-8 d-none d-md-block">
					</div>
					<div class="form-group col-12 col-md-2 ">

						<button type="submit" id="idSubmit" name="submit" class="btn btn-primary btn-block"><i class="fas fa-search"></i>&nbsp;<?= TRANS('BT_SEARCH'); ?></button>
					</div>
					<div class="form-group col-12 col-md-2">
						<button type="reset" class="btn btn-secondary btn-block" onClick="parent.history.back();"><?= TRANS('BT_CANCEL'); ?></button>
					</div>
				</div>
			</form>
			<?php
		} 
		?>

		
		<div id="buttonsAndList">
			<!-- Botões de ações -->
			<div class="row d-none" id="div_buttons">
				<div class="col-3 mb-4"><button id="bt_send_to_contractor" class="btn btn-block btn-primary" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="<?= TRANS('HELPER_BUTTON_SEND_TO_CONTRACTOR'); ?>" disabled><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('SEND_TO_CONTRACTOR'); ?></button></div>
				<div class="col-3 mb-4"><button id="bt_send_to_payment" class="btn btn-block btn-primary" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="<?= TRANS('HELPER_BUTTON_SEND_TO_PAYMENT'); ?>" disabled><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('SEND_TO_PAYMENT'); ?></button></div>
			</div>
			<!-- Listagem resultante da pesquisa -->
			<div id="divListResults"></div>
		</div>
	
	
	
	
		<form id="form_send_invoices" name="form_send_invoices" method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
            
            <div id="invoices_to_send_container"></div>
        
            <!-- Modal para confirmação de envio para os prestadores -->
            <div class="modal fade" id="modal_send_to_contractors" tabindex="-1" style="z-index:2001!important" role="dialog" aria-labelledby="send_to_contractors" aria-hidden="true" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div id="div_result_send_to_contractors"></div>
                        <div class="modal-header text-center bg-light">

                            <h4 class="modal-title w-100 font-weight-bold text-secondary"><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('INVOICES_SEND_BATCH_TO_CONTRACTORS'); ?></h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>

						<div class="row mx-2 mt-4">
                            <div class="form-group col-md-12">
                                <?= message('info', '', TRANS('HELPER_INVOICES_TO_CONTRACTORS'), '', '', true); ?>
                            </div>
                        </div>

                        <div class="row mx-2 mt-0">
                            <div class="form-group col-md-12">
                                <h5><?= TRANS('WERE_SELECTED'); ?>&nbsp;<span class="font-weight-bold" id="count_selected"></span>&nbsp;<?= TRANS('INVOICES'); ?>.</h5>
                            </div>
                        </div>
                        

                        <div class="modal-footer d-flex justify-content-end bg-light">
                            <button id="confirm_batch_send_to_contractors" class="btn btn-primary"><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('BT_SEND') ?></button>
                            <button class="btn btn-secondary" data-dismiss="modal" aria-label="Close"><?= TRANS('BT_CANCEL'); ?></button>
                        </div>
                    </div>
                </div>
            </div>


			<!-- Modal para confirmação de envio da listagem de pagamento -->
			<div class="modal fade" id="modal_send_to_payment" tabindex="-1" style="z-index:2001!important" role="dialog" aria-labelledby="send_to_payment" aria-hidden="true" data-backdrop="static" data-keyboard="false">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <div id="div_result_send_to_payment"></div>
                        <div class="modal-header text-center bg-light">

                            <h4 class="modal-title w-100 font-weight-bold text-secondary"><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('INVOICES_SEND_BATCH_TO_PAYMENT'); ?></h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>

						<div class="row mx-2 mt-4">
                            <div class="form-group col-md-12">
                                <?= message('info', '', TRANS('HELPER_INVOICES_TO_PAYMENT'), '', '', true); ?>
                            </div>
                        </div>

                        <div class="row mx-2 mt-0">
                            <div class="form-group col-md-12">
                                <h5><?= TRANS('WERE_SELECTED'); ?>&nbsp;<span class="font-weight-bold" id="count_selected_2"></span>&nbsp;<?= TRANS('INVOICES'); ?>.</h5>
                            </div>
                        </div>

						<?php
							$mailingLists = getMailingLists($conn);
						?>
						<div class="row mx-2 mt-0">
							<div class="form-group col-md-12">
								<select class="form-control bs-select" id="mailing_list" name="mailing_list" >
									<option value=""><?= TRANS('HELPER_MAILING_LIST'); ?></option>
									<?php
										foreach ($mailingLists as $mailingList) {
											$subtext = $mailingList['ml_addr_to'];
											$subtext .= ($mailingList['ml_addr_cc'] != '') ? ' - CC: ' . $mailingList['ml_addr_cc'] : '';
											?>
												<option data-subtext="<?= $subtext; ?>" value="<?= $mailingList['ml_cod']; ?>"><?= $mailingList['ml_sigla']; ?></option>
											<?php
										}
									?>
								</select>
								<small class="form-text text-muted"><?= TRANS('HELPER_MAILING_LIST'); ?></small>
							</div>
                        </div>

						<div class="row mx-2">
							<div class="form-group col-md-12">
								<textarea class="form-control " name="extra_text" id="extra_text"></textarea>
								<small class="form-text text-muted"><?= TRANS('HELPER_EXTRA_TEXT'); ?></small>
							</div>
						</div>

						<input type="hidden" name="start_due_date_hidden" id="start_due_date_hidden" value="" />
						<input type="hidden" name="end_due_date_hidden" id="end_due_date_hidden" value="" />

                        <div class="modal-footer d-flex justify-content-end bg-light">
                            <button id="confirm_batch_send_to_payment" class="btn btn-primary"><i class="fas fa-paper-plane"></i>&nbsp;<?= TRANS('BT_SEND') ?></button>
                            <button class="btn btn-secondary" data-dismiss="modal" aria-label="Close"><?= TRANS('BT_CANCEL'); ?></button>
                        </div>
                    </div>
                </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/bootstrap/js/bootstrap.bundle.js"></script>
	<script src="../../includes/components/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="../../includes/components/jquery/datetimepicker/build/jquery.datetimepicker.full.min.js"></script>
	
	<script src="../../includes/components/suneditor/node_modules/suneditor/dist/suneditor.min.js"></script>
    <script src="../../includes/components/suneditor/node_modules/suneditor/src/lang/pt_br.js"></script>
	<script src="../../includes/javascript/format_bar.js"></script>

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

			$(function() {
				$('[data-toggle="popover"]').popover({
					html: true
				});
			});

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

            $('.bs-select').selectpicker({
				/* placeholder */
				liveSearch: true,
				liveSearchNormalize: true,
				showSubtext: true,
				liveSearchPlaceholder: "<?= TRANS('BT_SEARCH', '', 1); ?>",
				noneResultsText: "<?= TRANS('NO_RECORDS_FOUND', '', 1); ?> {0}",
				
				style: "",
				styleBase: "form-control input-select-multi",
			});


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

            /* Calendários de início e fim do período */
            $('#start_due_date').datetimepicker({
                format: 'd/m/Y',
                onShow: function(ct) {
                    this.setOptions({
                        maxDate: $('#end_due_date').datetimepicker('getValue')
                    })
                },
                timepicker: false
            });
            $('#end_due_date').datetimepicker({
                format: 'd/m/Y',
                onShow: function(ct) {
                    this.setOptions({
                        minDate: $('#start_due_date').datetimepicker('getValue')
                    })
                },
                timepicker: false
            });

            var obs = $.initialize("#table_invoices", function() {
                var dataTableInvoices = $('#table_invoices').DataTable({
                    language: {
                        url: "../../includes/components/datatables/datatables.pt-br.json",
                    },
                    paging: true,
					pageLength: 25,
                    deferRender: true,

					columnDefs: [
						{
							targets: 0,
							checkboxes: {'selectRow': true},
							orderable: false
						}
					],
					
                    order: [0, 'DESC'],

					select: {'style': 'multi+shift'},
					rowId: 0,
                });


				/* Índice da coluna que não deve selecionar a linha ao ser clicada */
				var specificColumnIndex = 4;
				dataTableInvoices.on('click', 'td', function(e) {
					var columnIndex = $(this).index();
					if (columnIndex === specificColumnIndex) {
						e.stopPropagation();
					}
				});

				dataTableInvoices.on('select', function(e, dt, type, indexes) {
					var selectedRowsCount = dataTableInvoices.rows({ selected: true }).count();
					var selected_invoices = dataTableInvoices.rows({ selected: true }).ids().toArray();

					/* Por que os ids estão vindos como "undefined"? */
					
					$('#count_selected').text(selectedRowsCount);
					$('#count_selected_2').text(selectedRowsCount);
					$('#invoices_to_send_container').empty();
					selected_invoices.forEach(function(id) {
						$('#invoices_to_send_container').append('<input type="hidden" name="invoices_to_send[]" value="' + id + '">');
					});

					$('#bt_send_to_contractor').attr('disabled', true);
					$('#bt_send_to_payment').attr('disabled', true);
					if (selectedRowsCount > 0) {
						$('#bt_send_to_contractor').attr('disabled', false);
						
						if (hasDuePeriod()) {
							$('#bt_send_to_payment').attr('disabled', false);
						}
						
					}
				});

				// Evento para quando uma linha é deselecionada
				dataTableInvoices.on('deselect', function(e, dt, type, indexes) {
					var selectedRowsCount = dataTableInvoices.rows({ selected: true }).count();
					var selected_tickets = dataTableInvoices.rows({ selected: true }).ids().toArray();

					$('#count_selected').text(selectedRowsCount);
					$('#count_selected_2').text(selectedRowsCount);
					$('#invoices_to_send_container').empty();
					selected_tickets.forEach(function(id) {
						$('#invoices_to_send_container').append('<input type="hidden" name="invoices_to_send[]" value="' + id + '">');
					});

					$('#bt_send_to_contractor').attr('disabled', false);

					if (hasDuePeriod()) {
						$('#bt_send_to_payment').attr('disabled', false);
					}
					if (selectedRowsCount < 1) {
						$('#bt_send_to_contractor').attr('disabled', true);
						$('#bt_send_to_payment').attr('disabled', true);
					}
				})

				


            }, {
                target: document.getElementById('divListResults'),
            });

        
			if ($('#extra_text').length > 0) {
				let bar_type = 'basic';
				var editor = render_format_bar('extra_text', 100, bar_type);
            }

			
            $('input, select, textarea').on('change', function() {
				$(this).removeClass('is-invalid');
			});
			$('#idSubmit').on('click', function(e) {
				e.preventDefault();
				
				loadSearchResult();
				return false;
            });
 


			$('#bt_send_to_contractor').on('click', function(e) {
                e.preventDefault();
                $('#modal_send_to_contractors').modal('show');
            });

			$('#confirm_batch_send_to_contractors').on('click', function(e) {
                e.preventDefault();

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

				$('#bt_send_to_contractor').attr('disabled', true);
				$('#bt_send_to_payment').attr('disabled', true);

                $.ajax({
                    url: './batch_send_to_contractors_process.php',
                    method: 'POST',
                    dataType: 'json',
                    data: $('#form_send_invoices').serialize(),
                }).done(function(response) {
                    
					$('#bt_send_to_contractor').attr('disabled', false);
					$('#bt_send_to_payment').attr('disabled', false);
					
					if (!response.success) {
                        if (response.field_id != "") {
                            $('#' + response.field_id).focus().addClass('is-invalid');
                        }
                        $('#div_result_send_to_contractors').html(response.message);
                    } else {
                        $('#modal_send_to_contractors').modal('hide');
						loadSearchResult();
                        deselectAll();
                        getFlashMessage();
                    }
                });
                return false;
            });


			$('#bt_send_to_payment').on('click', function(e) {
                e.preventDefault();
                $('#modal_send_to_payment').modal('show');
            });

			$('#confirm_batch_send_to_payment').on('click', function(e) {
                e.preventDefault();

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

				editor.save();

				$('#bt_send_to_contractor').attr('disabled', true);
				$('#bt_send_to_payment').attr('disabled', true);

                $.ajax({
                    url: './batch_send_to_payment_process.php',
                    method: 'POST',
                    dataType: 'json',
                    data: $('#form_send_invoices').serialize(),
                }).done(function(response) {
                    
					$('#bt_send_to_contractor').attr('disabled', false);
					$('#bt_send_to_payment').attr('disabled', false);
					
					if (!response.success) {
                        if (response.field_id != "") {
                            $('#' + response.field_id).focus().addClass('is-invalid');
                        }
                        $('#div_result_send_to_payment').html(response.message);
                    } else {
                        $('#modal_send_to_payment').modal('hide');
						loadSearchResult();
                        deselectAll();
                        getFlashMessage();
                    }
                });
                return false;
            });


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



		function loadSearchResult() {
		// var form = $('form').get(0);
			var loading = $(".loading");
			$(document).ajaxStart(function() {
				loading.show();
			});
			$(document).ajaxStop(function() {
				loading.hide();
			});
		
			$("#idSubmit").prop("disabled", true);
			$.ajax({
				url: './invoices_search_process.php',
				method: 'POST',
				data: $('#form').serialize(),
				// data: new FormData(form),
				dataType: 'json',
				
				// cache: false,
				// processData: false,
				// contentType: false,
			}).done(function(data) {

				if (!data.success) {
					$('#divResult').html(data.message);
					$('input, select, textarea').removeClass('is-invalid');
					if (data.field_id != "") {
						$('#' + data.field_id).focus().addClass('is-invalid');
					}
					$("#idSubmit").prop("disabled", false);

					$('#div_buttons').addClass('d-none');
					$('#divListResults').html('');

				} else {
					$('#div_buttons').removeClass('d-none');
					
					let table = '<table id="table_invoices" name="table_invoices" class="table table-striped table-bordered" cellspacing="0" width="100%">';

					table += '<thead>';
						table += '<tr class="header table-borderless">';
							table += '<th class="line"></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('CONTRACTOR')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('CONTRACTOR_ORGANIZATION')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('TICKET_NUMBER')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('DOCUMENT')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('ISSUANCE_DATE')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('DUE_DATE')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('TOTAL_PRICE')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('INVOICE_SENT_TO_CONTRACTOR')); ?></th>';
							table += '<th class="line"><?= mb_strtoupper(TRANS('INVOICE_SENT_TO_PAYMENT')); ?></th>';
						table += '</tr>';

					table += '</thead>';
					table += '<tbody>';
					for (var i in data['invoices']) {

						if (data['invoices'][i].invoice_number !== undefined) {
							table += '<tr>';

							table += '<td class="line row-id">' + data['invoices'][i].invoice_id + '</td>';
							table += '<td class="line">' + data['invoices'][i].contractor_company_name + '</td>';
							table += '<td class="line">' + data['invoices'][i].contractor_organization_name + '</td>';
							table += '<td class="line"><span class="invoice-id" data-invoice="' + data['invoices'][i].invoice_id + '">' + data['invoices'][i].invoice_number + '</span></td>';
							
							table += '<td class="line"><a onClick="redirect(\'../../includes/functions/download_invoice_files.php?file_id=' + data['invoices'][i].file_id + '\');" href="javascript:void(0);">' + data['invoices'][i].filename + '</a></td>';
							
							table += '<td class="line" data-sort="' + data['invoices'][i].issuance_date	 + '">' + data['invoices'][i].issuance_date_br	 + '</td>';
							table += '<td class="line" data-sort="' + data['invoices'][i].due_date + '">' + data['invoices'][i].due_date_br + '</td>';
							table += '<td class="line" data-sort="' + data['invoices'][i].total_price + '">' + data['invoices'][i].total_price_br + '</td>';

							table += '<td class="line">' + data['invoices'][i].sent_to_contractor + '</td>';
							table += '<td class="line">' + data['invoices'][i].sent_to_paying + '</td>';
							
							table += '</tr>';
						}
					}
					table += '</tbody>';
					
					table += '</table>';

					disableSendingButtons();

					$('#start_due_date_hidden').val(data.start_due_date_criteria);
					$('#end_due_date_hidden').val(data.end_due_date_criteria);

					$('#divListResults').html(table);
					$("#idSubmit").prop("disabled", false);
				}
			});
		}



		function hasDuePeriod() {
			if ($('#start_due_date').val() == '' || $('#end_due_date').val() == '') {
				return false;
			} else {
				return true;
			}
		}

		/* Só habilitará o envio para pagamento se os filtros de data de vencimento forem preenchidos */
		function toggleBtSendToPayment() {
			var btSendToPayment = $('#bt_send_to_payment');
			
			if (hasDuePeriod()) {
				btSendToPayment.attr('disabled', false);
			} else {
				btSendToPayment.attr('disabled', true);
			}
		}

		function disableSendingButtons() {
			$('#bt_send_to_contractor').attr('disabled', true);
			$('#bt_send_to_payment').attr('disabled', true);
		}


		function deselectAll() {
            $('#table_invoices').DataTable().columns().checkboxes.deselectAll();
        }

		function getFlashMessage() {
            $.ajax({
                url: './get_flash_message.php',
                method: 'POST',
            }).done(function(response) {
                if (response.length > 0) {
                    $('#div_flash').html(response);
                }
            })
        }

	</script>
</body>

</html>