<?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 = "";


?>
<!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/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/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('INVOICES_SEARCH'); ?></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>

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

                    
                    
					<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"><?= TRANS('BT_OK'); ?></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="divListResults"></div>
	</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 type="text/javascript" charset="utf8" src="../../includes/components/datatables/datatables.js"></script>
	<script type="text/javascript">
		$(function() {

            $('.bs-select').selectpicker({
				/* placeholder */
				title: "<?= TRANS('SEL_SELECT', '', 1); ?>",
				liveSearch: true,
				liveSearchNormalize: 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() {
                $('#table_invoices').DataTable({
                    language: {
                        url: "../../includes/components/datatables/datatables.pt-br.json",
                    },
                    paging: true,
                    deferRender: true,
                    order: [0, 'DESC'],
                });

                // $('a').css('cursor', 'pointer');
            }, {
                target: document.getElementById('divListResults'),
            });

        
			
            $('input, select, textarea').on('change', function() {
				$(this).removeClass('is-invalid');
			});
			$('#idSubmit').on('click', function(e) {
				e.preventDefault();
				var loading = $(".loading");
				$(document).ajaxStart(function() {
					loading.show();
				});
				$(document).ajaxStop(function() {
					loading.hide();
				});

                // var form = $('form').get(0);
				$("#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);
					} else {
                        // var location = 'show_users_by_asset_tag.php?asset_id=' + data.asset_id;
						// window.location.href = location;
                        
                        
                        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 += '';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('CONTRACTOR')); ?></td>';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('TICKET_NUMBER')); ?></td>';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('DOCUMENT')); ?></td>';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('ISSUANCE_DATE')); ?></td>';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('DUE_DATE')); ?></td>';
                                table += '<td class="line"><?= mb_strtoupper(TRANS('TOTAL_PRICE')); ?></td>';
                            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">' + data['invoices'][i].contractor_company_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 += '</tr>';
                            }
                        }
                        table += '</tbody>';
                        
                        table += '</table>';

                        $('#divListResults').html(table);
                        $("#idSubmit").prop("disabled", false);
                        // console.log(response);
					}
				});
				return false;
            });
 
            
			$('#bt-cancel').on('click', function() {
				var url = '<?= $_SERVER['PHP_SELF'] ?>';
				$(location).prop('href', url);
			});
		});

	</script>
</body>

</html>