<?php
require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php")
?>
<?php
if (isset($_POST["btBuscar"])) {
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(sqlerror());
    mysql_select_db($dbname, $conn);
    if (isset($_POST["login"])) {
        $result = mysql_query("SELECT *,DATE_FORMAT(cmum_udb.expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br,DATEDIFF(cmum_udb.expiredate,cmum_udb.added) as teste_ver FROM cmum_udb WHERE name LIKE '%{$_POST["login"]}%' AND addedby='{$_SESSION["adminid"]}'");
    }
    if (isset($_POST["data_inicio"]) && isset($_POST["data_final"])) {
        //SELECT * FROM cmum_udb WHERE expiredate BETWEEN '{$_POST["data_inicio"]}' AND '$_POST["data_final"]}'
        $result = mysql_query("SELECT *,DATE_FORMAT(cmum_udb.expiredate,'%d/%m/%Y %H:%i:%s') as expiredate_br,DATEDIFF(cmum_udb.expiredate,cmum_udb.added) as teste_ver FROM cmum_udb WHERE expiredate BETWEEN '{$_POST["data_inicio"]}' AND '{$_POST["data_final"]}' AND addedby='{$_SESSION["adminid"]}'");
    }
}
if (isset($_GET['preparar_envio'])) {

    //var_dump($_POST);
    //exit();
    $dados['modelo_email'] = $_POST['modelo_email'];
    $dados['emails'] = $_POST['emails'];
    $dados['ids'] = $_POST['ids'];
    $dados['aids'] = $_POST['aids'];

    $p = base64_url_encode(json_encode($dados));
    $ret["url"] = "enviaremail.php?p=" . urlencode($p);
    echo json_encode($ret);
    exit();
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <title><?php print($longtitle); ?></title>
            <link rel="shortcut icon" href="favicon.ico"/>
            <link rel="apple-touch-icon" href="favicon.png"/>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css" />            
            <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
            <script>
                $(function() {
                    $("#data_inicio").datepicker({
                        dateFormat: "yy-mm-dd 00:00:00"
                                /*showOn: "button",
                                 buttonImage: "images/calendar/calendar.gif",
                                 buttonImageOnly: true*/
                    });
                    $("#data_final").datepicker({
                        dateFormat: "yy-mm-dd 23:59:59"
                                /*showOn: "button",
                                 buttonImage: "images/calendar/calendar.gif",
                                 buttonImageOnly: true*/
                    });
                });
            </script>            
            <style>
                #tabList tr:nth-child(odd) { background-color: white; }
                #tabList tr:nth-child(even) { background-color: antiquewhite; }
                #tabList td{
                    text-align: center;

                }
                #tabList thead{
                    background-color: #D1EDFF;
                }

            </style>
    </head>
    <body>                      
        <?php require_once 'topo.php'; ?>
        <div style="width: 980px; border: solid 0px; margin: auto;padding-top: 10px; padding-bottom: 20px; padding-left: 1px; padding-right: 1px">
            <a href='emails_notificacoes.php'>< Voltar</a>
            <br/><br/>
            <table width="980" border="0" valign="top" cellpadding="2" cellspacing="1" id="">
                <tr>
                    <td><fieldset>
                            <legend>Enviar email e notificações</legend>
                            <form method="post">
                                <table>
                                    <td><label>Buscar Por:</label></td>
                                    <td><select name="selBusc" class="form-control" onchange="this.form.submit();">
                                            <option>--Selecione--</option>
                                            <option value="0" <?php if (isset($_POST["selBusc"]) && $_POST["selBusc"] == 0) echo "selected=''"; ?>>Login</option>
                                            <option value="1" <?php if (isset($_POST["selBusc"]) && $_POST["selBusc"] == 1) echo "selected=''"; ?>>Data de Vencimento</option>
                                        </select></td>
                                    <?php if (isset($_POST["selBusc"]) && $_POST["selBusc"] == 0): ?>
                                        <td>Digite o Login:</td><td><input type="text" name="login" class="form-control" value="<?php echo isset($_POST["login"]) ? $_POST["login"] : ""; ?>"/></td><td><input type="submit" value="Buscar" name="btBuscar" class="btn btn-default"/></td>
                                    <?php endif; ?>
                                    <?php if (isset($_POST["selBusc"]) && $_POST["selBusc"] == 1): ?>
                                        <td>Data Inicio:</td><td><input type="text" name="data_inicio" id="data_inicio" class="form-control" value="<?php echo isset($_POST["data_inicio"]) ? $_POST["data_inicio"] : ""; ?>"/></td>
                                        <td>Data Final:</td><td><input type="text" name="data_final" id="data_final" class="form-control" value="<?php echo isset($_POST["data_final"]) ? $_POST["data_final"] : ""; ?>"/></td>
                                        <td><input type="submit" value="Buscar" name="btBuscar" class="btn btn-default"/></td>
                                    <?php endif; ?>
                                </table>
                            </form>
                        </fieldset>
                    </td>
                </tr>
            </table>
            <?php if (isset($result) && mysql_num_rows($result) > 0): ?>
                <!-- <form method="post" id="formListEmail">-->
                <table width="980" border="0" valign="top" cellpadding="5" cellspacing="0" id="" class="table table-striped table-bordered" style="font-size: 8pt">
                    <thead>
                        <tr style="background-color: ">
                            <th><input type="checkbox" class="sel-td-emails"/>Marcar Todos</th>
                            <th>ID</th>
                            <th>Login</th>
                            <th>Nome</th>
                            <th>Email</th>
                            <th>Data de Vencimento</th>
                        </tr>
                    </thead>
                    <tbody>                    
                        <?php
                        while ($lineUserEmails = mysql_fetch_assoc($result)):

                            if ($lineUserEmails['teste_ver'] == 1) {
                                $lineUserEmails["name"] .= '<sup><span class="label label-info" style="font-size:7pt">Teste</span></sup>';
                            }
                            ?>
                            <tr>
                                <td><input type="checkbox" name="email[]" value="<?php echo $lineUserEmails["email"] ?>" class="sel-email" _id="<?php echo $lineUserEmails["id"] ?>" _aid="<?php echo $lineUserEmails["addedby"] ?>"/></td>
                                <td><?php echo $lineUserEmails["id"] ?></td>
                                <td><?php echo $lineUserEmails["name"];
                            ?></td>
                                <td><?php echo $lineUserEmails["displayname"] ?></td>
                                <td>
                                    <!--<input type="hidden" name="email[]" value="<?php echo $lineUserEmails["id"]; ?>"/>--->
                                    <?php echo $lineUserEmails["email"] ?>
                                </td>
                                <td><?php echo $lineUserEmails["expiredate_br"] ?></td>
                            </tr>
                        <?php endwhile; ?>                    
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="6" style="text-align: right;">Total de Registros:&nbsp;<?php echo mysql_num_rows($result); ?></td>
                        </tr>
                        <tr>
                            <td colspan="6">
                                <label style="font-size: 8pt">Modelo de Email:</label>
                                <select class="form-control" style="width: 30%" id="sel-modelo-email">
                                    <?php
                                    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(sqlerror());
                                    mysql_select_db($dbname, $conn);
                                    //Modelos emails revendas
                                    $SQL = "SELECT * FROM cmum_modelos_email_rev WHERE aid = '{$_SESSION['adminid']}'";
                                    $rs = mysql_query($SQL);
                                    $modelos_email_rev = array();
                                    while ($row = mysql_fetch_assoc($rs)) {
                                        $modelos_email_rev[] = $row;
                                    }
                                    //Modelos emails sistema
                                    $SQL = "SELECT * FROM cmum_modelos_email WHERE permite_acesso = 1";
                                    if ($_SESSION['adminlevel'] == "0") {
                                        $SQL = "SELECT * FROM cmum_modelos_email";
                                    }
                                    $rs = mysql_query($SQL);
                                    while ($row = mysql_fetch_assoc($rs)) {
                                        $modelos_email_sistema[] = $row;
                                    }
                                    ?>
                                    <?php if (count($modelos_email_rev) > 0): ?>
                                        <option value="-">--- Modelos Personalizados ---</option>
                                        <?php foreach ($modelos_email_rev as $modelo) : ?>
                                            <option value="r:<?php echo $modelo['id'] ?>"><?php echo $modelo['nome_modelo'] ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                    <?php if (count($modelos_email_sistema) > 0): ?>
                                        <option value="-">--- Modelos do Painel ---</option>
                                        <?php foreach ($modelos_email_sistema as $modelo) : ?>
                                            <option value="s:<?php echo $modelo['id'] ?>"><?php echo $modelo['nome_modelo'] ?></option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </td>                                            
                        </tr>
                        <tr>
                            <td colspan="6">
                                <!--<input type="submit" value="Enviar Email" class="btn btn-success" id="enviar-email"> -->
                                <button class="btn btn-success" id="enviar-email">Enviar email</button>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            <?php endif; ?>
        </div>
        <?php
        require("includes/footer.php");
        ?>
        <!--<script src="js/func.js"></script>-->
        <script>
            $(document).ready(function() {
                /*$("#formListEmail").submit(function(event) {
                 event.preventDefault();
                 var strMail = new String("");
                 $(this).find(':hidden').each(function() {
                 strMail += $(this).val() + ";";
                 });
                 strMail.toString().substr(0, (strMail.toString().length - 1))
                 window.open("enviaremailvenc.php?p=" + base64_encode(strMail.toString().substr(0, (strMail.toString().length - 1))), "Enviar Emails", 'width=400,height=350,toolbar=no,scrollbars=no,resizable=no,location=no');
                 
                 });*/

                //Checkbox seleciona todos.
                $('.sel-td-emails').on('click', this, function() {
                    var cond = $(this).prop('checked');
                    if (cond == true) {
                        $.each($('.sel-email'), function() {
                            $(this).prop('checked', true);
                        });
                    }
                    if (cond == false) {
                        $.each($('.sel-email'), function() {
                            $(this).prop('checked', false);
                        });
                    }
                });
                $('#enviar-email').on('click', this, function() {
                    if ($('.sel-email:checked').length == 0) {
                        alert('Nenhum login selecionado.');
                        return false;
                    }
                    if ($('#sel-modelo-email').val() == "-") {
                        alert('Você deve selecionar um modelo de email para envio.');
                        return false;
                    }
                    var _emails = [];
                    var _ids = [];
                    var _aids = [];
                    var erro_email_vazios = 0;
                    $.each($('.sel-email:checked'), function() {
                        //alert();                                    
                        if ($(this).val() == "") {
                            alert('Na seleção existe email em branco.');
                            erro_email_vazios = 1;
                            return false;
                        } else {
                            _emails.push($(this).val());
                            _ids.push($(this).attr('_id'));
                            _aids.push($(this).attr('_aid'));
                        }
                    });
                    if (erro_email_vazios == 0) {
                        $.ajax({
                            type: "POST",
                            url: "emailsclientesvenc.php?preparar_envio=true",
                            data: {
                                'emails[]': _emails,
                                'ids[]': _ids,
                                'aids[]': _aids,
                                modelo_email: $('#sel-modelo-email').val()

                            },
                            dataType: 'json'
                        })
                                .done(function(ret) {
                                    if (ret.url) {
                                        window.open(ret.url, "Envio de emails", 'width=400,height=350');
                                    }
                                });
                    }

                });
            });

        </script>
    </body>
</html>