<?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'];


?>
<!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/datatables/datatables.min.css" />
    <link rel="stylesheet" type="text/css" href="../../includes/css/my_datatables.css" />
	<link rel="stylesheet" type="text/css" href="../../includes/css/switch_radio.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/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" />

    <style>

        caption {
            /* caption-side: top; */
            line-height: 1.8em;
        }

        caption.title {
            caption-side: top;
            /* font-size: large; */
        }

        span.title {
            font-size: large;
        }
        .chart-container {
            position: relative;
            /* height: 100%; */
            max-width: 100%;
            margin-left: 10px;
            margin-right: 10px;
            margin-bottom: 30px;
        }


        .flex-child-child {
            /* padding-right: 5px; */
            /* padding-bottom: 5px; */
            position: relative;
        }

        .row-card {
            position: relative;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding-top: 20px;
        }

        .row-card .card-title {
            position: absolute;
            top: -1px;
            left: 5px;
            z-index: 1;
            font-size: 12px;
            font-weight: bold;
            color: #48606B;
        }


    </style>

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

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


    <div class="container">
        <h5 class="my-4"><i class="fas fa-mail-bulk text-secondary"></i>&nbsp;<?= TRANS('SEND_EMAIL_BATCH'); ?></h5>
        <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" style="position:relative">
                        <iframe id="ticketsInfo"  frameborder="0" style="position:absolute;top:0px;width:100%;height:100vh;"></iframe>
                    </div>
                </div>
            </div>
        </div>

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


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

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


                    <label for="template" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('COL_MODEL'); ?></label>
                    <div class="form-group col-md-10">
                        <select class="form-control bs-select" id="template" name="template">
                            <option value="" selected><?= TRANS('SEL_SELECT'); ?></option>
                            <?php
                                $templates = getMailTemplates($conn, null, 4);
                                foreach ($templates as $tpl) {

                                    ?>
                                    <option data-subtext="<?= $tpl['description']; ?>" value="<?= $tpl['tpl_cod']; ?>"
                                    ><?= $tpl['tpl_sigla']; ?></option>
                                    <?php
                                }
                            ?>
                        </select>
                    </div>

                    <label for="number_of_recipients" class="col-md-2 col-form-label col-form-label-sm text-md-right"><?= TRANS('NUMBER_OF_RECIPIENTS'); ?></label>
                    <div class="form-group col-md-10">
                        <input type="number" min="1" class="form-control bs-select" id="number_of_recipients" name="number_of_recipients" />
                    </div>

                    <label class="col-md-2 col-form-label col-form-label-sm text-md-right" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="<?= TRANS('HELPER_DISABLE_USERS'); ?>"><?= firstLetterUp(TRANS('DISABLE_USERS')); ?></label>
					<div class="form-group col-md-4 ">
						<div class="switch-field">
							<?php
							$yesChecked = "";
							$noChecked = "checked";
                            $disableUsersDefaultValue = (!empty($yesChecked) ? 'yes' : 'no');
							?>
							<input type="radio" id="disable_users" name="disable_users" value="yes" <?= $yesChecked; ?> />
							<label for="disable_users"><?= TRANS('YES'); ?></label>
							<input type="radio" id="disable_users_no" name="disable_users" value="no" <?= $noChecked; ?> />
							<label for="disable_users_no"><?= TRANS('NOT'); ?></label>
						</div>
					</div>

                    <label class="col-md-2 col-form-label col-form-label-sm text-md-right" data-toggle="popover" data-placement="top" data-trigger="hover" data-content="<?= TRANS('HELPER_REPLIES_OPEN_TICKET'); ?>"><?= firstLetterUp(TRANS('REPLIES_OPEN_TICKET')); ?></label>
					<div class="form-group col-md-4 ">
						<div class="switch-field">
							<?php
							$yesChecked = "";
							$noChecked = "checked";
                            $repliesOpenTicketDefaultValue = (!empty($yesChecked) ? 'yes' : 'no');
							?>
							<input type="radio" id="replies_open_ticket" name="replies_open_ticket" value="yes" <?= $yesChecked; ?> />
							<label for="replies_open_ticket"><?= TRANS('YES'); ?></label>
							<input type="radio" id="replies_open_ticket_no" name="replies_open_ticket" value="no" <?= $noChecked; ?> />
							<label for="replies_open_ticket_no"><?= TRANS('NOT'); ?></label>
						</div>
					</div>




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

                        <input type="hidden" name="action" value="search">
                        <button type="submit" id="render_form" name="render_form" class="btn btn-primary btn-block"><i class="fas fa-cog"></i>&nbsp;<?= TRANS('GENERATE_SENDING_FORM'); ?></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>
        <div class="container" id="divResult"></div>
        
        <form method="post" action="<?=$_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" id="formSubmit">
            <input type="hidden" name="selected_template" id="selected_template">
            <input type="hidden" name="disable_users_value" id="disable_users_value" value="<?= $disableUsersDefaultValue; ?>">
            <input type="hidden" name="replies_open_ticket_value" id="replies_open_ticket_value" value="<?= $repliesOpenTicketDefaultValue; ?>">
            <input type="hidden" name="original_bt_text" id="original_bt_text" value="<?= TRANS('SEND_EMAILS'); ?>">
            <input type="hidden" name="processing_bt_text" id="processing_bt_text" value="<?= TRANS('PROCESSING_SEND_EMAILS'); ?>">
            <div class="container" id="divFormRendered"></div>
        </form>
        
        
    <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 type="text/javascript" charset="utf8" src="../../includes/components/datatables/datatables.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'>
        $(function() {
            
            $.fn.selectpicker.Constructor.BootstrapVersion = '4';
            $('.bs-select').selectpicker({
                /* placeholder */
                title: "<?= TRANS('ALL', '', 1); ?>",
                showSubtext: true,
                liveSearch: true,
                liveSearchNormalize: 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'
			});

            $('[name="disable_users"]').on('change', function() {
				if ($(this).val() == "no") {
                    $('#disable_users_value').val('no');
                } else {
                    $('#disable_users_value').val('yes');
                }
            });

            $('[name="replies_open_ticket"]').on('change', function() {
				if ($(this).val() == "no") {
                    $('#replies_open_ticket_value').val('no');
                } else {
                    $('#replies_open_ticket_value').val('yes');
                }
            });



            $('#render_form').on('click', function(e) {
                e.preventDefault();
                var loading = $(".loading");
                $(document).ajaxStart(function() {
                    loading.show();
                });
                $(document).ajaxStop(function() {
                    loading.hide();
                });

                $('#selected_template').val($('#template').val());

                $.ajax({
					url: './render_batch_fields_from_template.php',
					method: 'POST',
					data: $('#formRender').serialize(),
					// dataType: 'json',
				}).done(function(data) {
					$('#divFormRendered').html(data);
				});
				return true;
			});


            var obs = $.initialize(".after-dom-ready", function() {
                
                $('.bs-select').selectpicker({
                    /* placeholder */
                    title: "<?= TRANS('SEL_SELECT', '', 1); ?>",
                    // showSubtext: true,
                    liveSearch: true,
                    liveSearchNormalize: true,
                    liveSearchPlaceholder: "<?= TRANS('BT_SEARCH', '', 1); ?>",
                    noneResultsText: "<?= TRANS('NO_RECORDS_FOUND', '', 1); ?> {0}",
                    style: "",
                    styleBase: "form-control ",
                });
                
                $('.selected-user').on('change', function() {
                    
                    if ($(this).attr('id')) {
                        let elementID = $(this).attr('id');
                        let iterationID = elementID.split('_')[1];
                        let email = $(this).find(':selected').data('email');
                        let userName = $(this).find(':selected').data('name');
                        $('#business_email_' + iterationID).val(email);
                        
                        /* Ver se existe um campo chamado 'nome_usuario' */
                        if (fieldExists('nome_usuario')) {
                            // $('#nome_usuario_' + iterationID).val($(this).find(':selected').text());
                            $('#nome_usuario_' + iterationID).val(userName);
                        }
                    }
                });

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



            var obsFiles_add = $.initialize("#add_button_0", function() {
                
                /* Permitir a replicação do campo de input file */
                var maxField = 30; //Input fields increment limitation
                var wrapper = $('.field_wrapper'); //Input field wrapper

                var fieldHTML = '<div class="input-group my-1 d-block"><div class="input-group-prepend"><div class="input-group-text"><a href="javascript:void(0);" class="remove_button"><i class="fa fa-minus"></i></a></div><div class="custom-file"><input type="file" class="custom-file-input" name="anexo[]" lang="br"><label class="custom-file-label text-truncate"><?= TRANS('CHOOSE_FILE', '', 1); ?></label></div></div></div></div>';

                var x = 1; //Initial field counter is 1

                $(wrapper).on('click', '.add_button', function(e) {
                    e.preventDefault();
                    if (x < maxField) {
                        x++; 
                        $(this).parent('div').parent('div').parent('div').append(fieldHTML);
                        
                        var nearestInputFile = $(this).parent('div').parent('div').parent('div').find('input[type=file]')[0].getAttribute('name');
                        console.log ('Name: ' + nearestInputFile);
                        
                        /* Selecionar o elemento de name='anexo[]' */
                        $('input[name="anexo[]"]').attr('name', nearestInputFile);
                    }
                });


                //Once remove button is clicked
                $(wrapper).on('click', '.remove_button', function(e) {
                    e.preventDefault();
                    $(this).parent('div').parent('div').parent('div').remove(); //Remove field html
                    x--; //Decrement field counter
                });

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


            /* Adicionei o mutation observer em função dos elementos que são adicionados após o carregamento do DOM */
            var obs = $.initialize(".custom-file-input", function() {
                $('.custom-file-input').on('change', function() {
                    let fileName = $(this).val().split('\\').pop();
                    $(this).next('.custom-file-label').addClass("selected").html(fileName);
                });

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




            var obsForm = $.initialize("#process-messages", function() {
                
                $('#process-messages').on('click', function(e) {
                    e.preventDefault();

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

                    var form = $('form').get(1);
                    $("#process-messages").prop("disabled", true);
                    $("#process-messages").html('<i class="fa fa-circle-notch fa-pulse"></i>&nbsp;' + $('#processing_bt_text').val());

                    $.ajax({
                        url: './send_batch_emails_from_template_process.php',
                        method: 'POST',

                        data: new FormData(form),
                        // data: $('#formSubmit').serialize(),
                        dataType: 'json',

                        cache: false,
                        processData: false,
                        contentType: false,


                    }).done(function(data) {
                        
                        $("#process-messages").prop("disabled", false);
                        $("#process-messages").html('<i class="fa fa-paper-plane"></i>&nbsp;' + $('#original_bt_text').val());

                        if (!data.success) {
                            $('#divResult').html(data.message);
                            
                            $('input, select, textarea').removeClass('is-invalid');
                            if (data.field_id != "") {
                                $('#' + data.field_id).focus().addClass('is-invalid');
                            }
                        } else {
                            // $('#divResult').html(data.message);
                            $('#divFormRendered').html(data.message);
                            $('input, select, textarea').removeClass('is-invalid');
                            return true;
                        }

                        
                        // $('#divFormRendered').html(data);
                        // console.log(data);
                    });
                    return true;
                });

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


        });


        function fieldExists(fieldName) {
            var field = document.querySelector('input[name="' + fieldName + '[]"]');
            if (field) {
                return true;
            } else {
                return false;
            }
        }

    </script>
</body>

</html>